【发布时间】:2023-03-08 08:50:02
【问题描述】:
我正在使用 JUnit 4 来测试带有内存数据库的后端系统。我正在使用 @BeforeClass @Before @After 和 @AfterClass。
到目前为止,它在班级级别上运行良好。
@BeforeClass 包含缓慢的数据库设置,但每个测试会话只需执行一次。
@Before 只是为下一次测试擦干净。速度挺快的。
我的测试看起来像这样:
class CompanyTest {
@BeforeClass
public static void beforeAll() throws Exception {
BeforeAll.run(); //Setup In Memory Database!!! Very time intensive!!!
}
@Before
public void beforeTest() throws Exception {
BeforeTest.run(); //Setup data in database. Relatively quick
}
@Test
public void testCreateCompany() throws Exception {
///...
}
@Test
public void testDeleteCompany() throws Exception {
///...
}
@Test
public void testAdminCompany() throws Exception {
///...
}
@After
public void afterTest() {
AfterTest.run(); //clear data
}
@AfterClass
public static void afterAll() throws Exception {
AfterAll.run(); //tear down database
}
}
到目前为止,它在班级级别上运行良好。
我可以右键单击(在 Eclipse 中)单个测试,它将运行 @BeforeClass,然后运行 @Before。
我也可以(在 Eclipse 中)单击类本身,它只会运行一次 @BeforeClass,然后在每次测试之前运行 @Before。
....但是这个原则如何扩展到套件级别?
我想在我的套件中的所有课程之前运行@BeforeClass。如果我这样写我的套件:
@Suite.SuiteClasses({ CompanyTest.class, CustomerTest.class, SomeOtherTest.class, })
public class AllTests {
@BeforeClass
public static void beforeAll() throws Exception {
BeforeAll.run();
}
@AfterClass
public static void afterAll() throws Exception {
AfterAll.run();
}
}
...我需要从我的所有测试类中删除 @BeforeClass。这很烦人,因为我有很多测试类,我不想删除我的 @BeforeClass 因为我想单独测试它们。
我的基本意思是:
是否有一种简单的方法(在 IDE 中单击鼠标)在 (a) 方法级别、(b) 类级别和 (c) 套件级别测试 JUnit 测试,同时保持会话级别设置和拆卸过程?
【问题讨论】:
-
您可以添加一个静态计数器“nestingLevel”,而不是从所有测试类中删除 @BeforeClass,每个 BeforeAll.run() 递增,每个 AfterAll.run() 递减,然后执行仅当嵌套级别为 1 时才进行实际设置/拆卸。
-
我在similar question 中给出的建议是使用 JUnit(类)规则并在规则中检查它是否之前已经初始化,在这种情况下跳过初始化。这应该允许您为套件和具体测试类重用规则。