Singleton 解决方案有些笨拙,因为它阻止了将来的任何测试并行化。
有一些方法可以解决这个问题。一种是将 ITestContext 实例传递给您的 @BeforeSuite/@BeforeTest 和 @BeforeClass 配置方法,并通过每个实例中的测试上下文放置/获取参数:
public class Test {
/** Property Foo is set once per Suite */
protected String foo;
/** Property Foo is set once per Test */
protected String bar;
/**
* As this method is executed only once for all inheriting instances before the test suite starts this method puts
* any configuration/resources needed by test implementations into the test context.
*
* @param context test context for storing test conf data
*/
@BeforeSuite
public void beforeSuite(ITestContext context) {
context.setAttribute("foo", "I was set in @BeforeSuite");
}
/**
* As this method is executed only once for all inheriting instances before the test starts this method puts any
* configuration/resources needed by test implementations into the test context.
*
* @param context test context for storing test conf data
*/
@BeforeTest(alwaysRun = true)
public void beforeTest(ITestContext context) {
context.setAttribute("bar", "I was set in @BeforeTest");
}
/**
* This method is run before the first method of a test instance is started and gets all required configuration from
* the test context.
*
* @param context test context to retrieve conf data from.
*/
@BeforeClass
public void beforeClass(ITestContext context) {
foo = (String) context.getAttribute("foo");
bar = (String) context.getAttribute("bar");
}
}
即使 @BeforeSuite/Test/Class 方法位于实际测试实现的超类中,此解决方案也有效。