簡體   English   中英

如何在所有測試類開始之前執行一段代碼?

[英]How to execute a piece of code once before all test classes start?

如何在所有類中的所有測試開始之前執行一次方法?

我有一個程序需要在任何測試開始之前設置系統屬性。 有沒有辦法做到這一點?

注意: @BeforeClass@Before僅用於相同的測試 class。 就我而言,我正在尋找一種在所有測試類開始之前執行方法的方法。

如果您需要在所有測試開始之前運行該方法,則應使用注釋@BeforeClass或者如果您每次執行該 class 的測試方法時都需要執行相同的方法,則必須使用@Before

@Before
public void executedBeforeEach() {
   //this method will execute before every single test
}

@Test
public void EmptyCollection() {
  assertTrue(testList.isEmpty());     
}

要為您的測試用例設置前提條件,您可以使用這樣的東西 -

@Before
public void setUp(){
    // Set up you preconditions here
    // This piece of code will be executed before any of the test case execute 
}

您可以使用測試套件。

測試套件

@RunWith(Suite.class)
@Suite.SuiteClasses({ TestClass.class, Test2Class.class, })
public class TestSuite {

    @BeforeClass
    public static void setup() {

        // the setup
    }
}

並且,測試類

public class Test2Class {

    @Test
    public void test2() {

        // some test
    }
}
public class TestClass {

    @Test
    public void test() {

        // some test
    }
}

或者,您可以擁有一個基礎 class 來處理設置

public class TestBase {

    @BeforeClass
    public static void setup() {

        // setup
    }
}

然后,測試類可以擴展基礎 class

public class TestClass extends TestBase {

    @Test
    public void test() {

        // some test
    }
}
public class Test2Class extends TestBase {

    @Test
    public void test() {

        // some test
    }
}

但是,這將在每個子類每次執行時為其所有子類調用TestBase中的setup方法。

暫無
暫無

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

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