J'ai écrit mes méthodes de tests de la manière suivante :
package com.openclassrooms.api;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import com.openclassrooms.api.controller.EmployeeController;
import com.openclassrooms.api.service.EmployeeService;
//@WebMvcTest(controllers = EmployeeController.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EmployeeControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private EmployeeService employeeService;
// Test unitaire
// Ont pour vocation à tester uniquement le contenu d’une méthode
@Test
public void testGetEmployees() throws Exception {
mockMvc.perform(get("/employees"))
.andExpect(status().isOk());
}
// Test integration
// Ont pour vocation de tester plus largement une fonctionnalité
@Test
public void testGetEmployee() throws Exception {
mockMvc.perform(get("/employees"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].firstName", is("Nico")));
}
}
Le test sur la méthode testGetEmployees() fonctionne mais le test sur la méthode testGetEmployee() (la deuxième) me renvoie ceci :
java.lang.AssertionError: No value at JSON path "$[0].firstName"
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:302)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:73)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:214)
at com.openclassrooms.api.EmployeeControllerTest.testGetEmployee(EmployeeControllerTest.java:44)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
Caused by: com.jayway.jsonpath.PathNotFoundException: No results for path: $[0]['firstName']
Pourtant, sur Postman, lorsque je fais un GET sur /employees, j'ai bien mon premier employé qui s'appelle Nico (clé firstName) :