Domanda

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?

È stato utile?

Soluzione

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");
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top