Search code examples
spring-bootjunitmockito

No value present, when test method getEntityById?


Have next problem, when i test method i have exception NoSuchElementException - > no value present

My Mock

@InjectMocks
    private CarServiceImpl carService;
    
    @Mock
    private CarRepository carrepo;

My test

@Test
    void getCarById() {

        Car car = new Car();
        car.setId(1L);
    
        carService.getCarById(1l);
        when(carrepo.findById(1l)).thenReturn(Optional.of(car));
        
        Car actualCar = carService.getCarById(1L);
        Assertions.assertEquals (car, actualCar);
        
}

And Service Layer

@Override
    public Car getCarById(Long id) {
        
        return carrepo.findById(id).get();
    }

if somebody know where is problem, please help me


Solution

  • Not sure what you're trying to accomplish in this test, but you're calling carService.getCarById(1L); BEFORE the Mockito when. You also call it after but I'm guessing that the initial time you call the getCarById(1L) there's no value available hence the no value present message.