Albert Hendriks
Albert Hendriks

Reputation: 2143

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?

Upvotes: 81

Views: 68057

Answers (6)

Bartek
Bartek

Reputation: 137

JunitRunner worked, thank you all

Upvotes: 0

MeLean
MeLean

Reputation: 3441

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;

Upvotes: 3

Akshay Chopra
Akshay Chopra

Reputation: 1253

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.

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

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

Upvotes: 160

MatWdo
MatWdo

Reputation: 1740

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

Upvotes: 12

git pull origin
git pull origin

Reputation: 393

There is also a @Rule option:

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

Or in Kotlin:

@get:Rule
var rule = MockitoJUnit.rule()

Upvotes: 6

Related Questions