没有从控制器测试用例获取服务方法内的存储库调用的模拟对象数据?

时间:2015-09-28 11:39:43

标签: java unit-testing mocking mockito spring-data-jpa

未通过控制器测试用例模拟返回空对象的存储库对象是以下代码

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@WebAppConfiguration
@ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE)
public class EmployeeControllerRealTest {
@Autowired
private WebApplicationContext   webAppContext;
private MockMvc mockMvc;

@Mock
EmployeeCompositeService  employeeCompositeService;


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.
}

}

我在一侧EmployeeController中有一个服务调用,即employeeCompositeService.getEmployees(String name) 所以我在EmployeeControllerTestcase中进行了模拟,即@Mock EmployeeCompositeService employeeCompositeService; 当我运行控制器测试用例时,它会调用更多的服务调用和存储库并命中数据库 所以我确实想要调用那些服务从控制器返回结果形式我的employeeCompositeService.getEmployees(String name)。 你能否告诉我上面代码中我做错了什么,先谢谢

0 个答案:

没有答案