Spring ブート gradle アプリで REST API をテストしています。@MockBean を使用してモックされたサービスが null を返しています。このモックされたサービスは、サービス クラスに Autowired の Bean がある場合に null を返します (コンストラクター インジェクションを使用しました)。
これがサンプルコードです(コンパイルされていません。理解のためだけです)
@RestController
@RequestMapping("/xxx")
class TestController {
private RetriveDataService retriveDataService;
public TestControllerx(RetriveDataService retriveDataService) {
this.retriveDataService = retriveDataService;
}
@PostMapping(value = "/yyy")
public MyResponseModel myMethod(@RequestBody MyRequestModel model) {
return retriveDataService.retriveData(model);
}
}
@Service
class RetriveDataService {
private TokenService tokenService;
public RetriveDataService(TokenService tokenService) {
this.tokenService = tokenService;
}
public MyResponseModel retriveData(MyRequestModel model) {
String accessToken = tokenService.getToken().getAccessToken();
return retriveData(model, accessToken);
}
}
@RunWith(SpringRunner.class)
@WebMvcTest(TestController.class)
public class TestControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private RetriveDataService retriveDataService;
@Test
public void testRetriveData() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/xxx/yyy").content(objectMapper.writeValueAsString(new MyRequestModel()))
.contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
このテストを実行すると、次の出力が得られます (サービスが別の Bean を必要としない場合、期待される出力が得られます)
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
この応答により、.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); という行で問題に直面しています。また、応答本文をチェックするとき(本文もnullであるため)
問題を再現するためのサンプル プロジェクトはこちら