How to mock JSONObject?
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.