2

Let us assume that I have a class Foo, which does not implement Comparable and a FooComparator class, which implements Comparator<Foo>.

Using AssertJ's fluent API, I would now assume that I could do something like this:

Foo foo1 = ...;
Foo foo2 = ...;
FooComparator fooComparator = ...;
assertThat(foo1).usingComparator(fooComparator).isGreaterThan(foo2);

Since Foo does not implement Comparable, assertThat(foo1) will return a type of ObjectAssert<Foo> and since usingComparator also returns ObjectAssert<Foo>, I do not have access to the isGreaterThan and isLessThan methods, which are declared in the ComparableAssert interface.

Is there a reason why ObjectAssert<Foo>.usingComparator 'only' returns ObjectAssert<Foo> and not ComparableAssert<Foo>?

I can of course rewrite the above assertion with something along the line of assertThat(fooComparator.compare(foo1, foo2)).isGreaterThan(0), but the expression itself is not particularly readable and in case of failures, the generated message ('Expecting: <-1> to be greater than: <0>') does not mention the actual data in foo1 and foo2 causing the assertion to fail.

Is there a way to fluently express this condition with the built-in AssertJ API without having to implement proprietary extensions or wrappers?

jarnbjo
  • 33,923
  • 7
  • 70
  • 94

1 Answers1

0

At the moment, you can't return a ComparableAssert<Foo> after usingComparator because AbstractComparableAssert requires the actual type Foo to be Comparable. AbstractComparableAssert is declared like this:

AbstractComparableAssert<SELF extends AbstractComparableAssert<SELF, ACTUAL>,
                         ACTUAL extends Comparable<? super ACTUAL>>

I'm not sure if that will help but I will mention it anyway, you could write:

assertThat(asList(foo1, foo2)).isSortedAccordingTo(fooComparator);
Joel Costigliola
  • 6,308
  • 27
  • 35
  • That just shifts the question to be: Why does ComparableAssert require ACTUAL to implement Comparable instead of allowing assertions on a non-comparable type in connection with a suitable Comparator-implementation? – jarnbjo Apr 24 '19 at 11:28
  • Simply because we did not think of that use case. – Joel Costigliola Apr 24 '19 at 23:16
  • I have created an issue to track that improvement https://github.com/joel-costigliola/assertj-core/issues/1492 – Joel Costigliola Apr 24 '19 at 23:23