如何为特定的 JUnit 测试用例执行@After?
How to perform @After for a specific JUnit test case?
我正在使用 Espresso 构建 UI 测试。对于某些测试用例,我想调用特定的后续步骤来重置状态,以防脚本失败。
有没有办法为单个 JUnit 测试用例 (@Test
) 执行 @After
步骤?
我能想到的唯一解决办法就是单独做一个测试class。但我希望将测试用例分组在同一个测试中 class.
听起来确实有点奇怪 ;) 但是...
您可以将 try/finally 添加到您想要此 after 行为的单个测试中。例如:
@Test
public void testA() {
try {
// the body of testA
} finally {
// apply the 'after' behaviour for testA
}
}
或者,如果您真的想使用 JUnit 的 @After
,那么您可以使用 TestName Rule(自 JUnit 4.7 起),如下所示:
@Rule
public TestName testName = new TestName();
@After
public void conditionalAfter() {
if ("testB".equals(testName.getMethodName())) {
System.out.println("apply the 'after' behaviour for testB");
}
}
@Test
public void testA() {
}
@Test
public void testB() {
}
我正在使用 Espresso 构建 UI 测试。对于某些测试用例,我想调用特定的后续步骤来重置状态,以防脚本失败。
有没有办法为单个 JUnit 测试用例 (@Test
) 执行 @After
步骤?
我能想到的唯一解决办法就是单独做一个测试class。但我希望将测试用例分组在同一个测试中 class.
听起来确实有点奇怪 ;) 但是...
您可以将 try/finally 添加到您想要此 after 行为的单个测试中。例如:
@Test public void testA() { try { // the body of testA } finally { // apply the 'after' behaviour for testA } }
或者,如果您真的想使用 JUnit 的
@After
,那么您可以使用 TestName Rule(自 JUnit 4.7 起),如下所示:@Rule public TestName testName = new TestName(); @After public void conditionalAfter() { if ("testB".equals(testName.getMethodName())) { System.out.println("apply the 'after' behaviour for testB"); } } @Test public void testA() { } @Test public void testB() { }