MockMvc を使用して統合テスト ケースを作成し、REST API をテストしています。
RESTAPI の実装内で、RestTemplate (コントローラーから直接ではなく、コントローラーが呼び出す util クラス内から) を内部的に使用して、サード パーティの REST API を呼び出しています。私が (サードパーティの REST API を作成するために) 使用する RestTemplate は、Spring Managed Bean ではなく、RestTemplate restTemplate = new RestTemplate(); としてインスタンス化しています。
restTemplate 呼び出し (postForEntity) をモックしたい。
私は以下のアプローチを試みています:
私のテストクラス-
@ContextConfiguration(locations = {
"classpath:test-applicationContext.xml"
})
@WebAppConfiguration
パブリッククラスMockMVCTest {
private MockMvc mockMvc;
private RestTemplate restTemplate
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
if (!initalized) {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
restTemplate = (RestTemplate)webApplicationContext.getBean("restTemplate");
}
@Test
public void demo() throws Exception {
when(
restTemplate.postForEntity(
eq("thirdpartyuri"),
any(HttpEntity.class),
eq(MyClass.class))).thenReturn(myresponse);
mockMvc.perform(
post("uriExposedbyme")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(MY_PAYLOAD)).andExpect(status().isOk());
}
私のアプリケーションコンテキストでは、次のモックが定義されています。
<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.springframework.web.client.RestTemplate" /> </bean>
しかし、テストケースを実行するとRestTemplateがモックされますが、実行中にRestTemplateへの呼び出しが発生すると、モックresttemplateの代わりに実際のresttemplateが呼び出されます。
テスト ケースの RestTemplate をモックする方法を提案してください。