问题描述
我正在使用 Mockito 创建一个测试.在测试中,我创建了一个 ContentValues
类型的对象.当我运行这个测试时,我得到了错误:
I'm creating a test with Mockito. In the test, I'm creating an object of type ContentValues
. When I run this test, I'm getting error:
java.lang.RuntimeException: Method put in android.content.ContentValues not mocked.
这是最少的代码:
import android.content.ContentValues;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Test
public void test1() {
ContentValues cv = new ContentValues();
cv.put("key", "value");
}
}
如何避免此错误?
推荐答案
你正在使用一个为模拟而设计的库,它缺乏实现.因为您的测试实际上调用了对象上的方法,而不使用模拟库来赋予它行为,所以它给了您该消息.
You are using a library designed for mocking, that lacks implementions. Because your test actually calls the method on the object, without using a mocking library to give it behavior, it's giving you that message.
用于运行单元测试的 android.jar 文件不包含任何实际代码 - 由真实设备上的 Android 系统映像提供.相反,所有方法都会抛出异常(默认情况下).这是为了确保您的单元测试只测试您的代码,而不依赖于 Android 平台的任何特定行为(您没有明确模拟,例如使用 Mockito).如果这证明有问题,您可以将以下代码段添加到您的 build.gradle 以更改此行为:
android {
// ...
testOptions {
unitTests.returnDefaultValues = true
}
}
要解决这个问题,请使用 Mockito 之类的模拟框架,而不是调用 put
之类的真实方法,或者切换到 Robolectric 以使用 Java 等效类,否则只能在本机代码中实现.
To work around it, use a mocking framework like Mockito instead of calling real methods like put
, or switch to Robolectric to use Java equivalents of classes otherwise implemented only in native code.
这篇关于ContentValues 的方法未被模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!