当前位置: 代码迷 >> java >> 获取junit.framework.AssertionFailedError:使用Unit和Mockito时,[package]中没有找到任何测试
  详细解决方案

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

热度:14   发布时间:2023-07-25 19:21:50.0

我将以下依赖项添加到我的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'

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

@RunWith(MockitoJUnitRunner.class) 
public class AdderTest {

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

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

运行测试测试运行已启动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)完成

我和读到,但没有任何帮助。

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

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

android {
    ...
    sourceSets {
        ...
        defaultConfig {
            testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
        }
    }
}

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

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'

编辑:

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

MockitoAnnotations.initMocks(this);

要么:

System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getTargetContext().getCacheDir().getPath());

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

androidTestCompile ('com.google.dexmaker:dexmaker-mockito:1.2') {
        exclude module: 'mockito-core'
    }

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

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

您需要恢复对MockitoAnnotations.initMocks()手动调用, MockitoAnnotations.initMocks()选择向Mockito.validateMockitoUsage()下拉调用。 当然,直接调用Mockito.mock (等等)仍然有效。

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

  相关解决方案