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

查看:34
本文介绍了有条件地忽略 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 或与 @Ignore 注释创建的等效的类似实例?).

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.

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

为了与 junit-ext 中的 @RunIf 注释进行比较,它们的示例代码如下所示:

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天全站免登陆