我有一段代码看起来像这样:
MyObject getMyObject() {
Instant now = Instant.now();
return myService.doSomething(now);
}
我知道 PowerMock 在 JUnit 5 中不受支持,但我想知道至少对于像日期这样的标准 API 是否有解决方案。
现在我正在用 Mockito.any()
模拟 Instant
实例,这是不正确的,因为如果我传递错误的 Instant 我的测试不会失败
。
最佳答案
您可以将当前 Instant 的创建移动到包级别方法:
MyObject getMyObject() {
Instant now = getCurrentInstance();
return myService.doSomething(now);
}
Instant getCurrentInstant(){
Instant.now();
}
然后在您的测试中,您可以监视 SUT 并模拟 getCurrentInstant
方法:
Sut sut = spy(new Sut());
doReturn(testInstance).when(sut).getCurrentInstant();
sut.getMyObject();
这是我在 Mockito Spying 上写的一篇文章如果您需要进一步阅读。
关于java - 如何使用 JUnit 5 测试调用 Instant.now() 的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390522/