2011-11-22 14 views
3

用例很簡單:我想在JUnit測試的每個方法之前運行一些鍋爐板代碼,用@Test 註解我的自定義註釋(我們稱之爲@Mine)。如何在每個JUnit @Test方法之前單獨運行一些代碼,而不使用@RunWith或AOP?

我不想使用下面的方法(括號中解釋):

  1. @RunWith(我的測試可能或可能不會已經使用此批註,所以我不能假設我將能夠用我自己的亞軍)
  2. AOP(我不能做任何依賴於第三方庫,如AspectJ)

我想這給我留下了反思ONL喲,這對我來說很好。我想通過使用@Before,並通過Thread.getCurrentThread()等獲得當前方法,但不知何故,我發現這個解決方案有點骯髒,因爲我不得不在這個方法中重新生成鍋爐代碼來激發反射(和避免任何不必要的代碼是首要目標)。

也許您有其他想法?

+0

我不明白爲什麼@Before不能使用 –

+0

因爲,據我所知,Before是在每個用Test註解的方法之前運行的。我的預期行爲是不同的。我希望我的自定義代碼在標有Mine註釋的方法上運行。它不能依賴於其他註釋。 –

+0

@Before在每個方法之前都會運行。 –

回答

9

根據TestRule,您需要一個與Mark unit test as an expected failure的答案非常相似的解決方案。使用@Deprecated註釋的示例(您可以在這裏使用您的示例),如果註釋存在於方法中,則可以插入代碼。 Description類包含該方法的註釋列表。

public class ExecutionTest { 
    public class BeforeExecution 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 { 
        if (description.getAnnotation(Deprecated.class) != null) { 
         // you can do whatever you like here. 
         System.err.println("this will be run when the method has an @Deprecated annotation"); 
        } 
        base.evaluate(); 
       } 
      }; 
     } 
    } 

    @Rule public BeforeExecution beforeExecution = new BeforeExecution(); 

    // Will have code executed. 
    @Deprecated 
    @Test public void test1() { 
     // stuff 
    } 

    // won't have code executed. 
    @Test public void test2() { 
     // stuff 
    } 
} 
+0

確認。這按預期工作。我的最終解決方案是編寫具有適當'@規則'字段的抽象類。我的每個測試都會擴展這個類,因此唯一需要做的就是每當需要時使用我的正確'@Mine'註釋。 –

+0

將內部類設爲靜態,例如'public static class BeforeExecution實現TestRule'是否有害? –

+0

@Mr_and_Mrs_D不,它沒有。 –

2

我會把課堂分成兩部分。一個用@mine註解的方法,另一個用於其他註解。

然後使用@before爲正常。

這不會添加任何標準代碼,並且對未來的開發人員也很容易理解和維護。

相關問題