Carl Manaster
Carl Manaster

Reputation: 40356

Why Mockito's @Mock annotation fails when mock() method works

Here's the relevant bit from my build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'

    androidTestCompile "org.mockito:mockito-core:1.10.19"
    androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
    androidTestCompile('com.google.dexmaker:dexmaker-mockito:1.0') {
        exclude module: 'hamcrest-core'
        exclude module: 'objenesis'
        exclude module: 'mockito-core'
    }
    androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
}

When I use @Mock annotation to declare a mock, it's null. But when I use

context = mock(Context.class);

then I get a properly mocked object. I'm using this in a Junit-3 TestCase, if that matters.

Why does the annotation not work?

Upvotes: 2

Views: 2725

Answers (1)

bric3
bric3

Reputation: 42273

If you use JUnit 3, you have to use MockitoAnnotations in the set up method in your test :

public class ATest extends TestCase {
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    // ...
}

Annotations don't work out of the box, you have to instruct JUnit to do something. For a complete reference, with JUnit 4 you have other recommended options :

With a JUnit runner :

@RunWith(MockitoJUnitRunner.class)
public class ATest {
    @Mock Whatever w;

    // ...
}

Or with a JUnit rule :

public class ATest {
    @Rule MockitoRule mockitoRule = MockitoJUnit.rule();
    @Mock Whatever w;

    // ...
}

Upvotes: 3

Related Questions