2

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.

MA1
  • 926
  • 10
  • 28

3 Answers3

1

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

f.e

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

@Test
public void EmptyCollection() {
  assertTrue(testList.isEmpty());     
}
Alad Mocu
  • 46
  • 1
  • 3
  • 1
    For your information, in the context of your answer, `@BeforeClass` is known as an **_annotation_** and not a _tag_. – Abra Oct 23 '19 at 18:46
1

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 
}
Ashutosh
  • 917
  • 10
  • 19
0

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.

isank-a
  • 1,545
  • 2
  • 17
  • 22