未通过控制器测试用例模拟返回空对象的存储库对象是以下代码
@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(&#34; mike&#34;)所以我不想访问数据库所以我在我的Controller方法中嘲笑,即testGetEmployees()
当我运行这个测试用例时,它会调用EmployeeController方法并调用EmployeeCompositeService方法,而不是调用此服务方法中的EmployeeService方法
有一个存储库调用,在此控制器测试方法中调用mock。当我调试它时返回空列表。我在控制器测试用例中做错了什么。 能否请你帮我谢谢。