没有提供数值,在测试方法`getEntityById`中吗?

huangapple go评论59阅读模式
英文:

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);
    		
    	}

huangapple
  • 本文由 发表于 2023年2月23日 20:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定