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

查看:730
本文介绍了我应该如何在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?

我的解决方案(private splitLetters => protected 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.


  • 私有方法具体是实现的一部分离子。您不应该测试实现,而是测试功能。如果您测试类暴露的功能,您可以根据单元测试更改实现。

  • 如果您觉得需要测试私有方法,这是一个好的迹象表明您应该将私有方法移动到另一个类并将该方法设置为public。通过这样做,您可以获得更小的类,并且可以轻松地测试方法。如果您不想公开这个新类,可以将它设为package-private(默认访问修饰符)。

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

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