Search code examples
javajunitjunit3

Should JUnit3 TestSuite really be used like this?


I couldn't recall how to use JUnit3 TestSuite and after some Googling found this

public class MyTestsuite extends TestSuite {
    public static Test suite() {
        final TestSuite s = new TestSuite();
        s.addTestSuite(Test1.class);
        s.addTestSuite(Test2.class);
        return s;
    }
}

It seems to work, but looks very strange to me:

  • Why should I create a new instance when being in a suitable class?
  • How is anybody supposed to find this out? In the javadoc there's nothing like "write a static method called suite".
  • Why not something as simple as this:

 

public class MyTestsuite extends AbstractTestSuite {
    @Override
    public void suite() {
        add(Test1.class);
        add(Test2.class);
    }
}

Basically, I'm curious if doing it like in my first example is really the way to go. Moreover, I wonder what design decisions might be behind such an interface.


This works too and is maybe a bit less strange:

public class MyTestsuite extends TestSuite {
    MyTestsuite() {
        super(Test1.class, Test2.class);
    }
    public static Test suite() {
        return new TestSuite();
    }
}

Solution

  • The first example is used if you want to compose test suites and refer to them by class.

    Your second example doesn't follow the JUnit 3 patterns for defining suites, as discussed in the JUnit 3 cookbook discusses the usage of the static suite method, used by TestRunner.

    The TestRunner class also discusses its use in its Javadocs:

    If this class [a Test class] defines a static suite method it will be invoked and the returned test is run.