Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jUnit ignore @Test methods from base class

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?

like image 601
mgamer Avatar asked Feb 05 '10 12:02

mgamer


4 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() {}
}
like image 96
Matthew Flynn Avatar answered Oct 14 '22 15:10

Matthew Flynn


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
like image 20
Bozho Avatar answered Oct 14 '22 13:10

Bozho


ignoring the whole base class:

@Ignore
class BaseClass {
   // ...
}

check out this example

like image 45
dfa Avatar answered Oct 14 '22 13:10

dfa


It's quite easy to achieve implementing some few classes:

  • Create your own TestRunner
  • Create an annotation like @IgnoreInheritedTests
  • Create a class that extends org.junit.runner.manipulation.Filter

On the filter class:

public class InheritedTestsFilter extends Filter {

    @Override
    public boolean shouldRun(Description description) {
        Class<?> clazz = description.getTestClass();
        String methodName = description.getMethodName();
        if (clazz.isAnnotationPresent(IgnoreInheritedTests.class)) {
            try {
                return clazz.getDeclaredMethod(methodName) != null;
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String describe() {
        // TODO Auto-generated method stub
        return null;
    }

}

on your custom runner:

 /**
 * @param klass
 * @throws InitializationError
 * @since
 */
public CustomBaseRunner(Class<?> klass) throws InitializationError {
    super(klass);
    try {
        this.filter(new InheritedTestsFilter());
    } catch (NoTestsRemainException e) {
        throw new IllegalStateException("class should contain at least one runnable test", e);
    }
}
like image 10
user1607938 Avatar answered Oct 14 '22 14:10

user1607938