有条件地忽略JUnit 4中的测试 [英] Conditionally ignoring tests in JUnit 4

查看:126
本文介绍了有条件地忽略JUnit 4中的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以 @Ignore 注释适用于标记不应运行测试用例。

OK, so the @Ignore annotation is good for marking that a test case shouldn't be run.

但是,有时我想忽略基于运行时信息的测试。例如,如果我有一个需要在具有一定数量内核的机器上运行的并发性测试。如果这个测试是在单处理器机器上运行的,我认为只是通过测试是不正确的(因为它还没有运行),并且当然不适合通过测试并打破构建。

However, sometimes I want to ignore a test based on runtime information. An example might be if I have a concurrency test that needs to be run on a machine with a certain number of cores. If this test were run on a uniprocessor machine, I don't think it would be correct to just pass the test (since it hasn't been run), and it certainly wouldn't be right to fail the test and break the build.

所以我希望能够在运行时忽略测试,因为这似乎是正确的结果(因为测试框架将允许构建通过但记录了测试未运行)。我很确定注释不会给我这种灵活性,并且怀疑我需要手动为相关类创建测试套件。但是,文档没有提及任何相关内容,并查看了 API 还不清楚这将如何以编程方式完成(即如何以编程方式创建 Test 的实例或类似于创建的实例@忽略注释?)。

So I want to be able to ignore tests at runtime, as this seems like the right outcome (since the test framework will allow the build to pass but record that the tests weren't run). I'm fairly sure that the annotation won't give me this flexibility, and suspect that I'll need to manually create the test suite for the class in question. However, the documentation doesn't mention anything about this and looking through the API it's also not clear how this would be done programmatically (i.e. how do I programatically create an instance of Test or similar that is equivalent to that created by the @Ignore annotation?).

如果有人在过去做过类似的事情,或者对如何做到这一点有明确的想法,我很高兴听到它。

If anyone has done something similar in the past, or has a bright idea of how else I could go about this, I'd be happy to hear about it.

推荐答案

JUnit的方法是在运行时这样做 org.junit.Assume

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

你可以在 @Before 方法或测试本身,但不在 @After 方法中。如果你在测试中这样做,你的 @Before 方法将会运行。您也可以在 @BeforeClass 中执行此操作以防止类初始化。

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

假设失败导致测试被忽略。

编辑要与 @RunIf进行比较来自 junit-ext 的注释,他们的示例代码如下所示:

To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

更不用说捕获和使用来自以这种方式 Database.connect()方法。

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

这篇关于有条件地忽略JUnit 4中的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆