2011-11-14 33 views
3

我想在我的JUnit測試案例有條件的拆解,像JUnit的條件拆卸

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

在拆卸我想有像

if(pass) 
then execute teardown 
else skip teardown 

的情況是這樣的情景可能使用JUnit的?

回答

6

你可以用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"); 
    } 
} 

注意你手動調用拆卸,所以你不希望有方法@After註解,否則它被調用兩次。有關更多示例,請參閱ExternalResource.javaExpectedException.java

+0

非常感謝。這是很好的幫助..正是我需要.. – vpradhan