简体   繁体   中英

Changing Private Method Sign with Public for Unit Testing

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?

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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