簡體   English   中英

如何在每個JUnit @Test方法之前單獨運行一些代碼,而不使用@RunWith和AOP?

[英]How to run some code before each JUnit @Test method individually, without using @RunWith nor AOP?

用例很簡單:我想在使用@Test注釋的JUnit測試中的每個方法之前運行一些樣板代碼我的自定義注釋(讓我們稱之為@Mine)。

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

  1. @RunWith (我的測試可能,或者可能不會使用此注釋,所以我不能假設我能夠使用自己的跑步者)
  2. AOP (我不能對第三方庫,例如AspectJ做任何依賴)

我想這只留給我反思,這對我很好。 我想通過使用@Before並通過Thread.getCurrentThread()等獲得當前的方法,但不知怎的,我發現這個解決方案有點臟,因為我必須在這個方法中再次制作鍋爐板代碼來激發反射(和避免任何不必要的代碼是首先的目標)。

也許你有其他一些想法?

基於TestRule ,您需要一個非常類似於Mark單元測試答案的解決方案作為預期的故障 使用@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
    }
}

我會把班級分成兩部分。 一個用你用@mine注釋的方法和一個用其他方法注釋的方法。

然后正常使用@before。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM