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()));
}