Android 未模拟单元测试

Android unit test not mocked

我遵循了这个指南 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
  }

我认为您正在尝试 运行 测试 org.json.JSONObject,它是 Android Framework 的一部分,纯 jUnit

来自文档:

The android.jar file that is used to run unit tests does not contain any actual code - that is provided by the Android system image on real devices. Instead, all methods throw exceptions (by default).

We are aware that the default behavior is problematic when using classes like Log or TextUtils and will evaluate possible solutions in future releases.

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

JSON 与 Android SDK 捆绑在一起,因此您只会碰到一个存根。您可以拉入一个 JSON jar,它将提供真实的对象供您使用。

为此,您需要将此添加到您的 build.gradle:

testImplementation 'org.json:json:20140107'

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

testCompile files('libs/json.jar')

请注意,最新版本的 JSON 是为 Java 8 构建的,因此您需要获取 20140107 您可能还需要清理并重建项目。

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

}

您需要将以下内容添加到 build.gradle:

android {
  // ...
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}

dependencies {
//...
    testImplementation 'org.json:json:20180813'
}

如果您使用的是 Kotlin DSL,问题的解决方案:

testOptions {
    unitTests.isReturnDefaultValues = true
}

testImplementation("org.json:json:20210307")