繁体   English   中英

当mock()方法有效时,为什么Mockito的@Mock注释会失败

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

这是我的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'
}

当我使用@Mock注释声明一个mock时,它是null。 但是当我使用时

context = mock(Context.class);

然后我得到一个正确的模拟对象。 我在Junit-3 TestCase中使用它,如果这很重要的话。

为什么注释不起作用?

如果使用JUnit 3,则必须在测试中使用设置方法中的MockitoAnnotations

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

    // ...
}

注释不能立即使用,您必须指示JUnit执行某些操作。 有关JUnit 4的完整参考,您还有其他推荐选项:

使用JUnit运行程序

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

    // ...
}

或者使用JUnit规则

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

    // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM