【问题标题】:Generics in Hamcrest MatchersHamcrest Matchers 中的泛型
【发布时间】:2023-03-13 01:15:01
【问题描述】:

我不太确定我遇到的问题是否有简单的解决方案,但这里是代码摘录:

 Map<?,?> m = dbo.toMap();
 assertThat(m, Matchers.<Object, Object>hasEntry(is(someKeyValue), is(notNullValue())));

我必须添加那些泛型来安抚编译器,但为什么不能更简单呢?为什么我必须将通配符捕获添加到 m 变量?为什么至少不能:

 assertThat(dbo.toMap(), hasEntry(is((Object)someKeyValue), is(notNullValue())));

这是simple project。在困扰我的单元测试行中:

// this one doesn't quite work
DBObject dbo = returnSomeDBObject();
Map m3 = dbo.toMap();
assertThat(m3, hasEntry(is((Object)PSF_KEY), is(notNullValue())));

// but this one does
DBObject dbo2 = returnSomeDBObject();
Map<?,?> m4 = dbo.toMap();
assertThat(m4, Matchers.<Object, Object>hasEntry(is(PSF_KEY), is(notNullValue())));

【问题讨论】:

  • 实际上应该适用于 Java 7 和 8。向我们展示一个完整的参数化示例以及它是如何失败的(编译错误等)
  • 我添加了一个项目链接和说明问题的代码摘录

标签: java generics hamcrest


【解决方案1】:

您可以使用“原始”匹配器:

DBObject dbo = returnSomeDBObject();
Map m3 = dbo.toMap();

assertThat(m3, (Matcher)hasEntry(is("PSF_KEY"), is(notNullValue())));

顺便说一句,您可以使用Matchers.hasKey 方法来断言地图有一个带有特定键的条目:

assertThat(m3, (Matcher)hasKey("PSF_KEY"));

但请注意,在处理映射中的 null 值时,这在语义上与第一个断言不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多