安卓编写工具方法单元测试

3
我正在编写一个静态实用方法的单元测试:

我正在为一个静态实用方法编写单元测试:

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);
}

这是单元测试:

@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);
}

JokeItem 是一个简单的 pojo 类。我面临的问题是,我不确定我的测试用例是否正确,因为我在两个方法中基本上使用相同的方法 gson.toJson(object)。如果能够获得一些关于测试这种函数及其方法中的缺陷和不足之处的见解,那将非常有帮助。


如果你正在使用Google的gson,为什么要对它进行单元测试?我只测试我可以主动更改/重构并在使用第三方库时依赖于各自开发人员进行测试的代码。唯一的例外是当我自己发现库中的错误并想要证明它时。 - Smutje
正确的方法是使用 new Gson().toJson(item);,因为当您在 JokeItem 中有更多属性时,您可能需要更改自定义即 required1 - Smit
2个回答

3

对于 Gson 进行单元测试没有意义 - 它已经被作者测试过了。
由于你的方法非常简单,我认为只有第一个 if 语句需要进行测试,并检查是否在传递 null 对象时抛出 NullPointerException
如果你想创建更强大的测试,我建议检查与 GsonGsonBuilder 的交互,以验证是否调用了正确的方法。但这需要对这两个对象进行监视。


3

测试这样的方法其实非常简单 - 你创建一系列测试,用特定的输入调用该方法; 然后检查返回的结果。例如:

@Test(expected=NullPointerException.class)
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 ...

也许你不需要更多的东西 - 正如Marek所指出的那样; 你不应该开始Gson实现。
但是:你绝对想要测试方法中的所有可能路径;在你的情况下,你只需要确保你得到一些预期的输出,针对某个固定的输入(包括所有不同种类的“无效”输入!)。
最后,在代码质量方面:编写这样的小帮手作为静态方法很诱人;并且使用布尔值作为参数,但是...这不是一个好的OO设计。考虑这个:
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

而不是担心使用true/false并且紧密耦合该静态方法的用户到实现(以后很难分开),你可以只传递JsonBuilder接口的对象。然后,您的代码只调用那个方法,无需进一步担心。
也许在这里有些过度,但仍然值得考虑的方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接