【问题标题】:Stop JUnit test in @Before method without failing在 @Before 方法中停止 JUnit 测试而不会失败
【发布时间】:2012-05-11 21:26:30
【问题描述】:

这些是我的测试用例

class Mother {

    @Before
    public void setUp() {
        if (!this.getClass().isAnnotatedWith("Version20")) { // pseudo code
            /*
             * stop this test without failing!
             */
        }

        // further setup
    }
}


@Version20
class Child extends Mother {

    @Test
    public void test() {
        // run only when Version == 20
    }
}

是否可以在 Mother 的 @Before 方法中停止 Child 中的测试而不会失败或 assertTrue(false)?

编辑: 我有更多版本@Version19、@Version18 等。 我的软件正在读取配置文件并输出结果,一些测试仅适用于特殊版本。 我不想在测试方法中进行版本检查,因为我有很多小测试并且不喜欢代码重复

【问题讨论】:

标签: java junit


【解决方案1】:

我之前问过similar question - 结果是您可以使用Assume 类的方法来禁用基于运行时 检查的测试(而@Ignore 是静态条件)。

也就是说,如果您总是根据特定注释禁用它们,那么您似乎实际上不需要在运行时执行此操作。只需用 @Ignore@Version20 注释类就可以完成这项工作,并且可以说会更清晰。

虽然我怀疑您可能仅在测试以“1.0 模式”运行时才忽略 - 在这种情况下,它是运行时自省,您可以通过以下方式执行此操作:

@Before
public void setUp() {
   if (!this.getClass().isAnnotatedWith("Version20")) {
      final String version = System.getProperty("my.app.test.version");
      org.junit.Assume.assumeTrue(version.equals("2.0"));
   }
}

【讨论】:

  • 谢谢,正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 2012-05-27
  • 2019-05-01
  • 2011-07-23
  • 1970-01-01
  • 2011-12-09
相关资源
最近更新 更多