I am creating tests for my Springboot application. The application through a Get call, passing my "CarRequest" in the RequestBody
public class CarsRequest implements Serializable {
private String name;
private String plate ;
private String price;
}
it gives me back the car specifications related to that data
{
"name":"",
"plate":"",
"price":"",
"brand":"",
"kilometers":"",
"revisiondate":"",
"owner":""
}
I did this simple test using Mockito but I don't understand why my service is set by default to null, this throws everything in NullPointErexception
public class CarTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CarService service;
@Autowired
ObjectMapper objectMapper;
@Test
public void TestOk() throws Exception{
CarsRequest carsRequest = new CarsRequest();
Car car = new Car();
List<Car> cars = new ArrayList<>();
//septum the fields of cars and add them to the list
cars.add(car);
Mockito.when(
service.getByPlate("bmw",
"TG23IO", "1500")).thenReturn(cars);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/garage/cars").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
String expected = "{name:"bmw","plate":"TG23IO","price":"1500","brand":"POL","kilometers":"80000","revisiondate":"2016-03-15","owner":"JohnLocke"}";
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
}
}
Below I also add my CarService
@Service
public class CarService {
@Autowired
CarRepository carRepository;
@Autowired
ObjectMapper objectMapper;
public List<Cars> getByContratto(String name, String plate, String price) throws JsonProcessingException {
//some code, extraction logic
return cars;
}
}
The application works perfectly, only the test does not work. Being a novice in test writing I can't figure out what the null on my Carservice is due to. If needed, I can include the Controller Get and the repository as well, but I don't think they can help