javaunit-testingjunitjunit-runner

How to correctly shut down a JUnit-Runner?


I made my own JUnit-Runner by implementing org.junit.runner.Runner, so that I can run my UnitTests with them using the @RunWith-Annotation.

It lookes somewhat like this:

public class MyRunner extends Runner {

    private Context myContext;
    myContext.init();
    private final BlockJUnit4ClassRunner runner;

    public MyRunner(final Class<?> clazz) throws InitializationError {
        myContext = new Context();

        runner = new BlockJUnit4ClassRunner(clazz);
    }

    @Override
    public void run(final RunNotifier notifier) {
        runner.run(notifier);
    }

    @Override
    public Description getDescription() {
        return runner.getDescription();
    }

    public void filter(final Filter filter) throws NoTestsRemainException {
        runner.filter(filter);
    }
}

To clean up resources, I have to shut down MyContext by calling MyContext.close(). Where should I invoke this so that my resources are cleand up after the tests have run?


Solution

  • Where should I invoke this so that my resources are cleand up after the tests have run ?

    UPDATED MY ANSWER, you can use org.junit.runner.notification.RunListener as shown below:

    (1) Create your own RunListener class:

    public class MyRunnerListener extends RunListener {
        private Context context;
    
        public MyRunnerListener(Context context) {
            this.context = context;
        }
    
         void   testRunFinished(Result result)  {
              context.close();
         }
    }
    

    (2) Use the MyRunnerListener inside MyRunner :

    public class MyRunner extends Runner {
    
        private Context myContext;
        MyRunnerListener runnerListener;
        private final BlockJUnit4ClassRunner runner;
    
        public MyRunner(final Class<?> clazz) throws InitializationError {
            myContext = new Context();
            myContext.init();
            runnerListener = new MyRunnerListener(myContext);
    
            runner = new BlockJUnit4ClassRunner(clazz);
        }
    
        @Override
        public void run(final RunNotifier notifier) {
            notifier.addListener(runnerListener);
            runner.run(notifier);
        }
    
        @Override
        public Description getDescription() {
            return runner.getDescription();
        }
    
        public void filter(final Filter filter) throws NoTestsRemainException {
            runner.filter(filter);
        }
    }
    

    P.S.: If you don't want to use the Runner, then you can follow the answer from Markus (which uses TestRule, NOT TestRunner).