Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock JSONObject?

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.

like image 365
StackOverflower Avatar asked Nov 12 '15 22:11

StackOverflower


2 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)

like image 146
StackOverflower Avatar answered Oct 31 '22 23:10

StackOverflower


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.

like image 26
Andrew R. Freed Avatar answered Nov 01 '22 00:11

Andrew R. Freed