java contains 通配符,带有通配符的列表上的AssertJ`containsExactly`断言

I have a getter returning a List with a wildcard:

import java.util.List;

public interface Foo {

List extends Bar> getList();

}

Where Bar is an other interface.

When I write an assertion with AssertJ like this:

assertThat(foo.getList()).containsExactly(bar1, bar3);

EDIT: my complete usage is to chain a usingElementComparator and to provide a Comparator to compare the expected Bar instances.

Comparator comparator = createBarComparator()

assertThat(foo.getList()).usingElementComparator(comparator).containsExactly(bar1, bar3);

I get this compilation error:

The method containsExactly(capture#46-of ? extends Bar...) in the type ListAssert is not applicable for the arguments (Bar, Bar)

My first solution is to cast the result:

assertThat((List)foo.getList()).containsExactly(bar1, bar3);

Then I get a warning:

Type safety: Unchecked cast from List to List

Warning can be removed with @SuppressWarnings("unchecked"), but still the cast in the middle do not make the assertion really readable.

My second solution is to indicate the value the ELEMENT generic parameter:

Assertions.assertThat(foo.getList()).containsExactly(bar1, bar3);

A little better, but also not that nice (no static import possible, the beginning of the line do not facilitate the readability)

I guess I am looking for an other assertThat method for list, where the class type can be specified as second parameter:

@CheckReturnValue

public static ListAssert assertThat(List extends ELEMENT> actual, Class c) {

return AssertionsForInterfaceTypes.assertThat(actual);

}

This way I should be able to write something like this:

Assertions.assertThat(foo.getList(), Bar.class).containsExactly(bar1, bar3);

解决方案

That used to work with the Oracle JDK 7 compiler but this was actually a bug in the compiler, this has been fixed in Java 8 JDK so having the compilation error is the normal behavior (can't find the bug reference though).

I would be happy to support but I'm not sure this is possible in AssertJ except by removing all generics usage in collections assertions.

assertThat(List, Class) already exists but for another purpose so no luck for that option.

A possible hack is to define your own assertThat method like that:

public static ListAssert assertThat(final List list) {

return Assertions.assertThat(list);

}

The trick being to return a ListAssert.

Although I understand the rationale of the compilation error I disagree with it for read only method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值