我有一个服务 void
我 mock 过的方法。
我想登录或 system.out.println("..")
当 void 方法被击中时。
public class MyService {
public void call(){
// do something.
}
}
private MyService mySerivce = mock(MyService.class);
我想从调用方法主体记录一条消息,我该如何模拟?就像我可以使用非空方法的答案一样。
verify(myService, times(1)).call();
myService.call();
verify(my)
最佳答案
使用spy
并在运行测试后验证其状态(说实话 - 你也可以使用mock
来做到这一点,但是使用spy
你如果需要的话可以测试真实的物体):
//Given
MyService service = new MyService();
MyService serviceSpy = Mockito.spy(service);
//When
serviceSpy.call();
//Then
long count = Mockito.mockingDetails(serviceSpy)
.getInvocations()
.stream()
.filter(i -> i.toString().contains("service.call()"))
.count();
if (count > 0)
System.out.println("Method was called " + count + " times.");
else
System.out.println("Method wasn't called at all.");
//TODO: of course this isn't correct test because it hasn't any assertions.
关于java - Mockito 在 void 方法调用上打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57208077/