java 运行忽略 @Before/@After 的 Junit @Test
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13878273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Junit @Test that ignores @Before/@After
提问by m3th0dman
Is it possible to run a JUnit @Test
method in a class that has a method annotated with @Before
, but to ignore the @Before
method only for this test?
是否可以@Test
在具有用 注释的方法的类中运行 JUnit方法@Before
,但@Before
仅在此测试中忽略该方法?
Edit: I am interested if JUnit supports this functionality, not workarounds. I am aware of workarounds like moving the test(s) in another class or removing the annotation and manually calling setUp()
in each test method.
编辑:我感兴趣的是 JUnit 是否支持此功能,而不是解决方法。我知道一些变通方法,例如在另一个类中移动测试或删除注释并setUp()
在每个测试方法中手动调用。
Suppose in a class there are 30 tests, and for 29 of them @Before
really simplifies the testing initialization, but for one (or more than one) of them is useless/it complicates things.
假设在一个类中有 30 个测试,其中 29 个@Before
测试确实简化了测试初始化,但其中一个(或多个)没有用/它使事情复杂化。
public class MyTestClass {
@Before
public void setUp() {
//setup logic
}
@Test
public void test1() {
//[...]
}
@Test
public void test2() {
//[...]
}
//more tests here
@Test(ignoreBefore = true, ignoreAfter = true //false by default)
//something equivalent to this
public void test20() {
//[...]
}
}
采纳答案by Matthew Farwell
You can do this with a TestRule. See my answer to Exclude individual test from 'before' method in JUnit. Basically, implement ExternalResource, and in the apply method, check if there is a specific annotation on the method, and if there is, don't run the before/after method. You'll have to specifically call the before/after from your rule though.
您可以使用 TestRule 执行此操作。请参阅我对Exclude individual test from 'before' method in JUnit 的回答。基本上,实现ExternalResource,在 apply 方法中,检查该方法是否有特定的注解,如果有,不要运行 before/after 方法。不过,您必须根据规则专门调用之前/之后。
回答by kan
If it useless it should not be a problem - does it harm to run the setUp once more?
如果它没用,那应该不是问题 - 再次运行 setUp 是否有害?
However I don't think it's possible and looks for me as a cripple feature.
但是,我认为这是不可能的,并且将我视为一个残废的功能。
Another approach - move that test to a separate test-class.
另一种方法 - 将该测试移动到单独的测试类。
回答by ashxvi
With JUnit 5 You can have nested tests using @Nested annotation :
使用 JUnit 5 您可以使用 @Nested 注释进行嵌套测试:
public class MainClass {
@Nested
class InnerClass1 {
@BeforeEach
void setup(){}
@Test
void test1(){}
}
@Nested
class InnerClass2 {
// No setup
@Test
void test2(){}
}
}