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?
First of all, we remove the reference to MockitoJUnitRunner. Instead, we call the static initMocks() method of the MockitoAnnotations class. We do this in JUnit @Before method of test's class. This initializes any fields with Mockito annotations before each test is executed.
initMock() method, which is deprecated and replaced with MockitoAnnotations.
To opt-out from this feature, use @RunWith(MockitoJUnitRunner. Silent. class) Initializes mocks annotated with Mock , so that explicit usage of MockitoAnnotations.
public static class MockitoJUnitRunner.Silent extends MockitoJUnitRunner. This Mockito JUnit Runner implementation ignores unused stubs (e.g. it remains 'silent' even if unused stubs are present). This was the behavior of Mockito JUnit runner in versions 1.*. Using this implementation of the runner is not recommended.
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
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
There is also a @Rule
option:
@Rule
public MockitoRule rule = MockitoJUnit.rule();
Or in Kotlin:
@get:Rule
var rule = MockitoJUnit.rule()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With