Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockitoJUnitRunner is deprecated

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?

like image 560
Albert Hendriks Avatar asked Jan 28 '17 11:01

Albert Hendriks


People also ask

What can I use instead of MockitoJUnitRunner?

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.

Is initMocks deprecated?

initMock() method, which is deprecated and replaced with MockitoAnnotations.

What is the use of @RunWith MockitoJUnitRunner class?

To opt-out from this feature, use @RunWith(MockitoJUnitRunner. Silent. class) Initializes mocks annotated with Mock , so that explicit usage of MockitoAnnotations.

What is MockitoJUnitRunner silent?

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.


3 Answers

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

like image 191
Nicolas Filotto Avatar answered Oct 05 '22 15:10

Nicolas Filotto


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

like image 24
MatWdo Avatar answered Oct 05 '22 14:10

MatWdo


There is also a @Rule option:

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

Or in Kotlin:

@get:Rule
var rule = MockitoJUnit.rule()
like image 43
git pull origin Avatar answered Oct 05 '22 14:10

git pull origin