lundi 28 septembre 2015

how to write mokito test for repository from controller test case

Repository object not mocked from controller testcase return empty object here is the below code

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

}

I have repository call to invoke findByName("mike") in employeeServiceImpl So I doesn't want to hit the database So I have mocked in my Controller method i.e testGetEmployees()

When I run this test case it invoke EmployeeController method and than it's call to EmployeeCompositeService method than it's call to EmployeeService method in this service method has a repository call

i.e employeeCompositeService.getEmployees(String name) and than employeeService.getEmployeesByName(String name) in this method has logic like to hit the data base employeeRepository.findByName("Mike"); that call mocked in this controller test method.

When I debug it returns empty list of objects. How to writer test case from contorller to mock repositoy call to avoid database hit. and What I did wrong in my controller testcase. Can you please help me Thanks in Advance.

Aucun commentaire:

Enregistrer un commentaire