【问题标题】:<true> but was: <false> - i don't know how to solve it<true> 但是是:<false> - 我不知道如何解决它
【发布时间】:2021-07-10 23:42:06
【问题描述】:

我正在尝试对某个方法进行测试,但总是遇到同样的错误。

这是我的测试课:

private Car car;

@Autowired
protected CarService carService;

@Mock
private CarRepository carRepository;

@BeforeEach
void setUp() {
    car = new Car();
    car.setId(4L);
    car.setName("test1");
    car.setUrlCar("https://carconfigurator.ferrari.com/assets/cars/portofinom/packages/default/car-ferrari-portofino-m_splash.jpg");
    car.setColor("red");
    carRepository.save(car);
    }

@Test
void getCarById() throws Exception {
    Car res = this.carService.getCarById(4L);
    Assertions.assertTrue(res != null);
}

CarService 类是:

@Autowired
private carRepository carRepository;

public Iterable<Car> getAllCars(){
    return carRepository.findAll();
}
public Car getCarById(Long id){
    return carRepository.findById(id).orElse(null);
}

轨迹是:

org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)

跟踪指向Assertions.assertTrue(res != null); 行,我不知道如何解决该错误。如果你能帮助我,请。

【问题讨论】:

  • 嗯,你有一个空引用,你希望引用汽车。您编写的哪一行代码可以返回 null 而不是对 Car 的引用?
  • 第一步是确保您理解信息。第二步是尝试诊断原因。第三步是与我们分享您的尝试,并具体解释您发现的令人困惑或出乎意料的地方,即具体是什么阻止了您自己修复它。我的猜测是它与CarRepository.findByIdCarRepository.save 的内容有关;但我们只能帮助我们可以看到的代码。我也不清楚你期望.orElse(null) 部分在这里完成什么。在什么条件下它会改变结果?

标签: java spring-boot unit-testing testing


【解决方案1】:

您试图断言 res 不为 null 以避免 NullPointerException;更好的方法是编写不会导致 NullPointerException 的代码。在 Google 上阅读有关 NPE 的信息,上面有 数百万 条帖子。所以摆脱 Assertions.assertTrue(res != null); 并使用类似 try/catch (在谷歌上阅读)或只是

if (res==null){/*code here*/}
else {/*your normal code*/} 

【讨论】:

  • 对。是测试代码。测试代码断言特定结果不能为空是完全合理的,确实值得称赞。
  • 我会添加它谢谢你!但我希望测试成功,而不是得到一个空值作为回报。那么我可能认为我创建的汽车没有正确保存?
  • 如上所述,您的问题可能存在于 getCarById() 中。不管是发现部分,还是原来的保存部分,随便一瞥都说不出来。
  • @riley,可能是这样。 npe 的另一个原因是您可能在创建汽车之前运行了代码。代码会按顺序运行,所以在你尝试访问它之前应该先造一辆车。
【解决方案2】:

你在模拟CarRepository,但没有为它指定任何行为,所以当服务调用它时,模拟返回null。你需要说类似

when(carRepository.findOne(4L)).thenReturn(car)

此外,你应该避免assertTrue,除非你的意思是说“这个对象是真的”。相反,您应该使用更有意义的断言,例如assertNotNull

(您还可以消除对 Spring 的不必要依赖;只需创建您的 CarRepository 模拟并说 new CarService(mockCarRepository)。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-17
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多