Search code examples
javaassertj

AssertThat usage in a date comparison


I want to write a test against a search with date. I am thinking of a test code something like

assertThat(repository.findByBookingDateAfter(LocalDate.of(2016, 1, 1))).extracting("bookingDate").are(...));

where the class structure is something like the followings:

public class Booking{
  ...
  LocalDate bookingDate;
  ...
}

Because the query is on any bookings after a given date, my test shall check the field indeed later than the date. After some online search, I don't see any useful information. I am wondering whether I am on the right track or not.

Any suggestions?

Update:

Later, I change the dependency setup is the followings in the build.gradle file:

testCompile('org.springframework.boot:spring-boot-starter-test'){
    exclude group: 'org.assertj'
}
testCompile group: 'org.assertj', name: 'assertj-core', version: '3.6.2'

to have the latest version of assertj.

Update 2:

The following is a screenshot of any methods starting with "is". The "isAfter" isn't on the list.

enter image description here


Solution

  • I would use allMatch or allSatisfy assertions to check that every extracted date is after the one used in the query.

    // set the extracted type to chain LocalDate assertion 
    assertThat(result).extracting("bookingDate", LocalDate.class)
                      .allMatch(localDate -> localDate.isAfter(queryDate)));
    

    or

    // use a lambda to extract the LocalDate to chain LocalDate assertion
    assertThat(result).extracting(Booking::getBookingDate)
                      .allSatisfy(localDate -> assertThat(localDate).isAfter(queryDate));
    

    you get a better error message with the second assertion, it will show the faulty date.