junit 条件拆解

标签 junit conditional teardown

我想在我的 junit 测试用例中进行有条件的拆解,比如

@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}

在拆解中我想要一个像

这样的条件
if(pass) 
then execute teardown 
else skip teardown

使用 junit 是否可能出现这种情况?

最佳答案

您可以使用 TestRule 来做到这一点. TestRule 允许您在测试方法之前和之后执行代码。如果测试抛出异常(或断言失败的 AssertionError),则测试失败,您可以跳过 tearDown()。一个例子是:

public class ExpectedFailureTest {
    public class ConditionalTeardown implements TestRule {
        public Statement apply(Statement base, Description description) {
            return statement(base, description);
        }

        private Statement statement(final Statement base, final Description description) {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    try {
                        base.evaluate();
                        tearDown();
                    } catch (Throwable e) {
                        // no teardown
                        throw e;
                    }
                }
            };
        }
    }

    @Rule
    public ConditionalTeardown conditionalTeardown = new ConditionalTeardown();

    @Test
    public void test1() {
        // teardown will get called here
    }

    @Test
    public void test2() {
        Object o = null;
        o.equals("foo");
        // teardown won't get called here
    }

    public void tearDown() {
        System.out.println("tearDown");
    }
}

请注意,您是手动调用 tearDown,因此您不想在方法上使用 @After 注释,否则它会被调用两次。有关更多示例,请查看 ExternalResource.javaExpectedException.java .

关于junit 条件拆解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8118079/

相关文章:

python - 在Python 2.6中实现tearDownClass功能

unit-testing - 在Grails单元测试中使用mockDomain后是否需要删除metaClass?

java - 静态字段的 JUnit 初始化

installation - PHPUnit 中的 setup() 和 Codeception 中的 _before 有什么区别

java - WebDriver - 无法定位元素,提取网页输入字段

svg - 用于显示 PNG 代替旧浏览器的 SVG 的条件代码?

php - 我可以在字符串中存储逻辑比较吗?

.net - 在 .NET 中,最好是 mystring.Length == 0 还是 mystring == string.Empty?

java - android studio android.support.design.widget.CoordinatorLayout 中的渲染问题

java - 如何使用 ArgumentCaptor 进行 stub ?