如何使用junit和mockit编写void delete方法的单元测试?


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来删除。

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

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

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

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

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

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

参见:为什么Mockito不模拟静态方法?

最新更新