在JUnit 3中,我可以像这样获得当前运行的测试的名称:
public class MyTest extends TestCase
{
public void testSomething()
{
System.out.println("Current test is " + getName());
...
}
}
它会打印“当前测试是testSomething”。
在JUnit 4中是否有任何开箱即用或简单的方法来做到这一点?
背景:显然,我不想只打印测试的名称。我希望加载存储在与测试同名的资源中的特定于测试的数据。你知道,约定比配置更重要。
试试这个吧:
public class MyTest {
@Rule
public TestName testName = new TestName();
@Rule
public TestWatcher testWatcher = new TestWatcher() {
@Override
protected void starting(final Description description) {
String methodName = description.getMethodName();
String className = description.getClassName();
className = className.substring(className.lastIndexOf('.') + 1);
System.err.println("Starting JUnit-test: " + className + " " + methodName);
}
};
@Test
public void testA() {
assertEquals("testA", testName.getMethodName());
}
@Test
public void testB() {
assertEquals("testB", testName.getMethodName());
}
}
输出如下所示:
Starting JUnit-test: MyTest testA
Starting JUnit-test: MyTest testB
注意:如果你的测试是TestCase的子类,这是行不通的!测试运行了,但是@Rule代码从来没有运行过。
JUnit 5通过ExtensionContext
优势:
您可以通过重写afterEach(ExtensionContext上下文)来获得ExtensionContext的附加功能。
public abstract class BaseTest {
protected WebDriver driver;
@RegisterExtension
AfterEachExtension afterEachExtension = new AfterEachExtension();
@BeforeEach
public void beforeEach() {
// Initialise driver
}
@AfterEach
public void afterEach() {
afterEachExtension.setDriver(driver);
}
}
public class AfterEachExtension implements AfterEachCallback {
private WebDriver driver;
public void setDriver(WebDriver driver) {
this.driver = driver;
}
@Override
public void afterEach(ExtensionContext context) {
String testMethodName = context.getTestMethod().orElseThrow().getName();
// Attach test steps, attach scsreenshots on failure only, etc.
driver.quit();
}
}