我正在试验 JUnit Enclosed
运行程序,以尝试改进我的一些测试的组织。目前我正在尝试研究如何在内部类之间共享一些设置。
尝试第一个:
@RunWith(Enclosed.class)
public class EnclosedTest {
@Before
public void printSomething() {
System.out.println("Helllooo Meggan");
}
public static class FirstTest {
@Test
public void assertThatSomethingIsTrue() {
assertThat(true, is(true));
}
}
public static class SecondTest {
@Test
public void assertThatSomethingIsFalse() {
assertThat(false, is(false));
}
}
}
不幸的是,没有人向梅根问好。如果我更新一个内部类来扩展外部类,那么我会得到以下结果:
java.lang.Exception: class 'org.scratch.EnclosedTest$FirstTest' (possibly indirectly) contains itself as a SuiteClass
at org.junit.runners.model.InitializationError.<init>(InitializationError.java:32)
尝试在内部测试类之间共享设置时,是否有特定的 Enclosed
习惯用法?我希望它会像 C# example I found 一样简单.
最佳答案
Enclosed运行者在内部工作为 Suite ,也就是说,它将类作为测试用例运行。并且自 Junit 4.12 以来,抽象内部类被 Enclosed runner 忽略。
也就是说共享设置的方法是创建一个包含它的抽象类(@Before,@After):
@RunWith(Enclosed.class)
public class EnclosedTest {
abstract public static class SharedSetUp {
@Before
public void printSomething() {
System.out.println("Helllooo Meggan");
}
}
public static class FirstTest extends SharedSetUp {
@Test
public void assertThatSomethingIsTrue() {
assertThat(true, is(true));
}
}
public static class SecondTest extends SharedSetUp {
@Test
public void assertThatSomethingIsFalse() {
assertThat(false, is(false));
}
}
}
请注意,您甚至可以为每个子类声明自定义运行器。
关于java - JUnit 封闭式运行器和共享设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26775984/