Multiple RunWith Statements in jUnit

Solution 1:

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.

Solution 2:

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.