获取junit.framework.AssertionFailedError:使用Unit和Mockito时,[package]中没有找到任何测试

dor*_*ors 5 java junit android unit-testing mockito

我将以下依赖项添加到我的android项目中:

 // Unit testing dependencies
androidTestCompile 'junit:junit:4.12'
// Set this dependency if you want to use Mockito
androidTestCompile 'org.mockito:mockito-core:1.10.19'
Run Code Online (Sandbox Code Playgroud)

并使用junit4 api创建一个测试(例如,Adder是一个简单的类,它总结了int):

@RunWith(MockitoJUnitRunner.class) 
public class AdderTest {

    @Test
    public void testValidAdd() {
        Adder adder = new Adder();
        assertEquals(adder.add(1,1), 2);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行测试时,我得到:

运行测试测试运行已启动junit.framework.AssertionFailedError:在android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:android.test.AndroidTestRunner.runTest(AndroidTestRunner.run:)上的com.test.myapp.AdderTest中找不到测试. 176)在android.app.Instrumentation的android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)$ InstrumentationThread.run(Instrumentation.java:1701)完成

在这里这里读到,但没有任何帮助.

有谁看到我做错了/有什么输入?

Szy*_*zka 17

这些不是单元测试,它们是仪器测试.我有同样的问题,并通过将这些行添加到模块的build.gradle来解决它:

android {
    ...
    sourceSets {
        ...
        defaultConfig {
            testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你必须在依赖项中添加跑步者,我建议你喝咖啡:

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
Run Code Online (Sandbox Code Playgroud)

编辑:

我忘记了注释.只需删除@RunWith并使用line创建一个@Before方法:

MockitoAnnotations.initMocks(this);
Run Code Online (Sandbox Code Playgroud)

要么:

System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getTargetContext().getCacheDir().getPath());
Run Code Online (Sandbox Code Playgroud)

我不推荐这种方式.要使用第二个,您必须使用dex-maker为mockito添加依赖项:

androidTestCompile ('com.google.dexmaker:dexmaker-mockito:1.2') {
        exclude module: 'mockito-core'
    }
Run Code Online (Sandbox Code Playgroud)

由于您添加了mockito,我们必须从新依赖项中排除mockito核心.它已包含正常的dex-maker模块.


Jef*_*ica 2

您正在使用 Android Instrumentation 测试。默认情况下,Android 测试运行器不在 JUnit4 上运行,而是使用InstrumentationTestCase的子类在 JUnit3 上运行。

您需要恢复为手动调用MockitoAnnotations.initMocks(),并可选择对 进行拆卸调用Mockito.validateMockitoUsage()。当然,直接调用Mockito.mock(等)仍然有效。

作为替代方案,有一个官方的 JUnit4 运行程序,可以从Android 支持测试库安装。通过调用此 Instrumentation 而不是默认的测试运行程序,您可以在设备上运行 JUnit4 测试,包括使用MockitoJUnitRunnerMockitoRule