如何测试使用LocalDateTime.now()创建的日期 [英] How to test date created with LocalDateTime.now()
问题描述
我有这堂课
class MyObject {
private LocalDateTime date;
public LocalDateTime getDate() { return this.date; }
public void myMethod() {
this.date = LocalDateTime.now();
}
}
如何测试日期设置正确?我不能模拟 now()
,因为它是静态的,如果我在测试中使用LocalDateTime,则两个日期将不相同.
How can I test that the date is properly set? I cannot mock now()
because it is static and if I used LocalDateTime in the test both dates won't be the same.
推荐答案
您可以在调用 myMethod()
之前生成日期时间,并确保该日期在之前或等于到 getDate()
返回的日期,类似这样:
You could generate a date time just before calling myMethod()
and make sure that this date is before or equals to the date returned by getDate()
, something like that:
@Test
public void testDate() {
MyObject object = new MyObject();
// Get the current date time
LocalDateTime time = LocalDateTime.now();
// Affect the current date time to the field date
object.myMethod();
// Make sure that it is before or equals
Assert.assertTrue(time.isBefore(object.getDate()) || time.isEqual(object.getDate()));
}
If you don't care adding coupling to your class a better approach could be to provide a Supplier<LocalDateTime>
to your class as next:
public class MyObject {
private final Supplier<LocalDateTime> supplier;
private LocalDateTime date;
public MyObject() {
this(LocalDateTime::now);
}
public MyObject(final Supplier<LocalDateTime> supplier) {
this.supplier = supplier;
}
public LocalDateTime getDate() { return this.date; }
public void myMethod() {
this.date = supplier.get();
}
}
通过这种方式,可以轻松创建 供应商
用于测试用例.
This way it will be easy to create a Supplier
for testing purpose in your test case.
例如,测试用例可以是:
For example the test case could then be:
@Test
public void testDate() {
LocalDateTime time = LocalDateTime.now();
MyObject object = new MyObject(() -> time);
object.myMethod();
Assert.assertTrue(time.isEqual(object.getDate()));
}
这篇关于如何测试使用LocalDateTime.now()创建的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!