Mockito.捕获对LocalDateTime.now()的调用; [英] Mockito. Capturing a call to LocalDateTime.now();
问题描述
我正在做一个单元测试,它调用一个类并检查是否已使用某些参数调用了该类中的方法.这些参数之一是LocalDateTime.now()
.
I'm doing a unit test which calls a class and checks that a method in that class has been called with certain parameters. One of those parameters is LocalDateTime.now()
.
我的问题是,当时间控件返回到我的JUnit测试时,时间已经过去了,因此,如果我尝试将正在调用的类中使用的时间与当前时间进行比较,则它们将不匹配
My problem is that by the time control comes back to my JUnit test, time has marched on, so if I try to compare the time used in the class I'm calling with the current time, they ain't gonna match.
这是我正在寻找的方法:
This is the method I'm looking at:
ServiceStatus serviceStatus = ServiceStatus.createNew(LocalDateTime.now());
Junit测试是:
verify(service).saveNotice(LocalDateTime.now));
我尝试使用TimeFactory
来确定日期:
I've tried using TimeFactory
to fix the date:
given(timeFactory.currentDateTime()).willReturn(NOW);
其次:
given(message.getHeader("MESSAGE_CREATED_TIME")).willReturn(NOW.toString());
&
verify(service).saveNotice(NOW));
但没有喜悦.
有什么建议吗?
(PS.在实际的代码中,还有其他参数,但出于简单起见和出于商业机密的原因,我将其删除了.)
(PS. In the actual code there are other parameters but I've stripped them out for the sake of simplicity and for reasons of commercial confidentiality.)
推荐答案
请勿使用PowerMock.改用/模拟时钟.将您的呼叫切换到LocalDateTime.now()
到LocalDateTime.now(clock)
.从时钟文档:
Don't use PowerMock. Use/mock a Clock instead. Switch your call to LocalDateTime.now()
to LocalDateTime.now(clock)
. From the Clock docs:
应用程序的最佳实践是将Clock传递到需要当前时刻的任何方法中.依赖项注入框架是实现此目标的一种方法:
Best practice for applications is to pass a Clock into any method that requires the current instant. A dependency injection framework is one way to achieve this:
public class MyBean {
private Clock clock; // dependency inject
...
public void process(LocalDate eventDate) {
if (eventDate.isBefore(LocalDate.now(clock)) {
...
}
}
}
这种方法允许在测试过程中使用备用时钟,例如固定时钟或偏移时钟.
This approach allows an alternate clock, such as fixed or offset to be used during testing.
有一种策略可以使clock
最终化,并提供两个构造函数-一个使用提供的时钟,而另一个将系统时钟从Clock.systemDefaultZone()
或Clock.systemUTC()
中取出.另一个方法是使Clock字段可设置为进行测试,可能将其设置为package-private.无论哪种情况,您都可以通过提供由Clock.fixed(...)
创建的Clock来轻松覆盖该值,或者如果需要在测试期间进行更改,则可以编写自己的实现.
One strategy there is to make the clock
final, and offer two constructors--one that uses a supplied clock, and one that gets the system clock out of Clock.systemDefaultZone()
or Clock.systemUTC()
. Another is to make the Clock field settable for testing, possibly by leaving it package-private. In either case, you could easily override the value by supplying a Clock created by Clock.fixed(...)
, or write your own implementation if you need it to change across the duration of the test.
这篇关于Mockito.捕获对LocalDateTime.now()的调用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!