gpt4 book ai didi

java - ContentValues 的方法未被模拟

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:47 24 4
gpt4 key购买 nike

我正在使用 Mockito 创建测试。在测试中,我创建了一个 ContentValues 类型的对象。当我运行此测试时,出现错误:

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");
}
}

如何避免此错误?

最佳答案

您正在使用一个为模拟而设计的库,它缺少实现。因为您的测试实际上是在对象上调用方法,而不使用模拟库来赋予它行为,所以它会向您提供该消息。

Android Unit Testing Support page 上:

"Method ... not mocked."

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). This is to make sure your unit tests only test your code and do not depend on any particular behaviour of the Android platform (that you have not explicitly mocked e.g. using Mockito). If that proves problematic, you can add the snippet below to your build.gradle to change this behavior:

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

要解决它,请使用像 Mockito 这样的模拟框架,而不是调用像 put 这样的真实方法,或者切换到 Robolectric 以使用类的 Java 等价物,否则只能在 native 代码中实现。

关于java - ContentValues 的方法未被模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36555136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com