将私有方法的访问权限从私有改为公共以进行单元测试

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

Changing Private Method Sign with Public for Unit Testing

问题

我知道改变私有方法的访问级别会违反封装原则。此外,私有方法是实现细节。但我想知道,如果该方法不影响或破坏系统的其他部分,是否可以将方法的访问级别改为公共?

例如;

我有一个包含 switch-case 语句块的方法;

private Object foo(Object object, MyTypeEnum type) {
    ....
    switch(type) {
        case type.x:
            return "a";
        case type.y:
            return "b";
        case type.z:
            return "c";
        .
        .
        .
    }
    ..
}

此外;

  • 将该方法移动到工具类中以使其访问级别变为公共是不好的实践,因为该方法不是通用的可重用的
  • 测试调用私有方法(foo)的公共方法是解决方案之一。然而,我的代码库中有很多遗留代码和未经测试的代码,所以我必须更改其他类和方法。此外,我没有足够的时间来重构代码库的其他部分。

您对我在这种情况下的建议是什么?

英文:

I know that changing private method's sign with public ignore encapsulation principle. In addition, private method is an implementation detail. But I wonder that if the method does not effect or break other part of system, can i make the method's signature public?

For instance;

I have a method which contains switch-case block;

private Object foo(Object object, MyTypeEnum type) {
    ....
    switch(type) {
      case type.x:
         return "a";
     case type.y:
         return "b";
     case type.z:
         return "c";
     .
     .
     .
  }
  ..
 }

In addition;

  • Moving the method in utils class to be able to make its sign public is bad practise since the method is not generic and reusable
  • Testing a public method which calls the private method(foo) is one of solutions. However, my codebase has a lot of legacy and untested code so i have to change other classes and methods. Furthermore, I have no enough time refactor other part of my codebase.

What do you advice to me for this case ?

答案1

得分: 2

你已经知道这不是一个好的做法,但尝试测试工作但未经测试的旧代码通常不是一个明智的时间投资,因为正是因为这些确切的原因。你不希望花费很长时间来重新模型化旧的东西,只是为了添加测试;实际上,这会增加在生产中发生意外情况的风险。参考 https://stackoverflow.com/questions/1541568/adding-unit-tests-to-legacy-code

在这种情况下,我总是试图在更高的层次上进行测试,而不是在单独的类的单独方法中进行测试。

英文:

You already know this isn't good form but trying to test working but untested legacy code is not a good investment of time generally because of these exact reasons. You don't want to spend ages remodelling the old stuff just to add tests; It actually increases risk of something unexpected happening in production. See https://stackoverflow.com/questions/1541568/adding-unit-tests-to-legacy-code

In such circumstances I always try to test at a higher level rather than individual methods in individual classes.

huangapple
  • 本文由 发表于 2020年8月18日 20:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63468474.html
匿名

发表评论

匿名网友

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

确定