subash subash - 1 year ago 80
Java Question

Android writing Unit test for utility methods

I am writing unit test for a static utility method:

public static String getString(Object object, boolean prettyPrint) {
if (object == null) {
throw new NullPointerException("Cannot pass null to Utility.getString() method");
Gson gson;
if (prettyPrint) {
gson = new GsonBuilder().setPrettyPrinting().create();
} else {
gson = new Gson();
return gson.toJson(object);

Here's the unit test:

public void getString() throws Exception {
JokeItem item = new JokeItem("title", "joke");
String required = new Gson().toJson(item);
String actual = Utility.getString(item, false);
Assert.assertEquals(required, actual);
String required1 = "{\"joke\":\"joke\",\"title\":\"title\"}";
String actual1 = Utility.getString(item, false);
Assert.assertEquals(required1, actual1);

is a simple pojo class. The problem I am facing is that I am not sure if my test case if the right way to test this method because I am basically using the same method
in both the methods.It would be very helpful if I could get some insights in testing this kind of functions and pitfalls and inadequacies in my approach.

Answer Source

Testing such methods is actually pretty easy - you create a series of tests that call the method with specific input; and then you check what is coming back. Like:

public testCtorWithNullStringAndTrue() {
  Whatever.getString(null, true);
// same for false

// and then
public testSomeInput() {
  assertThat(Whatever.getString("whatever", true), is("expected-json-string"));
} // same for false ...

Probably you won't need much more than that - as Marek has pointed out; you should not starting Gson implementations.

But: you definitely want to test all possible paths within your method; in your case you simply want to make sure that you get back some expected output for a certain, fixed input (including all different kinds of "invalid" input!).

Finally, on code quality: it is tempting to write such little helpers as static methods; and to use a boolean as argument, but ... this is not a good OO design. Consider this:

interface JsonBuilder {
   String getString(Object input);

class SimpleBuilder implements JsonBuilder 
// does what your "non-pretty print code" does

class PrettyBuilder implements JsonBuilder
// does the other thing

And instead of worrying about using true/false; and tightly coupling the users of that static method to the implementation (hard to break up later on); you can just pass around objects of the JsonBuilder interface. And your code just calls that one method, without further worrying.

Maybe overkill here, but still an approach worth thinking about.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download