简体   繁体   中英

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

How can I execute a method once before all tests in all classes start?

I have a program that needs a system property to be set before any test start. Is there any way to do that?

Note: @BeforeClass or @Before are used just for the same test class. In my case, I'm looking for a way to execute a method before all test classes start.

if you need to run that method before the start of all test you should use the annotation @BeforeClass or if you need to execute the same method every time you will execute a test method of that class you must use @Before

fe

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

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

To setup precondition to your test cases you can use something like this -

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

You can make use of a Test Suite.

The test suite

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

    @BeforeClass
    public static void setup() {

        // the setup
    }
}

and, the test classes

public class Test2Class {

    @Test
    public void test2() {

        // some test
    }
}
public class TestClass {

    @Test
    public void test() {

        // some test
    }
}

Or, you can have a base class which handles the setup

public class TestBase {

    @BeforeClass
    public static void setup() {

        // setup
    }
}

and, then the test classes can extend the base class

public class TestClass extends TestBase {

    @Test
    public void test() {

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

    @Test
    public void test() {

        // some test
    }
}

However, this will call the setup method in TestBase for all its subclasses everytime each of them executes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM