问题描述
我正在尝试使用jUnit 4.4执行测试,为一组集成测试执行设置和拆解。拆卸需要可靠运行。我在使用TestNG时遇到了其他问题,所以我想回到jUnit。在运行任何测试之前以及所有测试完成之后,可以执行哪些挂钩?
I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed?
注意:我们正在使用maven 2进行构建。我尝试过使用maven的 pre -
& post-integration-test
阶段,但是,如果测试失败,maven会停止并且不会运行 post-integration-test
,这没有用。
Note: we're using maven 2 for our build. I've tried using maven's pre-
& post-integration-test
phases, but, if a test fails, maven stops and doesn't run post-integration-test
, which is no help.
推荐答案
是的,可以在前后可靠地运行设置和拆除方法测试套件中的任何测试。让我演示代码:
Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code:
package com.test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class})
public class TestSuite {
@BeforeClass
public static void setUp() {
System.out.println("setting up");
}
@AfterClass
public static void tearDown() {
System.out.println("tearing down");
}
}
所以你的Test1类会看起来像什么喜欢:
So your Test1 class would look something like:
package com.test;
import org.junit.Test;
public class Test1 {
@Test
public void test1() {
System.out.println("test1");
}
}
...你可以想象Test2看起来很相似。如果你运行了TestSuite,你会得到:
...and you can imagine that Test2 looks similar. If you ran TestSuite, you would get:
setting up
test1
test2
tearing down
所以你可以看到设置/拆除只分别在所有测试之前和之后运行。
So you can see that the set up/tear down only run before and after all tests, respectively.
捕获:这只适用于运行测试套件,而不是将Test1和Test2作为单独的JUnit测试运行的情况。你提到你正在使用maven,maven surefire插件喜欢单独运行测试,而不是套件的一部分。在这种情况下,我建议创建一个每个测试类扩展的超类。然后,超类包含带注释的@BeforeClass和@AfterClass方法。虽然不像上面的方法那么干净,但我认为它对你有用。
The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you.
至于测试失败的问题,你可以设置maven.test.error。忽略,以便在失败的测试中继续构建。这不建议作为一种持续的练习,但它应该让您在所有测试通过之前都能正常运行。有关更多详细信息,请参阅。
As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the maven surefire documentation.
这篇关于在jUnit 4.x中的套件执行挂钩之前和之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!