2016-02-16 128 views
4

我想要一個簡單的方法來爲我的JUnit測試分配一個優先級值,以便我可以說'只運行優先級1測試','運行優先級1,2和3測試'等。我知道我可以包含在每次測試開始時(例如priority是我想要運行的最高優先級測試,2是此特定測試的優先值),但是在每次測試開始時拷貝粘貼一行不會似乎是非常好的解決方案。如何根據條件自動跳過某些JUnit測試?

我曾嘗試使用由JUnit的規則檢測到簡單的註解寫一個解決方案,我使用反正:

public class Tests { 
    @Rule 
    public TestRules rules = new TestRules(); 
    @Test 
    @Priority(2) 
    public void test1() { 
     // perform test 
    } 
} 

public class TestRules extends TestWatcher { 
    private int priority = 1; // this value is manually changed to set the priority of tests to run 
    @Override 
    protected void starting(Description desc) { 
     Priority testCasePriority = desc.getAnnotation(Priority.class); 
     Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority); 
    } 
} 

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Priority { 
    public int value() default 0; 
} 

雖然這似乎工作(正確的測試顯示爲在Eclipse的JUnit跳過查看)仍然執行測試,即test1()中的任何代碼仍在運行。

有沒有人有任何想法如何我可以在我的規則Assume實際上跳過測試?

+1

這可能幫助: - http://stackoverflow.com/questions/1689242/conditionally-ignoring-tests-in-junit-4 –

+0

...或者這可能有所幫助:http://www.codeaffine.com/2013/11/18/a-junit-rule-to-conditionally-ignore-tests/ – SiKing

回答

3

TestWatcher.starting拋出的異常被忽略,並在測試結束時重新拋出。

你應該實現的TestRule代替TestWatcher

public class TestRules implements TestRule { 
    private int priority = 1; // this value is manually changed to set the priority of tests to run 

    public Statement apply(final Statement base, final Description description) { 
     return new Statement() { 
      @Override 
      public void evaluate() throws Throwable { 
       Priority testCasePriority = desc.getAnnotation(Priority.class); 
       Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority); 

       base.evaluate(); 
      } 
     }; 
    } 
} 
+0

我有其他'starting()','failed ()''和'finished()'方法,這些在TestRule中很容易重新創建,還是值得爲我的'Assume'方法創建一個單獨的'TestRule',除了我現有的'TestWatcher '子類? – Dave

+1

看看TestWatcher的源代碼:它只是一個簡單的委託TestRule實現。您可以輕鬆地從TestRule中重新實現您的TestWatcher:https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/rules/TestWatcher.java –