MockitoJUnitRunner is deprecated
JavaMockitoDeprecatedJava Problem Overview
I'm trying to make a unit test with @InjectMocks
and @Mock
.
@RunWith(MockitoJUnitRunner.class)
public class ProblemDefinitionTest {
@InjectMocks
ProblemDefinition problemDefinition;
@Mock
Matrix matrixMock;
@Test
public void sanityCheck() {
Assert.assertNotNull(problemDefinition);
Assert.assertNotNull(matrixMock);
}
}
When I don't include the @RunWith
annotation, the test fails. But
> The type MockitoJUnitRunner is deprecated
I'm using Mockito 2.6.9. How should I go about this?
Java Solutions
Solution 1 - Java
org.mockito.runners.MockitoJUnitRunner
is now indeed deprecated, you are supposed to use org.mockito.junit.MockitoJUnitRunner
instead. As you can see only the package name has changed, the simple name of the class is still MockitoJUnitRunner
.
Excerpt from the javadoc of org.mockito.runners.MockitoJUnitRunner
:
> Moved to MockitoJUnitRunner
, this class will be removed with
> Mockito 3
Solution 2 - Java
You can try this:
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
Because you add @Before
annotation, Your mock objects can be new and recorded many times, and in all test you can give objects new properties. But, if you want one time record behavior for mock object please add @BeforeCLass
Solution 3 - Java
There is also a @Rule
option:
@Rule
public MockitoRule rule = MockitoJUnit.rule();
Or in Kotlin:
@get:Rule
var rule = MockitoJUnit.rule()
Solution 4 - Java
You can try importing the following:
import org.mockito.runners.MockitoJUnitRunner;
Also, if you are using Eclipse, just press Ctrl + Shift + O and it will auto import it.
Solution 5 - Java
I managed to fix this when I updated the dependencies to the latest versions in my case:
def mockito_version = '2.28.2'
// For local unit tests on your development machine
testImplementation "org.mockito:mockito-core:$mockito_version"
// For instrumentation tests on Android devices and emulators
androidTestImplementation "org.mockito:mockito-android:$mockito_version"
Then I changed the imports by the replace command (Mac: cmd+Shift+R Windows: Ctrl+Shift+R) from
import org.mockito.runners.MockitoJUnitRunner;
to
import org.mockito.junit.MockitoJUnitRunner;