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?

Torsten
  • 1,696
  • 2
  • 21
  • 42

1 Answers1

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");
        }
    }
}
Ted Bigham
  • 4,237
  • 1
  • 26
  • 31
  • 1
    What a bummer, I hoped there was some Eclipse magic that would take care of it! – Torsten Feb 23 '14 at 17:23
  • 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. – Fede E. Nov 14 '18 at 12:49