未从控制器测试用例模拟的存储库对象返回空对象这里是下面的代码
@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") 所以我不想访问数据库所以我在我的Controller 方法中进行了模拟,即testGetEmployees()
当我运行这个测试用例时,它调用 EmployeeController 方法,它调用 EmployeeCompositeService 方法而不是调用这个服务方法中的 EmployeeService 方法
有一个存储库调用,该调用在此控制器测试方法中被模拟。当我调试它返回空列表。我在控制器测试用例中做错了什么。你能帮我提前谢谢。