如何对调用 void 方法的方法进行单元测试?
How to unit test a method which calls a void method?
我遇到了一个场景单元测试的基本问题,希望得到帮助。
我有一个 class MyService
,它调用 MyRemovalService
在数据库中将标志设置为 true。
@Slf4j
@Service
@RequiredArgsConstructor
public class MyService {
private final MyRemovalService myRemovalService;
private final MyRepository myRepository;
public void setFlag() {
final List<String> records = myRepository.getData(ENUM_1, ENUM_2, ENUM_3);
records.forEach(MyRemovalService::removeData);
}
}
我的测试:
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
private MyRemovalService myRemovalService;
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
@Test
void testMyUseCase() {
when(myRepository.getData(any(), any(), any())).thenReturn(List.of("Test1", "Test2"));
myService.setFlag();
}
}
我被要求测试并检查 (MyRemovalService::removeData)
是否正在调用相关数据。
由于 return 类型为 void,我该如何测试它?
您使用验证方法:
verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));
Mockito 允许定义 ArgumentCaptors
允许您捕获调用模拟对象的参数方法:
var objectRequestedForRemovalCapture = ArgumentCaptor.forClass(String.class);
verify(myRemovalService).removeData(objectRequestedForRemovalCapture.capture());
var results = objectRequestedForRemovalCapture.getAllValues();
//and do the verification on your list of objects
我遇到了一个场景单元测试的基本问题,希望得到帮助。
我有一个 class MyService
,它调用 MyRemovalService
在数据库中将标志设置为 true。
@Slf4j
@Service
@RequiredArgsConstructor
public class MyService {
private final MyRemovalService myRemovalService;
private final MyRepository myRepository;
public void setFlag() {
final List<String> records = myRepository.getData(ENUM_1, ENUM_2, ENUM_3);
records.forEach(MyRemovalService::removeData);
}
}
我的测试:
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
private MyRemovalService myRemovalService;
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
@Test
void testMyUseCase() {
when(myRepository.getData(any(), any(), any())).thenReturn(List.of("Test1", "Test2"));
myService.setFlag();
}
}
我被要求测试并检查 (MyRemovalService::removeData)
是否正在调用相关数据。
由于 return 类型为 void,我该如何测试它?
您使用验证方法:
verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));
Mockito 允许定义 ArgumentCaptors
允许您捕获调用模拟对象的参数方法:
var objectRequestedForRemovalCapture = ArgumentCaptor.forClass(String.class);
verify(myRemovalService).removeData(objectRequestedForRemovalCapture.capture());
var results = objectRequestedForRemovalCapture.getAllValues();
//and do the verification on your list of objects