IgorekPotworek
IgorekPotworek

Reputation: 1335

Asserting java.util.Date fields in Test

I'm writing integration test for my DAO services. I perform that by using dao insert methods and then reading objects from database and asserting all fields with orginal objects.

I want to use assertj-core to make assertions. Especially isEqualToComparingFieldByField .

But there is problem with java.util.Date fields. They return identical getTime() value but aren't equal.

Currently I ignore these fields in isEqualToComparingFieldByField assertion and then comapre with hasSameTimeAs method.

assertThat(object).isEqualToIgnoringGivenFields(other, "time");
assertThat(object.getTime()).hasSameTimeAs(other.getTime());

Is any way to provide custom comparator to isEqualToComparingFieldByField method for given type(in this case java.util.Date) or any other solution to assert two objects field by field avoiding this issue?

Upvotes: 1

Views: 4209

Answers (2)

Joel Costigliola
Joel Costigliola

Reputation: 7086

There is no way of specifying a custom comparator for a given field type in "field by field" comparison - I'm not sure there is an elegant of introducing that in AssertJ (but I'd love to be proven wrong).

What you can do is to define a comparator for your objects, and use it like this:

assertThat(frodo).usingComparator(raceNameComparator).isEqualTo(pippin);

See assertj-examples project for a full working example.

I know it requires work to write the Comparator, it's the price to pay to have full control over the comparison strategy used.

Upvotes: 2

Michael Faurel
Michael Faurel

Reputation: 23

If you take your objects from sql, you are mixing Timestamps and Date.

Date date = theTwoTowers.getReleaseDate();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());

// timestamp is a Date, it can be compared to date 
assertThat(date.equals(timestamp)).isTrue();

// as date is not a Timestamp, it can't be equal to timestamp  
assertThat(timestamp.equals(date)).isFalse();

This link can help you : https://github.com/joel-costigliola/assertj-core/issues/273

Upvotes: 0

Related Questions