0

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

}

I have a service call in side EmployeeController i.e employeeCompositeService.getEmployees(String name) So I have mocked in the EmployeeControllerTestcase i.e @Mock EmployeeCompositeService employeeCompositeService; when I run the controller testcase it invokes further services calls and repository and hit the database So I does want to call those services returns the results form my employeeCompositeService.getEmployees(String name) from controller. Can you please tell me what I did wrong in the above code Thanks in Advance

Venkata Rama Raju
  • 1,325
  • 2
  • 10
  • 15
  • possible duplicate of [mocked repository object returns empty results from controller testcase?](http://stackoverflow.com/questions/32820404/mocked-repository-object-returns-empty-results-from-controller-testcase) – Yosef Weiner Sep 28 '15 at 22:10
  • I have changed the logic to mock only the service inside of EmployeeController and return results. I doesn't want to mock employeeService and employeeRepository I have tried with the updated code in the above post but no luck. Can you please tell me what I did wrong – Venkata Rama Raju Sep 29 '15 at 10:10

0 Answers0