Christopher Perry
Christopher Perry

Reputation: 39235

How do I get the test class instance JUnit is running test cases on from inside the ClassRunner?

I have a custom test runner that extends BlockJUnit4ClassRunner, and I'd like to get the instance of the test class that's instantiated in BlockJUnit4ClassRunner inside my custom test runner.

Upvotes: 4

Views: 2014

Answers (1)

Christopher Perry
Christopher Perry

Reputation: 39235

I figured this one out.

What you can do is override createTest() in BlockJUnit4ClassRunner, and pass the result of super.createTest() to a method of your choice. For example:

public class CustomTestRunner extends AbstractTestRunner {

    @Override
    public abstract void prepareTest(final Object test) {
     // have your way with the test object
    }
}

public abstract class AbstractTestRunner extends BlockJUnit4ClassRunner {

    @Override
    public Object createTest() throws Exception {
         Object test = super.createTest();
         prepareTest(test);
         return test;
    }

    public abstract void prepareTest(final Object test);
}

Upvotes: 7

Related Questions