81

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?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Albert Hendriks
  • 1,979
  • 3
  • 25
  • 45

6 Answers6

158

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

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
12

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

timekeeper
  • 698
  • 15
  • 37
MatWdo
  • 1,610
  • 1
  • 13
  • 26
6

There is also a @Rule option:

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

Or in Kotlin:

@get:Rule
var rule = MockitoJUnit.rule()
git pull origin
  • 353
  • 4
  • 8
3

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;
MeLean
  • 3,092
  • 6
  • 29
  • 43
1

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.

Akshay Chopra
  • 1,035
  • 14
  • 10
0

JunitRunner worked, thank you all

Bartek
  • 127
  • 6