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