Androidunit testing没有被嘲笑

我遵循本指南https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support,但我坚持这个错误:

junit.framework.AssertionFailedError: Exception in constructor: testSaveJson (java.lang.RuntimeException: Method put in org.json.JSONObject not mocked. See https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support for details. 

我修改了Gradle构建像指南说,​​但它没有区别

  testOptions { unitTests.returnDefaultValues = true } 

JSON与Android SDK捆绑在一起,所以你只需要打一个存根。 你可以拉一个JSON jar,这将提供真正的对象使用。

要做到这一点,你需要添加到您的build.gradle:

testCompile 'org.json:json:20140107'

或者,您可以下载并包含jar。

 testCompile files('libs/json.jar') 

请注意,最新版本的JSON是为Java 8构建的,因此您需要获取20140107

我想你试图运行org.json.JSONObject是纯粹的jUnitAndroid Framework一部分的jUnit

从文档:

用于运行unit testing的android.jar文件不包含任何实际的代码 – 由真实设备上的Android系统映像提供。 相反,所有方法都会抛出exception(默认情况下)。

我们知道使用Log或者TextUtils这样的类时,默认行为是有问题的,并且会在将来的版本中评估可能的解决方案。

您需要模拟您可以用于Robolectric或InstrumentationTests的Android环境

 android { testOptions { unitTests.returnDefaultValues = true } } dependencies { testImplementation libs.leakCanaryNoOp testImplementation tests.jUnit testImplementation tests.mockito testImplementation(tests.mokitoKotlin) { exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib" exclude group: "org.jetbrains.kotlin", module: "kotlin-runtime" exclude group: "org.jetbrains.kotlin", module: "kotlin-reflect" exclude group: "org.mockito", module: "mockito-core" } testImplementation tests.powerMock testImplementation tests.powerMockApiMockito testImplementation (tests.robolectric) { exclude group: 'org.robolectric', module: 'robolectric-resources:' } testImplementation (tests.robolectricShadowsSupport){ exclude group: 'org.robolectric', module: 'robolectric' } kaptTest libs.daggerCompiler 

}