在下面使用这种方法时,通过设置带有套件的jUnit。当所有TestClass中的所有@BeforeClass将在任何测试开始执行之前被执行时,我们遇到了问题。
(对于每个n个TestClass文件,@BeforeClass运行,然后在它们执行之后,它开始执行第一个MyTest.class文件@Test)
这将导致我们分配大量的资源和内存。
我的想法是这一定是错误的,每个@BeforeClass都应该只在执行实际的testclass之前运行,而不是在Suite启动时运行吗?
@RunWith(Suite.class)
@Suite.SuiteClasses({ MyTests.class, Mytests2.class, n1, n2, n })
public class AllTests {
// empty
}
public class MyTests { // no extends here
@BeforeClass
public static void setUpOnce() throws InterruptedException {
...
@Test
...
public class MyTests2 { // no extends here
@BeforeClass
public static void setUpOnce() throws InterruptedException {
...
@Test
...
最佳答案
在AllTests类中编写一个@BeforeClass方法,该方法将在启动套件时执行。
public class MyTests1 {
@BeforeClass
public static void beforeClass() {
System.out.println("MyTests1.beforeClass");
}
@Before
public void before() {
System.out.println("MyTests1.before");
}
@AfterClass
public static void afterClass() {
System.out.println("MyTests1.AfterClass");
}
@After
public void after() {
System.out.println("MyTests1.after");
}
@Test
public void test1() {
System.out.println("MyTests1.test1");
}
@Test
public void test2() {
System.out.println("MyTests1.test2");
}
}
public class MyTests2 {
@BeforeClass
public static void beforeClass() {
System.out.println("MyTests2.beforeClass");
}
@Before
public void before() {
System.out.println("MyTests2.before");
}
@AfterClass
public static void afterClass() {
System.out.println("MyTests2.AfterClass");
}
@After
public void after() {
System.out.println("MyTests2.after");
}
@Test
public void test1() {
System.out.println("MyTests2.test1");
}
@Test
public void test2() {
System.out.println("MyTests2.test2");
}
}
@RunWith(Suite.class)
@Suite.SuiteClasses( { MyTests1.class, MyTests2.class })
public class AllTests {
@BeforeClass
public static void beforeClass() {
System.out.println("AllTests.beforeClass");
}
@Before
public void before() {
System.out.println("AllTests.before");
}
@AfterClass
public static void afterClass() {
System.out.println("AllTests.AfterClass");
}
@After
public void after() {
System.out.println("AllTests.after");
}
@Test
public void test1() {
System.out.println("AllTests.test1");
}
@Test
public void test2() {
System.out.println("AllTests.test2");
}
}
输出
AllTests.beforeClass
MyTests1.beforeClass
MyTests1.before
MyTests1.test1
MyTests1.after
MyTests1.before
MyTests1.test2
MyTests1.after
MyTests1.AfterClass
MyTests2.beforeClass
MyTests2.before
MyTests2.test1
MyTests2.after
MyTests2.before
MyTests2.test2
MyTests2.after
MyTests2.AfterClass
AllTests.AfterClass
hth