【问题标题】:How to do compare a bundle with collectionassert in jUnit?如何在 jUnit 中将 bundle 与 collectionassert 进行比较?
【发布时间】:2013-09-23 17:29:46
【问题描述】:

我想使用 jUnit 断言方法确保下面的 bundles 列表不包含 TestFramework 包。

Bundle[] bundles = framework.getBundleContext().getBundles();

所以我想知道 jUnit 是否提供任何这样的方法来比较捆绑包和捆绑包列表?

【问题讨论】:

  • TestFramework 扩展 Bundle 吗?

标签: java junit assert assertions


【解决方案1】:

只需遍历数组并使用 assertEquals 或 assertFalse(假设您不想使用 John B 提到的 ham)。

for (Bundle current : bundles)
{
    assertFalse(current instanceof TestFramework);
}

【讨论】:

    【解决方案2】:

    使用Hamcrest:

     Assert.assertThat(bundles, 
              CoreMatchers.not(
                   IsArrayContaining.hasItemInArray(TestFramework)));
    

    如果你使用静态导入,这将是:

     assertThat(bundles, not(hasItemInArray(myItem)));
    

    如果你需要实例,你可以使用:

     Assert.assertThat(bundles, 
              CoreMatchers.not(
                   IsArrayContaining.hasItemInArray(
                        CoreMatchers.instanceOf(TestFramework.class))));
    

    IsArrayContaining

    仅供参考,我使用Assert.assertThat 只是因为它更容易,但我更喜欢使用MatcherAssert.assertThat,因为它提供了更好的错误文档。

    编辑以响应 DwB。我更喜欢Hamcrest,因为提出的非Hamcrest 解决方案有效,但在失败的情况下,除了expected false got true,您不会得到任何信息。这不会告诉您数组的哪个元素不符合条件或多个元素是否失败。一旦你去 Hamcrest,你将永远不会回去。我不再使用assertTrueassertFalseassertEquals

    【讨论】:

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