Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method of ContentValues is not mocked

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.

Here is the minimal code:

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

What to do to avoid this error?

like image 621
Piotr Aleksander Chmielowski Avatar asked Apr 11 '16 17:04

Piotr Aleksander Chmielowski


1 Answers

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.

As on the 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
  }
}

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.

like image 169
Jeff Bowman Avatar answered Sep 22 '22 10:09

Jeff Bowman