lundi 28 septembre 2015

mocked repository object returns empty results from controller testcase?

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 it's call to EmployeeCompositeService method than it's call to EmployeeService method in this service method

has a repository call that call mocked in this controller test method. When I debug it returns empty list. What I did wrong in my controller testcase. Can you please help me Thanks in Advance.

Aucun commentaire:

Enregistrer un commentaire