【问题标题】:How to write unit test for void delete method using junit and mockito?如何使用junit和mockito为void delete方法编写单元测试?
【发布时间】:2021-11-17 09:39:51
【问题描述】:
public void delete(Long id){
Optional<Car> optional = CarRepository.findById(id);
if(optional.isPresent()){
    Car car = optional.get();
    car.setActionStatus("DELETE");
    CarRepository.save(car);
}
else{
    throw new CustomException("custom message");
}}

我必须为上面的删除方法编写一个单元测试,这里我们不是删除记录而是我们只是更新 setActionStatus 来删除。

【问题讨论】:

  • 您的项目中是否有一个名为Object 的类不是java.lang.Object
  • 注意:您几乎不应该使用get()。相反,obj = repo.findById(id).orElseThrow(() -&gt; new CustomException());.
  • 是的,我的项目中有一个类名 Object。
  • 这真的很混乱,我建议使用其他名称。

标签: java spring spring-boot junit


【解决方案1】:

首先,不要在CarRepository 上使用静态方法,创建一个接口:

interface CarRepository {
  Car findById(long id);
  void save(Car car);
  ...
}

并将 this 的实例传递给您要测试的类:

class ClassToTest {
  public ClassToTest(CarRepository carRepository) { ... }
  ...
}

现在在您的测试中,您可以使用模拟 CarRepository

...
@Test
void test() {
  // create the mocks we need and set up their behaviour
  CarRepository carRepository = mock(CarRepository.class);
  Car car = mock(Car.class);
  when(carRepository.findById(123)).thenReturn(car);

  // create the instance we will test and give it our mock
  ClassToTest classToTest = new ClassToTest(carRepository);
  classToTest.delete(123);

  // check that the expected methods were called
  verify(car).setActionStatus("DELETE");
  verify(carRepository).save(car);
}

【讨论】:

    【解决方案2】:

    不要使用像CarRepository 这样的静态存储库。静态方法很难模拟。使用非静态方法并使用依赖注入注入CarRepository 的实例。然后,您可以轻松地注入一个模拟对象。

    如果您坚持使用静态方法,还有其他解决方案,例如 PowerMock 库。但我不会推荐它。

    另请参阅: Why doesn't Mockito mock static methods?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 2023-02-17
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多