我应该如何在 Java 中测试私有方法? [英] How should I test private methods in Java?

查看:36
本文介绍了我应该如何在 Java 中测试私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:单元测试私有方法的最佳方式是什么?

我是一名初级程序员,我不知道如何编写一个结构良好的单元测试应用程序.我想编写能够随后添加有效单元测试的应用程序.

I am a beginner programmer, and I don't know how to write an application that will be well structured for unit testing. I want to write applications with the ability to afterwards add effective unit tests.

问题出在 private 方法上 - 它们不能在它们的类之外进行测试.

The problem is with private methods - they can't be testing with outside of their classes.

我是否应该通过将所有 private 的方法更改为 protected 来解决这个问题,并让测试类扩展源类?或者有更好的解决方案吗?

Should I solve this problem by changing all methods that are private to protected, and let the test class extend source class? Or is there a better solution?

我的解决方案(私有 splitLetters => 受保护的 splitLetters)会像这样工作:

My solution (private splitLetters => protected splitLetters) would work like this:

源类:

class MyClass{
  protected splitLetters(int num){
    return num+2;
  }
}

测试类:

class Test_MyClass extend MyClass{
  public splitLettersTest(){
  for(int i=0;i<100;i++){
    System.println(parent.splitLetters(i));
  }
 }
}

解决方案:

  1. 不测试私有方法 - 有时私有方法正在执行非常复杂的任务,应该很好地进行测试,我们不希望该用户可以访问这些方法.很快,解决方案就是将私有方法更改为受保护的方法.

  1. Not testing private methods - Sometimes a private method is doing very complicated tasks that should be tested very well, and we don't want that user will have access to this methods. Soon the solution is changing private methods to protected.

用于测试的嵌套类方法 - 有问题,因为 QA 更改了源代码

Nested class way to test - problematic because QA make changes in source code

反射 - 如果这使得调用私有方法成为可能,它看起来是一个很好的解决方案http://www.artima.com/suiterunner/private3.html(我应该学习更多来理解反射.如果我们可以从另一个类调用私有方法,我不明白反射如何不会破坏拥有公共和私有方法的所有想法.)

Reflection - If this makes it possible to call private methods, it looks like a great solution http://www.artima.com/suiterunner/private3.html (I should learn more to understand reflection. I don't understand how reflections do not break all the idea of having public and private methods if we can call private methods from another class.)

未定义私有方法(正如我在我的解决方案中所展示的)- 有问题,因为有时我们必须定义私有方法.

Not define private methods (as I showed in my solution) - problematic because sometimes we have to define a private method.

推荐答案

您不应该需要测试私有方法.

You should not need to test private methods.

  • 私有方法是具体实现的一部分.您不应该测试实现,而应该测试功能.如果您测试类公开的功能,则可以根据单元测试更改实现.
  • 如果您觉得需要测试一个私有方法,这是一个好兆头,您应该将私有方法移到另一个类并将该方法设为公开.通过这样做,您可以获得更小的类,并且您可以轻松地测试这些方法.如果您不想公开这个新类,可以将其设为包私有(默认访问修饰符).

这篇关于我应该如何在 Java 中测试私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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