Unit Tests - lemberg/android-json-serializable-sample GitHub Wiki

This implementation of Json unit tests require instance of Application Context. In this case developer should use AndroidTestCase or InstrumentationTestCase. All test case classes of Android SDK extend TestCase class from JUnit framework that gives ability easy to implement tests. Also, this implementation using JsonUnit library for Json assertion.


Preparations for testing

public class JsonSerializableTest extends InstrumentationTestCase {

    private Utils utils;

    private static final String JSON_READING_EXPECTED = "{\"field1\":1,\"field2\":1.0,\"field3\":true,\"field4\":\"test\",\"field5\":{\"key1\":\"test\",\"key2\":\"test\",\"key3\":\"test\"}}";

    @Override
    public void setUp() throws Exception {
        super.setUp();

        utils = new Utils(getInstrumentation().getContext());
    }

    @Override
    public void tearDown() throws Exception {
        utils = null;

        super.tearDown();
    }
    
    //tests will follow here
}

JsonSerializableTest contains an instance of Utils class. Utils provide some help methods, such as generating objects, generating lists of objects, and method, that allow to read Json from some file at the assets directory of the test project ([src/androidTest/assets]).

public class Utils {

	private static final String UTF_8_CODING = "UTF-8";

    private Context context;

    public Utils(Context context) {
        this.context = context;
    }

    public String loadJsonFromAsset(String assetName) {

        String outputJson = null;

        try {
            InputStream inputStream = context.getResources().getAssets().open(assetName, AssetManager.ACCESS_STREAMING);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            outputJson = new String(buffer, UTF_8_CODING);

        } catch (IOException ignore) {
            ignore.printStackTrace();
        }

        return outputJson;
    }

	public UserProfile getUserProfile() {/*...*/}
	public List<UserProfile> getUserProfileList() {/*...*/}
	public Map<String, UserProfile> getUserProfileMap() {/*...*/}
}

UserProfile - it's a test object, that will be converted into Json string and viceverca.

public class UserProfile {

    @SerializedName("username")
    private String name;

    @SerializedName("surname")
    private String surname;

    @Expose(serialize = false)
    private String nickname;

    @SerializedName("age")
    private int age;

    @Expose(deserialize = false)
    private boolean married = false;

    public UserProfile(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }

	//getters and setters
	//equals() and hashcode()

At least, needs to create Json files, that will be uses by tests. Single object example

{
  "username" : "test-username",
  "surname" : "test-surname",
  "age" : 1,
  "married" : true
}

List of objects example

[
  {
    "username": "test-username-1",
    "surname": "test-surname-1",
    "age": 1,
    "married" : false
  },
  {
    "username": "test-username-2",
    "surname": "test-surname-2",
    "age": 2,
    "married" : false
  },
  ...
]

Key value objects example

{
  "test-1": {
    "username": "test-username-1",
    "surname": "test-surname-1",
    "age": 1,
    "married" : false
  },
  "test-2": {
    "username": "test-username-2",
    "surname": "test-surname-2",
    "age": 2,
    "married" : false
  },
  ...
}

Corrupted Json example

{
  'username' => 'test-username';
  'surname' => 'test-surname';
  'age' => 1;
  'married' => true
}

Json testing 1.Json reading test

public void testJsonReadingFromAssets() {

        String actualJson = utils.loadJsonFromAsset("json_for_reading.json");

        JsonAssert.assertJsonStructureEquals(JSON_READING_EXPECTED, actualJson);
        JsonAssert.assertJsonEquals(JSON_READING_EXPECTED, actualJson);
    }

2.Json into Object/List/Map transformation tests

public void testObjectsFromJsonEquals() {

        UserProfile expectedProfile = utils.getUserProfile();
        UserProfile actualProfile = JsonSerializable.fromJsonUnsafe(UserProfile.class, utils.loadJsonFromAsset("user_profile.json"));

        assertEquals(expectedProfile, actualProfile);
    }

    public void testListEqualsFromJson() {

        List<UserProfile> expectedList = utils.getUserProfileList();
        List<UserProfile> actualList = JsonSerializable.toList(utils.loadJsonFromAsset("user_profile_array.json"), UserProfile.class);

        assertEquals(expectedList, actualList);
    }

    public void testMapsEqualsFromJson() {

        Map<String, UserProfile> expectedMap = utils.getUserProfileMap();
        Map<String, UserProfile> actualMap = JsonSerializable.toMap(utils.loadJsonFromAsset("user_profile_map.json"), String.class, UserProfile.class);

        assertEquals(expectedMap, actualMap);
    }

3.Object/List/Map into Json transformation test

public void testJsonEquals_objects() {

        String expectedJson = utils.loadJsonFromAsset("user_profile.json");

        UserProfile profile = utils.getUserProfile();
        profile.setMarried(true);

        String actualJson = JsonSerializable.toJson(profile);

        JsonAssert.assertJsonStructureEquals(expectedJson, actualJson);
        JsonAssert.assertJsonEquals(expectedJson, actualJson);
    }

    public void testJsonEquals_list() {

        String expectedJson = utils.loadJsonFromAsset("user_profile_array.json");
        String actualJson = JsonSerializable.toJson(utils.getUserProfileList());

        JsonAssert.assertJsonStructureEquals(expectedJson, actualJson);
        JsonAssert.assertJsonEquals(expectedJson, actualJson);
    }

    public void testJsonEquals_map() {

        String expectedJson = utils.loadJsonFromAsset("user_profile_map.json");
        String actualJson = JsonSerializable.toJson(utils.getUserProfileMap());

        JsonAssert.assertJsonStructureEquals(expectedJson, actualJson);
        JsonAssert.assertJsonEquals(expectedJson, actualJson);
    }

4.Tests of using @expose() annotation

public void testExposeAnnotation_serialize() {

        UserProfile profile = utils.getUserProfile();
        profile.setNickname("test-nickname");
        profile.setMarried(true);

        String expectedJson = utils.loadJsonFromAsset("user_profile.json");
        String actualJson = JsonSerializable.toJson(profile);

        JsonAssert.assertJsonStructureEquals(expectedJson, actualJson);
        JsonAssert.assertJsonEquals(expectedJson, actualJson);
    }

    public void testExposeAnnotation_deserialize() {

        UserProfile expectedProfile = utils.getUserProfile();
        UserProfile actualProfile = JsonSerializable.fromJsonUnsafe(UserProfile.class, utils.loadJsonFromAsset("user_profile.json"));

        assertEquals(expectedProfile, actualProfile);
    }

5.Corrupted Json test

public void testCorruptedJson() {

        UserProfile expectedProfile = utils.getUserProfile();
        UserProfile actualProfile = JsonSerializable.fromJsonUnsafe(UserProfile.class, utils.loadJsonFromAsset("user_profile_wrong.json"));

        assertEquals(expectedProfile, actualProfile);
    }

Full implementation you can find here.