コントローラーのテストケースからモックされていないリポジトリ オブジェクトは、空のオブジェクトを返します。ここでは、以下のコードを示します。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@WebAppConfiguration
@ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE)
public class EmployeeControllerRealTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Mock
EmployeeRepository employeeRepository;
@InjectMocks
EmployeeCompositeService employeeCompositeService;
@InjectMocks
EmployeeService employeeService;
@InjectMocks
EmployeeController employeeController;
String name = "mike";
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetEmployees() throws Exception {
Mockito.when(employeeRepository.findByName(name)).thenReturn(getEmployees());
String url = URIConstants.ROOT_CONTEXT + URIConstants.EMPLOYEE;
MvcResult result =
mockMvc.perform(post(url)
.contentType(APPLICATION_JSON_UTF8)
.content(convertObjectToJsonBytes(name))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$[0].employeeName").value("Mike"))
.andReturn();
String jsonContent = result.getResponse().getContentAsString();
LOGGER.debug("jsonContent: {}",jsonContent);
}
protected byte[] convertObjectToJsonBytes(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
private List<Employee> getEmployees(){
//here is the logic to get List of employees to return. When the mockito call is invoked.
}
}
employeeServiceImpl で findByName("mike") を呼び出すためのリポジトリ呼び出しがあるので、データベースにアクセスしたくありません。
このテスト ケースを実行すると、EmployeeController メソッドが呼び出され、このサービス メソッドの EmployeeService メソッドの呼び出しよりも EmployeeCompositeService メソッドの呼び出しになります。
このコントローラー テスト メソッドでモックされた呼び出しを呼び出すリポジトリ呼び出しがあります。デバッグすると、空のリストが返されます。コントローラーのテストケースで間違っていたこと。よろしくお願いします。