ContentValues的方法没有被模拟 [英] Method of ContentValues is not mocked

查看:220
本文介绍了ContentValues的方法没有被模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与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单元测试支持页面


Method ... not mocked。



用于运行单元测试的android.jar文件不包含任何实际代码 - 这是由真实设备上的Android系统映像提供的。相反,所有方法都会抛出异常(默认情况下)。这是为了确保您的单元测试仅测试您的代码,并且不依赖于Android平台的任何特定行为(您没有明确嘲笑,例如使用Mockito)。如果这证明有问题,您可以将下面的代码段添加到build.gradle中以更改此行为:

"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等价的类,否则只在本机代码中实现。

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的方法没有被模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆