Unit-testing – Unit test JSON parsing code

integration-testsunit testing

In my humble view of unit testing a unit test tests a single unit of code. For me, this means a single class. Every dependency for that class is mocked in the corresponding test class, and passed in the constructor (or injected via a DI container). This allows you to test the class in complete isolation from the rest of the system. I take this as the gospel truth of what a unit test is supposed to be. If you are testing multiple real classes (more than one class in your test class is not a mock) then you don't have a unit test, you have an integration test.

Given this point of view, there are things that seem to fall outside of the realm of unit testing even though it seems as if you are testing a single class. One of these types of tests is data parsing tests. For example, given a data class:

public class Person {
  private Name name;
  private PhoneNumber phoneNumber;
  private Address address;
}

a purported unit test then attempts to validate correct parsing:

@Test
public void shouldParsePerson() {
    String json = "{ the json would be here }";
    Person person = new Gson().fromJson(json, Person.class);

    assertThat(person.getName().getFirst()).isEqualTo("Jim");
    // more assertions based on what the JSON was would be here
}

What is this really testing? For me, it appears to be testing that Gson works. The test is tightly coupled to both the structure of the JSON and the class in Java that it maps to. Is the test really worth writing? Is it worth maintaining? Is it useful? Wouldn't an integration test somewhere else that relies on the parsing code catch this anyways?

There is another question here that is related to my question, but it is actually different because it is asking how to unit test consumers of an API that wraps third parts classes, while I'm asking what constitutes a valid unit test that involves a third party class. My question is more philosophical in nature, while the other is more practical. My question could also be extended to things like testing configuration code which isn't necessarily involving third party classes.

Best Answer

In general, unit testing should test your code, not the code of some library. Presumably the library already contains its own unit tests.

Certainly, one or two unit tests would help you get the feel of the library and how it works. But detailed testing of this kind generally falls under the purview of integration testing.