您能否建议我如何通过 Mockito 检查函数调用是否参数也是函数。
我们假设三个服务类别,为简洁起见省略了详细信息
class SomeService {
public void process(SomeType type1) {...}
public void process(AnotherType type2) {...}
}
class AnotherService {
public SomeType anotherProcess(args) {...}
}
class ServiceForTests {
public void mainProcess() {
someService.process(anotherService.anotherProcess(args))
}
}
我需要检查 process 是否在 ServiceForTests.mainProcess 中调用。
代码 verify(someService).process(any(SomeType.class)) 由于参数差异而失败。想要:任何 SomeType,但实际:anotherService.anotherProcess。
我无法使用 verify(someService).process(any()) 进行测试,因为 SomeService.process 已过载。
请确认您是否正确执行了所有操作,或者我可能理解错误了您的问题。
我在本地复制了它,它似乎对我来说没问题。
public class SomeService {
public void process(String T1) {}
public void process(Map<String,String> T2) {}
}
public class AnotherService {
public String anotherProcess() {
return "Hello World";
}
}
public class ServiceForTests {
public SomeService someService;
public AnotherService anotherService;
public ServiceForTests(SomeService someService, AnotherService anotherService) {
this.someService = someService;
this.anotherService = anotherService;
}
public void mainProcess() {
someService.process(anotherService.anotherProcess());
}
}
@ExtendWith(MockitoExtension.class)
public class TestServiceForTests {
ServiceForTests classUnderTest;
@Mock
private SomeService someService;
@Mock
private AnotherService anotherService;
@BeforeEach
public void setUp() {
classUnderTest = new ServiceForTests(someService, anotherService);
}
@Test
public void testMainProcess() {
doReturn("Hello World!")
.when(anotherService)
.anotherProcess();
classUnderTest.mainProcess();
verify(someService)
.process(any(String.class));
}
}