3

I always enjoyed running only one test of a test class. Now I'm using test suites to order my tests by tested methods into separate classes. However, Eclipse is not running the @BeforeClass-method if I want to run a single test of a test suite.

I have the following test setup:

@RunWith(Suite.class) @SuiteClasses({ Test1.class, Test2.class }) public class TestSuite { @BeforeClass public static void setup (){ // essential stuff for Test1#someTest } public static class Test1{ @Test public void someTest(){} } } 

When I run someTest, it fails because TestSuite#setup isn't run. Is there a way to fix this?

1 Answer 1

4

If you just execute Test1, then JUnit doesn't know about TestSuite, so @BeforeClass is not picked up. You can add a @BeforeClass to Test1 that calls TestSuite.setup(). That will also require adding a static flag in TestSuite so it only executes once.

@RunWith(Suite.class) @SuiteClasses({ Test1.class, Test2.class }) public class TestSuite { private static boolean initialized; @BeforeClass public static void setup (){ if(initialized) return; initialized = true; System.out.println("setup"); // essential stuff for Test1#someTest } public static class Test1{ @BeforeClass public static void setup (){ TestSuite.setup(); } @Test public void someTest(){ System.out.println("someTest"); } } } 
Sign up to request clarification or add additional context in comments.

2 Comments

What a bummer, I hoped there was some Eclipse magic that would take care of it!
I know this is an old post... but trying to make it work it seems that something is missing. I added the setup method in the suite and then in the test class, but it doesn't work, I get NullPointerExceptions. I'm seeing that in your example you have the tests classes nested in the TestSuite, which I don't, I have different files but with a call to the TestSuite.setup() method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.