【问题标题】:How to use an Or with a JUnit assume如何使用 Or 与 JUnit 假设
【发布时间】:2019-06-25 17:42:29
【问题描述】:

在一个 jUnit 测试用例中,我试图使用一个 Assume 来检查一个条件是否为真,或者另一个条件是否为真。但是,只要一个条件为真,jUnit 就会有效地停止测试。

在下面列出的示例中,如果原因为 null 或 enumValue 在 allowedReasons EnumSet 中,我将尝试运行测试。

EnumSet 不允许其成员中有空值,我想坚持使用 EnumSet 来模仿实际类用来验证其原因的内容。

  @RunWith(Parameterized.class)
  public static class AllowedExclusionsTest
  {

    @Parameters
    public static Iterable<EntitlementReason> data()
    {
      final List<EntitlementReason> data = new ArrayList<>();
      data.addAll(Arrays.asList(EntitlementReason.values()));
      data.add(null);
      return data;
    }

    @Parameter(0)
    public EntitlementReason reason;

    private final Set<EntitlementReason> allowedReasons =
        EnumSet.of(EntitlementReason.INCARCERATED, EntitlementReason.ABSENT_FROM_CANADA);

    @Test
    public void testAllowedExclusionReason()
    {
      Assume.assumeThat(reason, Matchers.isIn(allowedReasons));
      Assume.assumeThat(reason, Matchers.nullValue());
      final ExcludedPeriodFact test = new ExcludedPeriodFact();
      test.setExclusionReason(reason);
      Assert.assertEquals("getExclusionReason()", reason, test.getExclusionReason());
    }
  }

【问题讨论】:

    标签: java junit junit4 hamcrest


    【解决方案1】:

    事实证明,使用 Matcher anyOf 就可以做到这一点。

    @Test
    public void testAllowedExclusionReason()
    {
      Assume.assumeThat(reason, Matchers.anyOf(Matchers.nullValue(), Matchers.isIn(allowedReasons)));
      final ExcludedPeriodFact test = new ExcludedPeriodFact();
      test.setExclusionReason(reason);
      Assert.assertEquals("getExclusionReason()", reason, test.getExclusionReason());
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2014-02-20
      • 1970-01-01
      • 2017-11-09
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多