3

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.

Venkata Rama Raju
  • 1,325
  • 2
  • 10
  • 15
  • Isn't there a code messup with parenthesis in Mockito.when(employeeRepository.findByName(name).thenReturn(getEmployees()); I think it should be rather Mockito.when(employeeRepository.findByName(name)).thenReturn(getEmployees()); – Nadir Sep 28 '15 at 10:15
  • Sorry, I forget it to write the closing bracket while I was posting the question – Venkata Rama Raju Sep 28 '15 at 10:19
  • Ok, so when you debug what does it say about the repository class? You should see it as something like repositoryEnchncedWithCGLib or similar. You can also verify that your getEmployees returns some values. Normally if method is not mocked you should get null instead of empty list. – Nadir Sep 28 '15 at 10:22
  • After this pice of code is executed i.e employeeRepository.findByName("Mike") in EmployeeServiceImpl it shows empty list even though we mocked in controller test method i.e testGetEmployees() – Venkata Rama Raju Sep 28 '15 at 10:31
  • ok, what about getEmployees()? Did you tried to assign it to local variable at the begining of the test and check what does it contain? Is it not empty? – Nadir Sep 28 '15 at 10:34
  • Yes, It's not empty; getEmployees() method return some static data instead of getting data from database – Venkata Rama Raju Sep 28 '15 at 10:37
  • Ok, my last idea, did you compare the objects in the test case with the ones that are handling the requests? Maybe they're not the same instances because something is wrong with creating the app context or injecting the mocks? – Nadir Sep 28 '15 at 10:42
  • Actually When I debug it calling the right service finally means employeeController.getEmployees(String name) and than employeeCompositeService.getEmployees(String name) and than employeeService.getEmployeesByName(String name) in this method has logic like to hit the data base employeeRepository.findByName("Mike"); When I test this code from EmployeeServiceTest it's working but from controller not mocked with data I tried but no luck – Venkata Rama Raju Sep 28 '15 at 10:55
  • Is there an answer to this question? I'm facing the same issue. The request is getting mocked properly (i.e, no DB calls are made in the backend), but the result list is always empty. – Gowtham Sankaran Apr 30 '21 at 02:54

0 Answers0