JUnit测试用于具有多个方法调用的类

huangapple go评论82阅读模式
英文:

JUnit test for Class with multiple method calls

问题

Class QueryGenerator
.. 
  String generateQuery()
  {
    final String jsonString = anotherClass1.method();
    final Map<String, List<POJO>> map = someMethod1(jsonString);
    final List<POJO> pojos = someMethod2(map);
    final POJO chosen_pojo = anotherClass2.method();
    final String query = ... //执行操作以生成查询语句;
  }
.. 
  someMethod1() { //执行操作 };
  someMethod2() { //执行操作 };
}

这个类拥有一个 JSON 字符串,并从中提取查询字符串。在中间,有许多步骤(反序列化,存储到 POJO 等),每个步骤由不同的类处理。所有这些类都从这个方法中调用。

对于单元测试,仅测试最终步骤是否足够确保生成的查询正确吗?(如果该步骤正确,则其上面的所有步骤也都是正确的,对吗?)。

英文:
Class QueryGenerator
..
  String generateQuery()
  {
   final String jsonString = anotherClass1.method();
   final Map&lt;String, List&lt;POJO&gt; map = someMethod1(jsonString);
   final List&lt;POJO&gt; pojos = someMethod2(map);
   final POJO chosen_pojo = anotherClass2.method();
   final String query = ... //do something to generate the query;
  }
..
  someMethod1() { //do something};
  someMethod2() { //do something};
}

This class has a json string and retrieves a query string from it. In between, there are a lot of steps, (deserializing, storing to POJO etc), and each step is handled by a different class. All of these classes are called from this method.

For unit test, is it enough to test only the final step to ensure the query generated is correct? (If that step is correct, all steps above it is also correct, right?).

答案1

得分: 1

如果你的方法一次性执行许多不同的操作,你可能应该将它的职责分解为不同的方法甚至不同的类。如果你的方法变得更难以进行单元测试,那是因为它承担了过多的职责。你可以看到你的方法使用了许多不同的数据,实际上这些数据完全可以由其他类来处理,所以你应该首先重构你的方法,使其实际上只执行最后一部分操作。

你可以轻易地分别测试 someMethod1() 和 someMethod2(),这样你就可以依赖它们正常工作。如果你的方法分解了大部分的职责,你也可以分别对它们进行测试。

英文:

If your method does so many different things at once, you probably should divide it's responsibilities to different methods or even classes. If your methods become harder to unit-test is because your methods has to much responsibilities. You can see how your methods use so many different data that really could be processed by other classes as well so you should at first refactor your method to make it actually performing only last part.

See, you can easily test someMethod1() and someMethod2() separately so you can rely on them working properly. If your method divide most of it's responsibilities, you can test them separately as well.

huangapple
  • 本文由 发表于 2020年10月14日 12:52:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64346800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定