Search code examples
javajunit4junit3

Can I mix JUnit 3 and JUnit 4?


I am writing some JUnit tests that extend a class from a third party library. The super class extends TestCase, so by definition so does my subclass.

In my subclass, I write test methods with the prefix test and these get executed.

However, for a number of reasons we would like to move to JUnit 4 (one of those reasons is that we don't want to have to prefix test methods with test)

I have tried simply writing my new tests with the JUnit 4 @Test annotation, but these methods do not get executed.
For example:

public abstract class UtilityClassFromThirdPartyLibrary extends TestCase {

}

public class MyTestClass extends UtilityClassFromThirdPartyLibrary {

    public void testThisMethodIsInvokedBecauseItStartsWithTest {
    }

    @Test
    public void thisMethodDoesNotGetInvoked {
    }
}

Not extending the 3rd party test class is not an option. (For what it's worth, it's Spring's AbstractXmlFlowExecutionTests which in turn extends other Spring classes, which eventually extend TestCase. The methods in the super classes provide so much setup and boilerplate, that not extended these simply to use JUnit 4 would be counter-productive)

As mentioned, one of our motivations for using JUnit 4's @Test annotation is that it allows us to name our methods better. Our view is the word test is redundant, as the class is clearly a test class, and the method is annotated with @Test. And we write our tests in a BDD style, and so our test method names describe what the unit under test should do - our naming convention is public void shouldDoSomething()

Does anyone know if its possible to mix'n'match test classes that extend JUnit 3's TestCase with methods that use JUnit 4's @Test ?, and if so, how?

Thanks
Nathan


I've already seen a couple of SO questions that pertain to be the same problem, but they are related to Android or test suites, so are not quite the same as my question. EG:
Is it possible to mix JUnit3 and JUnit4?
https://stackoverflow.com/questions/32393330/run-junit-3-and-junit-4-tests-in-the-same-class


Solution

  • JUnit4 style tests should not extend junit.framework.TestCase directly or indirectly. If you do, you often get confusing behavior (fields annotated by @Rule ignored, test failures because the base class methods are not being called by JUnit, etc). The tests may be run as JUnit4-style or JUnit3-style depending bon how they are run.

    Your options are either to stick with JUnit3 or convince the maintainers of your base class to create classes that support JUnit4 (Rules, Runners, etc).