I'm currently developping a rest api web service and i have to test them using unit testing, so i cannot figure out how to test the RESTFul API with Spring using Mockito and Junit, first of all i have preapared the class in which i created two method with @Before and @Test, when i turned in debugging mode the method in the the controle "getEmployeDTOList" always return null therefore the console show me Exception NullPointerException.
the class EmployeControllerTest:
@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeControllerTest {
private MockMvc mockMvc;
@InjectMocks
private EmployeController employeController ;
@Mock
private EmployeService employeService ;
@Mock
IConverter converterDto ;
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.standaloneSetup(employeController).build();
}
@Test
public void testgetAllEmployee() throws Exception{
List<Employe> employes= Arrays.asList(
new Employe("BOUROUNIA", "HICHEM", "h.bourounia", "9dfd1be37de137f146ca990310a1483c",true)
,new Employe("BRADAI", "ALI", "a.bradai", "830ddf1b7e8e34261f49d20e5e549338",true) );
when(employeService.findAll()).thenReturn(employes);
mockMvc.perform(get("/employe/dto"))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].nom", is("BOUROUNIA")))
.andExpect(jsonPath("$[0].prenom", is("HICHEM")))
.andExpect(jsonPath("$[0].login", is("h.bourounia")))
.andExpect(jsonPath("$[0].mp", is("9dfd1be37de137f146ca990310a1483c")))
.andExpect(jsonPath("$[0].actif", is(true)))
.andExpect(jsonPath("$[1].nom", is("BRADAI")))
.andExpect(jsonPath("$[1].prenom", is("ALI")))
.andExpect(jsonPath("$[1].login", is("a.bradai")))
.andExpect(jsonPath("$[1].mp", is("830ddf1b7e8e34261f49d20e5e549338")))
.andExpect(jsonPath("$[1].actif", is(true))).andReturn().getResponse().getContentAsString();
verify(employeService,times(1)).findAll();
verifyNoMoreInteractions(employeService);
}
}
this is Employecontroller:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/employe")
public class EmployeController {
@GetMapping("/dto")
public List<EmployeDTO > getEmployeDTOList(){
try {
List<Employe> listemp=employeService.findAll();
return listemp.stream()
.filter(Objects::nonNull)
.map(emp ->converterDTO.convertToDto(emp))
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
error that i got:
java.lang.AssertionError: No value at JSON path "$[0].id": com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['id'] in path $[0] but found 'null'. This is not a json object according to the JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'