简体   繁体   中英

AssertJ: fluent ordering tests with custom comparator

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM