适当的方法封装以进行单元测试 [英] Appropriate method encapsulation for unit testing

查看:182
本文介绍了适当的方法封装以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级包含14 private methods1 public method.公共方法直接或通过其他私有方法间接调用所有私有方法.

My class contains 14 private methods and 1 public method. The public method calls all the private method directly or indirectly via other private methods.

public方法还具有对查询数据库的DAO的调用. 我为班级写了单元测试.由于您不能为私有方法编写单元测试,因此我将所有私有方法都更改为默认访问权限,并为它们编写了单元测试.

The public method also has a call to a DAO that queries the database. I wrote a unit test for the class. Since you can't write unit test for private methods, I changed all the private methods to default access and wrote unit test for them.

有人告诉我,不应仅出于测试目的而更改封装.但是我的公共方法有一个对DAO的调用,并从该调用中获取其数据.即使我要为公共方法编写测试,我也认为这将是漫长而复杂的.

I was told that I shouldn't change the encapsulation just for the purpose of testing. But my public method has a call to the DAO and gets its data from the call. Even if I were to write a test for the public method, I'm assuming it would be really long and complicated.

我应该如何解决这个问题.一方面,我必须为访问DAO的公共方法编写一个非常复杂的测试,另一方面,更改方法的访问级别并为它们编写简短的简单测试方法.我该怎么办?

How should I approach this problem. On one hand, I have to write a really complicated test for the public method which accesses a DAO and on the other hand, change the access level of the methods and write short, simple test methods for them. What should I do?

任何建议将不胜感激

推荐答案

Purists将告诉您,私有方法可以提取到另一个提供可访问方法的帮助器类中,并且它们可能是正确的.

Purists will tell you that the private methods could be extracted to another helper class providing accessible methods, and they could be right.

但是如果将这些实用程序方法保留在类中是有意义的,则如果该类不是公共API的一部分并且不打算被子类化(例如,它可能是最终的),那么我看不到任何使某些私有方法受到程序包保护或受保护的问题.尤其是如果记录了这种非私有可见性,例如带有Guava注释@VisibleForTesting.

But if it makes sense to keep these utility methods inside the class, if the class is not part of a public API and is not intended to be subclassed (it could be final, for example), I don't see any problem with making some of its private methods package-protected or protected. Especially if this non-private visibility is documented, for example with the Guava annotation @VisibleForTesting.

这篇关于适当的方法封装以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆