Hans-Helge Hans-Helge - 4 months ago 227
Java Question

Multiple RunWith Statements in jUnit

I write unit test and want to use

JUnitParamsRunner
and
MockitoJUnitRunner
for one test class.

Unfortunately, the following does not work:

@RunWith(MockitoJUnitRunner.class)
@RunWith(JUnitParamsRunner.class)
public class DatabaseModelTest {
// some tests
}


Is there a way to use both, Mockito and JUnitParams in one test class?

Answer

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 case:

@Rule public MockitoRule mockitoRule = new MockitoRule();

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