我已经阅读了这篇关于如何测试私有方法的文章。我通常不测试它们,因为我总是认为只测试将从对象外部调用的公共方法更快。你测试私有方法吗?我应该一直测试它们吗?


当前回答

I understand the point of view where private methods are considered as implementations details and then don't have to be tested. And I would stick with this rule if we had to develop outside of the object only. But us, are we some kind of restricted developers who are developing only outside of objects, calling only their public methods? Or are we actually also developing that object? As we are not bound to program outside objects, we will probably have to call those private methods into new public ones we are developing. Wouldn't it be great to know that the private method resist against all odds?

我知道有些人会回答说,如果我们正在开发另一个公共方法到那个对象中,那么这个方法应该被测试,就是这样(私有方法可以在没有测试的情况下继续存在)。但这也适用于一个对象的任何公共方法:当开发一个web应用程序时,一个对象的所有公共方法都是从控制器方法调用的,因此可以认为是控制器的实现细节。

那么为什么我们要单元测试对象呢?因为这是非常困难的,不是说不可能,以确保我们正在测试控制器的方法与适当的输入将触发底层代码的所有分支。换句话说,我们在堆栈中的位置越高,测试所有行为就越困难。私有方法也是如此。

对我来说,私人方法和公共方法之间的界限是测试时的心理标准。对我来说更重要的标准是:

该方法是否在不同的地方被多次调用? 这种方法是否复杂到需要测试?

其他回答

I understand the point of view where private methods are considered as implementations details and then don't have to be tested. And I would stick with this rule if we had to develop outside of the object only. But us, are we some kind of restricted developers who are developing only outside of objects, calling only their public methods? Or are we actually also developing that object? As we are not bound to program outside objects, we will probably have to call those private methods into new public ones we are developing. Wouldn't it be great to know that the private method resist against all odds?

我知道有些人会回答说,如果我们正在开发另一个公共方法到那个对象中,那么这个方法应该被测试,就是这样(私有方法可以在没有测试的情况下继续存在)。但这也适用于一个对象的任何公共方法:当开发一个web应用程序时,一个对象的所有公共方法都是从控制器方法调用的,因此可以认为是控制器的实现细节。

那么为什么我们要单元测试对象呢?因为这是非常困难的,不是说不可能,以确保我们正在测试控制器的方法与适当的输入将触发底层代码的所有分支。换句话说,我们在堆栈中的位置越高,测试所有行为就越困难。私有方法也是如此。

对我来说,私人方法和公共方法之间的界限是测试时的心理标准。对我来说更重要的标准是:

该方法是否在不同的地方被多次调用? 这种方法是否复杂到需要测试?

我不是这方面的专家,但是单元测试应该测试行为,而不是实现。私有方法严格来说是实现的一部分,所以不应该测试IMHO。

不,你不应该测试私有方法,为什么?此外,流行的mock框架(如Mockito)不支持测试私有方法。

我从来不理解单元测试的概念,但现在我知道它的目标是什么了。

单元测试不是一个完整的测试。所以,它并不是QA和手动测试的替代品。在这方面,TDD的概念是错误的,因为你不能测试所有的东西,包括私有方法,也包括使用资源的方法(特别是我们无法控制的资源)。TDD的所有质量都是无法实现的。

单元测试更像是一个枢轴测试,你标记一些任意的枢轴,枢轴的结果应该保持不变。

如果你的私有方法没有通过调用公共方法来测试,那么它在做什么? 我说的是私人的,不是受保护的,也不是朋友。