Home » Android » android – How to mock JSONObject?

android – How to mock JSONObject?

Posted by: admin June 15, 2020 Leave a comment


In the middle of a method I’m doing something like this

JSONObject = new JSONObject(json);

Now I’m trying to unit test that using Android Studio and JUnit. Unfortunately, Android Studio won’t let me create a real JSONObject instance and ask me to mock it.

What’s the simplest way to keep that code and being able to unit test?

Mockito won’t help me since it’s not able to mock constructors, but it seems PowerMock is the way to go.

How to&Answers:

I’ve finally used Robolectric. It allows you to run tests simulating real device conditions. This makes unnecessary to mock frameworks classes.

Just need to add robolectric reference to gradle and decorate my test classes with @RunWith(RobolectricTestRunner.class)


You can create a mock JSONObject with the simple code

JSONObject mock = Mockito.mock(JSONObject.class);

Then you can easily mock it’s methods such as the field getters, to be able to return whatever you want from the JSONObject.

If the problem is that this JSONObject is created in the middle of a long function, you can extract the JSONObject creation to a collaborator and then mock the collaborator.

MyClass {
   MyClass(JSONObjectCreator creator) {
      this.creator = creator;
   public void doesSomethingWithJSON(String input) {
      JSONObject jsonObject = creator.createJSONObject(input);
JSONCreator {
   public JSONObject createJSONObject(String input) {
      return new JSONObject(input);

In your test you would create a mock JSONObject, and a new MyClass with a mocked JSONObjectCreator. The mocked JSONObjectCreator would return the mock JSONObject.