如何使用 junit 和 mockito 为 void delete 方法编写单元测试?
How to write unit test for void delete method using junit and mockito?
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
这样的静态存储库。静态方法很难模拟。使用非静态方法并使用依赖注入注入 CarRepository
的实例。然后你可以轻松地注入模拟对象。
如果您坚持使用静态方法,还有其他解决方案,例如 PowerMock 库。但我不推荐它。
另请参阅:
Why doesn't Mockito mock static methods?
首先,不要在你的 CarRepository
上使用静态方法,创建一个接口:
interface CarRepository {
Car findById(long id);
void save(Car car);
...
}
并将此实例传递给您要测试的 class:
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);
}
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
这样的静态存储库。静态方法很难模拟。使用非静态方法并使用依赖注入注入 CarRepository
的实例。然后你可以轻松地注入模拟对象。
如果您坚持使用静态方法,还有其他解决方案,例如 PowerMock 库。但我不推荐它。
另请参阅: Why doesn't Mockito mock static methods?
首先,不要在你的 CarRepository
上使用静态方法,创建一个接口:
interface CarRepository {
Car findById(long id);
void save(Car car);
...
}
并将此实例传递给您要测试的 class:
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);
}