Hello! This post explores most common situations on asserting Java date/time entities using AssertJ library.
Common date/time assertions
This section presents assertion methods to assert LocalDateTime instances, introduced since Java 8.
LocalDateTime is before
Techincally, to check that the given LocalDateTime entity is before another one, it is possible to use two approaches:
- Create predicate that uses isBefore built-in method
- Use isBefore assertion
Take a look on the code snippet below, which demonstrates both cases:
@Test
public void beforeTest(){
LocalDateTime date = LocalDate.of(1992, 2, 14).atStartOfDay();
assertThat(date).matches(d -> d.isBefore(LocalDateTime.now()));
assertThat(date).isBefore(LocalDateTime.now());
}
LocalDateTime is after
Likewise with the previous situation, to assert that the given date/time object is after another, it is possible to follow two ways:
- Create predicate that uses isAfter built-in method
- Use isAfter assertion
This code presents both approaches:
@Test
public void afterTest(){
LocalDateTime now = LocalDateTime.now();
LocalDateTime after = now.plusDays(10);
assertThat(after).matches(d -> d.isAfter(now));
assertThat(after).isAfter(now);
}
LocalDateTime is equal to another DateTime
When it comes to validation of equality, you have to remember that LocalDateTime contains information both about date and time. However, AssertJ allows to check only date entry, ignoring time information. We can summarize equality assertions as following:
- Use isEqualTo assertion, which checks both date and time
- Create predicate that utilizes isEqual implementation of LocalDateTime entites
- Select method that will compare only date and ignore time entry: isEqualToIgnoringHours, isEqualToIgnoringMinutes, isEqualToIgnoringNanos, isEqualToIgnoringSeconds.
Consider the following code snippet below, which shows mentioned approaches:
@Test
public void equalsTest(){
LocalDateTime date1 = LocalDate.of(2013, 3, 5).atStartOfDay();
LocalDateTime date2 = date1.plusHours(12).plusMinutes(30);
assertThat(date1).isEqualToIgnoringHours(date2);
assertThat(date1.plusHours(12)).isEqualToIgnoringMinutes(date2);
assertThat(date1.plusHours(12).plusMinutes(30)).isEqualTo(date2);
assertThat(date1).matches(d -> d.isEqual(date2.minusHours(12).minusMinutes(30)));
}
Source code
You can find the full source code for this post in this github repository. If you have questions regarding this post, don't hesitate to contact me. Have a nice day!
Top comments (0)