Junit5 RestTemplateのモック化

今回は、RestTemplateをモック化する方法について調べていこうと思います。

環境

  • Springboot2.5.x
  • Gradle
  • Junit5(Springboot2.2.x以降には入っている)
  • Mockito(Springbootに入っている)
  • Java11
  • Intellij

実装

Service

@Service
public class SomeService {

    @Autowired
    RestTemplate restTemplate;
    
    @Autowired
    HttpHeaders httpHeaders;

    public void someMethod() {
        Map<String, String> someRequest = new HashMap<>();
        someRequest.put("param1", "param1");

        HttpEntity<Map<String, String>> data = new HttpEntity<>(someRequest, httpHeaders);

        SomeResponse someResponse = restTemplate.exchange("url", HttpMethod.POST,  data, SomeResponse.class);
    }
}

TestClass

@SpringBootTest
public class SomeServiceTest {
    @MockBean
    RestTemplate restTemplate;

    @Autowired
    SomeService someServices;

    @Test
    public void someTest() throws Exception {
        SomeResponse expectedResponse = new SomeResponse();
        ResponseEntity<SomeResponse> response = new ResponseEntity<>(expectedResponse, HttpStatus.OK);

        when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.anyString(HttpMethod.class),
                ArgumentMatchers.anyString(HttpEntity.class),
                ArgumentMatchers.anyString(SomeResponse.class)
        )).thenReturn(expectedResponse);

        SomeResponse actualResponse = someService.someMethod();
    }
}
  • Mockito.any()のような書き方もしてみました、うまく行けなかったですが、ArgumentMatchersを使ったらうまくいきました。

ArgumentMatcherはこちらのブログに親切に書いてあるので、ご参考ください。

コメントを残す