簡體   English   中英

如何使用不同的參數運行選定的junit測試

[英]How to run selected junit tests with different parameters

我想從任何具有不同參數的測試類中運行選定的測試方法

例如:1)ClassA->測試方法A,B

@Test
public void testA(String param) {
    System.out.println("From A: "+param);
}
@Test
public void testB(String param) {
}

2)ClassB->測試方法C,D

@Test
public void testC(String param) {
    System.out.println("From C: "+param);
}
@Test
public void testD(String param) {
}

從這些我想運行以下測試
1)使用diff參數“ test1”和“ test2”兩次testA(來自ClassA)
2)使用diff參數“ test3”和“ test3”兩次testC(來自ClassB)

我的測試計數應顯示為“ 4”

任何人都可以幫忙...

使用Junits隨附的參數化測試,您可以在運行時傳遞參數。

請參考org.junit.runners.Parameterized (JUnit 4.12提供了在設置數組中使用期望值和沒有期望值進行參數化的可能性)。

嘗試這個:

@RunWith(Parameterized.class)
public class TestA {

   @Parameterized.Parameters(name = "{index}: methodA({1})")
   public static Iterable<Object[]> data() {
      return Arrays.asList(new Object[][]{
            {"From A test1", "test1"}, {"From A test2", "test2"}
      });
   }

   private String actual;
   private String expected;

   public TestA(String expected,String actual) {
      this.expected = expected;
      this.actual = actual;
   }

   @Test
   public void test() {
      String actual = methodFromA(this.actual);
      assertEquals(expected,actual);
   }

   private String methodFromA(String input) {
      return "From A " + input;
   }
}

您可以為B類編寫類似的測試。

對於僅使用單個參數的測試,可以從JUnit 4.12進行:

@RunWith(Parameterized.class)
public class TestU {

    /**
     * Provide Iterable to list single parameters
     */

    @Parameters
    public static Iterable<? extends Object> data() {
        return Arrays.asList("a", "b", "c");
    }

    /**
     * This value is initialized with values from data() array
     */

    @Parameter
    public String x;

    /**
     * Run parametrized test
     */

    @Test
    public void testMe() {
        System.out.println(x);
    }
}

嘗試使用JUnit參數化測試。 這是來自TutorialsPoint.com的教程

JUnit 4引入了一項稱為參數化測試的新功能。 參數化測試允許開發人員使用不同的值一次又一次地運行相同的測試。 創建參數化測試需要遵循五個步驟。

  • 使用@RunWith(Parameterized.class)注釋測試類。

  • 創建一個用@Parameters注釋的公共靜態方法,該方法返回對象的集合(作為數組)作為測試數據集。

  • 創建一個公共構造函數,該結構接受相當於一“行”測試數據的內容。

  • 為測試數據的每個“列”創建一個實例變量。

  • 使用實例變量作為測試數據的源來創建您的測試用例。

測試用例將為每行數據調用一次。

暫無
暫無

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

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