Numero 21
Numero 21

Reputation: 265

The service is set to null in my Junit Test

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

Upvotes: 1

Views: 8338

Answers (3)

code_mechanic
code_mechanic

Reputation: 1148

Assuming, you want to test just only your controller layer (Because you are using mockMvc) and you are using Junit 4 (looks like from your code), you should write your test case as follows

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class CarTest {
    @MockBean
    private SomeService service;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldPassTest() {
        BDDAssertions.assertThat(service).isNotNull();
    }
}

Note: In example test method is irrelevant, I added just to to illustrate.

Let us know if it helps.

Upvotes: 2

Vasilis Konstantinou
Vasilis Konstantinou

Reputation: 133

Try adding @RunWith(SpringRunner.class) to your test class.

I suspect that you are using Junit 4 for your tests. In Junit 4 you need to add @RunWith(SpringRunner.class) in your test otherwise all annotations will be ignored. For more info check the docs here . 46.3 Testing Spring Boot Applications is the section that answers your question.

I would however recommend you to migrate to Junit 5 if possible.

@RunWith(SpringRunner.class)
public class CarTest {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private CarService service;
    @Autowired
    ObjectMapper objectMapper;
    @Test
    public void TestOk() throws Exception{
        // code here
        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);
    }
}

Upvotes: 3

vijaydeep
vijaydeep

Reputation: 385

I believe you are trying to test the controller. Hence include the following annotations on top of the test class.

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)

Also, I can see that in the test code CarService is being referred while the service code that is shared contains DocumentService.

Upvotes: 3

Related Questions