junit有条件的拆解
发布时间:2020-12-15 08:45:11 所属栏目:Java 来源:网络整理
导读:我希望在我的junit测试用例中有条件拆解,例如 @Testtestmethod1(){//condition to be tested}@Teardown{//teardown method here} 在拆解我想要有一个像这样的条件 if(pass) then execute teardown else skip teardown 是这样的场景可能使用junit? 解决方法
我希望在我的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.java和ExpectedException.java. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读