How to reuse existing JUnit tests in another test class?

Avoid the scenario, in general. It is prone to making tests much more brittle. If TestClass1 fails, then TestClass2 implicitly fails, which isn’t desirable for at least the following reasons:

  • Code is tested more than once, which wastes execution time.
  • Tests should not rely on each other, they should be as decoupled as possible
  • If this becomes a pattern, it will become harder to identify what section of code is broken by looking at which tests are failing, which is part of the point of tests

Occasionally sharing sections of test code is useful, particularly for integration tests. Here’s how you might do it without depending on the tests themselves:

public abstract BaseTests {

    protected void somethingHelper() {
        // Test something
    }
}

public TestClass1 extends BaseTests {
    @Test
    public void testSomething(){
        somethingHelper();
    }
}

public TestClass2 extends BaseTests {
    @Test
    public void testSomethingAndSomethingElse() {
        somethingHelper();
        // and then test something else
    }
}

Alternatively, you could use a helper class and avoid the inheritance altogether. Asserts and the like can go in the somethingHelper() method.

Don’t call a method from TestClass1 in TestClass2 directly. The test cases become less readable this way, and can lead to spaghetti frittata.

Leave a Comment