【发布时间】:2019-10-23 18:28:04
【问题描述】:
如何在所有类的所有测试开始之前执行一次方法?
我有一个程序需要在任何测试开始之前设置系统属性。有什么办法吗?
注意:@BeforeClass 或 @Before 仅用于同一个测试类。就我而言,我正在寻找一种在所有测试类开始之前执行方法的方法。
【问题讨论】:
如何在所有类的所有测试开始之前执行一次方法?
我有一个程序需要在任何测试开始之前设置系统属性。有什么办法吗?
注意:@BeforeClass 或 @Before 仅用于同一个测试类。就我而言,我正在寻找一种在所有测试类开始之前执行方法的方法。
【问题讨论】:
要为您的测试用例设置先决条件,您可以使用类似这样的东西 -
@Before
public void setUp(){
// Set up you preconditions here
// This piece of code will be executed before any of the test case execute
}
【讨论】:
如果您需要在所有测试开始之前运行该方法,您应该使用注解@BeforeClass,或者如果您需要在每次执行该类的测试方法时执行相同的方法,您必须使用@Before
f.e
@Before
public void executedBeforeEach() {
//this method will execute before every single test
}
@Test
public void EmptyCollection() {
assertTrue(testList.isEmpty());
}
【讨论】:
@BeforeClass 被称为 annotation 而不是 tag i>.
测试套件
@RunWith(Suite.class)
@Suite.SuiteClasses({ TestClass.class, Test2Class.class, })
public class TestSuite {
@BeforeClass
public static void setup() {
// the setup
}
}
还有,测试类
public class Test2Class {
@Test
public void test2() {
// some test
}
}
public class TestClass {
@Test
public void test() {
// some test
}
}
public class TestBase {
@BeforeClass
public static void setup() {
// setup
}
}
然后,测试类可以扩展基类
public class TestClass extends TestBase {
@Test
public void test() {
// some test
}
}
public class Test2Class extends TestBase {
@Test
public void test() {
// some test
}
}
但是,这将在每次执行时为其所有子类调用TestBase 中的setup 方法。
【讨论】: