Android单元测试没有嘲笑

时间:2015-04-01 22:46:35

标签: android unit-testing junit

我遵循了本指南 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 build一样修改了指南,但它并没有什么区别

 testOptions { 
    unitTests.returnDefaultValues = true
  }

4 个答案:

答案 0 :(得分:86)

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

要执行此操作,您需要将其添加到build.gradle:

testCompile 'org.json:json:20140107'

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

testCompile files('libs/json.jar')

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

答案 1 :(得分:3)

我认为您尝试使用org.json.JSONObject运行测试,Android Framework是纯jUnittheme的一部分。

来自docs:

  

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

     

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

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

的Android环境

答案 2 :(得分:2)

您需要在 build.gradle 中添加以下内容:

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

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

答案 3 :(得分:-3)

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

}