Multiple RunWith Statements in jUnit

You cannot do this because according to spec you cannot put the same annotation twice on the same annotated element.

So, what is the solution? The solution is to put only one @RunWith() with runner you cannot stand without and replace other one with something else. In your case I guess you will remove MockitoJUnitRunner and do programatically what it does.

In fact the only thing it does it runs:

MockitoAnnotations.initMocks(test);

in the beginning of test case. So, the simplest solution is to put this code into setUp() method:

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

I am not sure, but probably you should avoid multiple call of this method using flag:

private boolean mockInitialized = false;
@Before
public void setUp() {
    if (!mockInitialized) {
        MockitoAnnotations.initMocks(this);
        mockInitialized = true;  
    }
}

However better, reusable solution may be implemented with JUnt's rules.

public class MockitoRule extends TestWatcher {
    private boolean mockInitialized = false;

    @Override
    protected void starting(Description d) {
        if (!mockInitialized) {
            MockitoAnnotations.initMocks(this);
            mockInitialized = true;  
        }
    }
}

Now just add the following line to your test class:

@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

and you can run this test case with any runner you want.


As of JUnit 4.7 and Mockito 1.10.17, this functionality is built in; there is an org.mockito.junit.MockitoRule class. You can simply import it and add the line

@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

to your test class.


This solution works for every possible runner, not just this mockito example. For example; for Spring, just change the runner classes and add necessary annotations.

@RunWith(JUnitParamsRunner.class)
public class DatabaseModelTest {

    @Test
    public void subRunner() throws Exception {
        JUnitCore.runClasses(TestMockitoJUnitRunner.class);
    }

    @RunWith(MockitoJUnitRunner.class)
    public static class TestMockitoJUnitRunner {
    }
}

DatabaseModelTest will be run by JUnit. TestMockitoJUnitRunner depends on it (by logic) and it will be run inside of the main in a @Test method, during the call JUnitCore.runClasses(TestMockitoJUnitRunner.class). This method ensures the main runner is started correctly before the static class TestMockitoJUnitRunner sub-runner runs, effectively implementing multiple nested @RunWith annotations with dependent test classes.

Also on https://bekce.github.io/junit-multiple-runwith-dependent-tests