簡體   English   中英

讀取 JUNIT 的自定義注釋

[英]Reading custom annotation for JUNIT

我有一個自定義注釋,我將其用作配置來啟動 Junit 的一次設置。

@Target(TYPE) @Retention(RUNTIME)
public @interface MyAnnotation{
   String host();
   int port();
}

測試 class:

@MyAnnotation(host="0.0.0.0", port=4567)
public class MyTest extends MyAbstractClass{
   @Test
   public void myTest(){
      //do testy things
   }   
}

超類:

public class MyAbstractClass{

   @BeforeAll
   public static void start(){
    Config cfg = readConfig();
    //Use config to do one time set-up
   }

   private static Config readConfig(){
      MyAnnotation ann = MyTest.class.getAnnotation(MyAnnotation.class);
      return new Config(ann.host(), ann.port());
   }
}

所以目前,我在readConfig(..)中硬編碼了測試 class ( MyTest ) 的名稱。 當我添加第二個測試 class 時,這將不起作用。

解決它的一種方法是:

  • 在 MyTest 中添加另一個 @BeforeAll 方法,它將調用超類中的 @BeforeAll 並將 class 名稱作為參數傳遞。

但是,我很好奇是否可以通過一些反射魔法讀取超類中正在執行的子類的名稱。 任何想法都是最受歡迎的。

謝謝

@BeforeAll注釋的存在表明您正在使用 JUnit 5。在這種情況下,您可以使用。

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInfo;

public class MyAbstractClass {
    @BeforeAll
    public static void start(TestInfo ti) {
        Config cfg=readConfig(ti.getTestClass().orElseThrow(IllegalStateException::new));
        //Use config to do one time set-up
    }

    private static Config readConfig(Class<?> testClass) {
         MyAnnotation ann = testClass.getAnnotation(MyAnnotation.class);
         return new Config(ann.host(), ann.port());
    }
}

另請參閱TestInfo API 文檔

This is not “Reflection Magic” but a feature provided by JUnit itself, but it's also only JUnit which knows that the invocation of a static method annotated with @BeforeAll is associated with a particular test class it is going to process.

暫無
暫無

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

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