Search code examples
javaunit-testingtestngmaven-surefire-plugin

@BeforeSuite not invoked when testing a single class


I have a @BeforeSuite-annotated method.

public class MySuiteTest {

    @BeforeSuite
    public static void doSomethingVeryMandatory() {
        // say, boot up an embedded database
        // and create tables for JPA-annotated classes?
    }
}

public class MySingleTest {

    @Test
    public void doSomething() {
        // say, tests some MyBatis mappers against the embedded database?
    }
}

When I test the whole test,

$ mvn clean test

everything's fine. @BeforeSuite runs and @Tests run.

When I tried to test a single class

$ mvn -Dtest=MySingleTest clean test

doSomethingVeryMandatory() is not invoked.

Is this normal?


Solution

  • Your @BeforeSuite and @Test are in different classes. When you run a single class, testng generates a default suite.xml with only one class in it. Hence your @BeforeSuite is not visible to testng. You can either extend MySuiteClass in your testclass or create a suite file and run the suite file as suggested in comments.