英文:
No value present, when test method getEntityById?
问题
有下一个问题,当我测试方法时,出现异常NoSuchElementException - > no value present
我的Mock
@InjectMocks
private CarServiceImpl carService;
@Mock
private CarRepository carrepo;
我的测试
@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);
}
和服务层
@Override
public Car getCarById(Long id) {
return carrepo.findById(id).get();
}
如果有人知道问题出在哪,请帮助我。
英文:
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
答案1
得分: 3
不确定您在这个测试中想要实现什么,但在Mockito的when
之前,您调用了carService.getCarById(1L);
。您之后也调用了它,但我猜您最初调用getCarById(1L)
时可能没有可用的值,因此会出现“no value present”消息。
英文:
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.
答案2
得分: 0
这个测试将由我通过,大家谢谢!
@Test
void getCarById() {
Car car = new Car();
car.setId(1L);
when(carrepo.findById(1l)).thenReturn(Optional.of(car));
Car actualCar = carService.getCarById(1L);
Assertions.assertEquals(car, actualCar);
}
英文:
This test will passed form me, everybody tnx!
@Test
void getCarById() {
Car car = new Car();
car.setId(1L);
when(carrepo.findById(1l)).thenReturn(Optional.of(car));
Car actualCar = carService.getCarById(1L);
Assertions.assertEquals (car, actualCar);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论