jUnit ignore @Test methods from base class

Viewed 17025

Let's say I have a test class called testFixtureA with several methods testA, testB, testC, etc, each with @Test annotation.

Let's now say I subclass testFixtureA into class called testFixtureAB and I don't overwrite anything. testFixtureAB is empty as for now.

When I run tests from testFixtureAB, methods testA, testB and testC are executed by test runner because test runner doesn't distinguish between test methods from class and baseclass.

How can I force test runner to leave out tests from baseclass?

11 Answers

and I don't overwrite anything. testFixtureAB is empty as for now

There's your answer. If you want to not run testB from the main class, overrride it:

public class testFixtureAB extends testFixtureA {
   @Override
   public void testB() {}
}

Restructure your test classes.

  • If you don't want to use the tests from the baseclass, then don't extend it
  • If you need other functionality from the base class, split that class in two - the tests, and the other functionality

In Junit 5, you can make base class as abstract and extends it with a concrete class.

When you run the abstract in your IDE, your subclass will get executed instead.

In the latest JUnit you can use the @Rule annotation on the subclass to inspect the test name and intercept the test run to ignore the test dynamically. But I would suggest that @Bozho's idea is the better one - the fact that you need to do this indicates a bigger problem that probably shows inheritance is not the right solution here.

I know, it's not the answer...

Consider the reason why you extend concrete test classes. You do duplicate test methods that way.

If you share code between tests then consider writing base test classes with helper and fixture setup methods or test helper class.

If for running tests then try organizing tests with suites and categories.

If for any reason you need two JUnit classes for same functionality, the best approach for me is:

  • put the common code in a parent class TestFixture with only constants and mocked services.
  • create two subclasses: TestFixtureA and TestFixtureB

This way you will not have duplicated code, nor double runs.

I ran into a similar issue where I had a generic abstract base class TestBase and 2 subclasses TestA, TestB that extended the base class. I wanted all tests from TestBase to run for TestA but to skip some for TestB. You can use the JUnit annotations Nested and Disabled to group tests in the base class into categories and then enable a full disable of that entire category of tests.

public class TestB extends TestBase {

  // disable entire suite of inherited tests
  // from the nested class declared on the parent
  @Nested
  @Disabled
  public class ComponentCTests {}

}

public abstract class TestBase {

  @Nested
  public class ComponentCTests {
     @Test
     public void testSomething() {
      // test something
      }
  }
}
Related