简体   繁体   English

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

[英]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 = ... //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.这个类有一个 json 字符串并从中检索一个查询字符串。 In between, there are a lot of steps, (deserializing, storing to POJO etc), and each step is handled by a different class.中间有很多步骤(反序列化、存储到 POJO 等),每个步骤都由不同的类处理。 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?). (如果那一步是正确的,那么上面的所有步骤也是正确的,对吧?)。

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.看,您可以轻松地分别测试 someMethod1() 和 someMethod2(),因此您可以依靠它们正常工作。 If your method divide most of it's responsibilities, you can test them separately as well.如果您的方法划分了大部分职责,您也可以单独测试它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM