尽管我同意@assylias 的观点,使用 @BeforeClass是一种经典的解决方案,但它并不总是方便的。用 @BeforeClass注释的方法必须是静态的。对于一些需要测试用例实例的测试来说是非常不方便的。例如,使用 @Autowired处理在 Spring 上下文中定义的服务的基于 Spring 的测试。
public abstract class AbstractTestBase {
private static Class<? extends AbstractTestBase> testClass;
.....
public void setUp() {
if (this.getClass().equals(testClass)) {
return;
}
// do the setup - once per concrete test class
.....
testClass = this.getClass();
}
}
private static boolean started = false;
static{
if (!started) {
started = true;
try {
setUpDriver(); //method where you initialize your driver
} catch (MalformedURLException e) {
}
}
}
public class TestClass {
private static TestClass testClass = null;
@Before
public void setUp() {
if (testClass == null) {
// set up once
...
testClass = this;
}
}
@AfterClass
public static void cleanUpAfterAll() {
testClass.cleanUpAfterAllTests();
}
private void cleanUpAfterAllTests() {
// final cleanup after all tests
...
}
@Test
public void test1() {
// test 1
...
}
@Test
public void test2() {
// test 2
...
}
}