Custom JUnit Runner which delegate to standard runners
Asked Answered
C

0

7

I'm currently creating a unit custom JUnit runner (which will precisely call custom code before/after each test method) e.g.

class MyRunner extends BlockJUnit4ClassRunner {

    private MyApi api = new MyApi();

    public MyRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    // todo

}

However, I would like to support other runners e.g. MockitoJunitRunner and SpringRunner, so instead of reinventing the wheel, I'd like to use my runner like the following (using a custom MyConfig annotation to specify existing test runners): -

@RunWith(MyRunner.class)
@MyConfig(testRunner=MockitoJUnitRunner.class)
public class MockitoRunnerTest {

}

... or ...

@RunWith(MyRunner.class)
@MyConfig(testRunner=SpringRunner.class)
public class MockitoRunnerTest {

}

This means the test runner is very light i.e. it's like a Junit rule and simply proxies to another existing Junit runner after calling it's own code.

My gut feeling is that this has already be implemented/solved - just having problems finding it.

NOTE: I want to avoid using rules due to these problems - see Apply '@Rule' after each '@Test' and before each '@After' in JUnit

Chapell answered 25/3, 2018 at 9:29 Comment(4)
maybe you just need to use SpringRunner's or MockitoRunner's logic inside your MyRunner class? try to @autowire them or create a new instance and just use it's methodsAmelia
Yes, that is one solution but does mean at least 3 lines of code i.e. auto-wiring (or manually creating an instance) of the service, calling the code inside a @Before method (and creating this setup method if it doesn't exist) and also calling the code inside an @After method (and also creating this tearDown method if it doesn't exist). Really looking for a more DRY solution but agree that delegating to another existing (more established) runner like SpringRunner isn't ideal either. Trying to call the API of this open source project - github.com/videofirst/vft-captureChapell
What solution did you go for in the end?Woodworking
I just used rules in the end - even though I said I wanted to avoid them :-)Chapell

© 2022 - 2024 — McMap. All rights reserved.