How to avoid inheritance in JUnit test cases?

The JUnit way to compose reusable code (instead of inheriting from it) are Rules.

See https://github.com/junit-team/junit/wiki/Rules

Here is a dumb sample, but you’ll get the point.

import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
import org.junit.runner.Description;

public class MyTestRule implements TestRule {
  @Override
  public Statement apply(final Statement statement, Description description) {
    return new Statement() {
      public void evaluate() throws Throwable {
        // Here is BEFORE_CODE
        try {
          statement.evaluate();
        } finally {
          // Here is AFTER_CODE
        }
      }
    };
  }
}

You can then use your TestRule like this:

import org.junit.Rule;

public class MyTest {
    @Rule
    public MyTestRule myRule = new MyTestRule();
}

BEFORE_CODE and AFTER_CODE will then be executed around each of your test methods.

If you need to run your code only once per class, use your TestRule as a @ClassRule:

import org.junit.ClassRule;

public class MyTest {
    @ClassRule
    public static MyTestRule myRule = new MyTestRule();
}

Now, BEFORE_CODE and AFTER_CODE will be executed around each of your test class.

@Rule field is not static, @ClassRule field is.

A @ClassRule can be declared in a Suite too.

Note that you can declare several rules in a single test class, that’s how you compose test lifecycles at test-suites, test-classes and test-methods levels.

A Rule is an object that you instanciate in your test classes (statically or not). You can add contructor parameters if needed.

HTH

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)