TestSuite Setup in jUnit 4
Asked Answered
M

1

36

I've managed to find out how to make a TestSuite in jUnit 4, but I really miss the v3 possibility of wrapping a suite in a TestSetup.

Any ideas as to how to get some @BeforeClass/@AfterClass setup executed for a suite of test cases in jUnit 4?

I.e.

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class, Test2.class})
public class MyTestSuite {
    @BeforeClass public static void setUpClass() {
        // Common initialization done once for Test1 + Test2
    }
    @AfterClass public static void tearDownClass() {
        // Common cleanup for all tests
    }
}

Unfortunately the above code fragment doesn't work. @BeforeClass only works on a per-test-class basis.

Muir answered 5/7, 2011 at 9:42 Comment(1)
According to this answer it should work: #83449Amphictyon
U
54

Here is what I have and it runs just fine.

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ TestSuite1.class, TestSuite2.class })
public class CompleteTestSuite {

    @BeforeClass 
    public static void setUpClass() {      
        System.out.println("Master setup");

    }

    @AfterClass public static void tearDownClass() { 
        System.out.println("Master tearDown");
    }

}

Here is my test suite 1 (do the same for test suite 2).

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(value = Suite.class)
@SuiteClasses(value = { TestCase1.class })
public class TestSuite1 {}

And here is my test class. Create both testcase1 and testcase2.

import static org.junit.Assert.assertEquals;

import org.junit.BeforeClass;
import org.junit.Test;

public class TestCase1 {

    @BeforeClass 
    public static void setUpClass() {      
        System.out.println("TestCase1 setup");
    }

    @Test
    public void test1() {
        assertEquals(2 , 2);
    }
}    

you should have 5 classes completesuite suite1 suite2 test1 test2

and make sure you have Junit in your build path. This should run!

Here is the output

Master setup
TestCase1 setup
Master tearDown
Uniliteral answered 5/7, 2011 at 22:35 Comment(2)
What! It actually works! Geez, I wonder how come I couldn't get it to work yesterday (probably just a blunder on my part then).Muir
Awesome solution! Even in my scenario where a custom test scanner creates the list of tests.Netsuke

© 2022 - 2024 — McMap. All rights reserved.