应用于私有方法的单元测试
我目前正在尝试创建一些类来进行一些傅里叶变换。 我尝试首先创建一些单元测试,然后构建基本功能。
问题是,我可以编写一个测试来看看算法是否有效,并且我知道预期的结果。然后我开始构建大算法,如果它有效,我的单元测试就会通过。
我的问题是,这并不是真正的 TDD。因为通常您会创建测试来测试类的非常基本的功能。现在我的类基本上执行一个大算法,我无法测试该算法的较小部分,因为它们不是公开的(我总是被告知你永远不想测试私有方法)。
你如何处理这个问题?
I'm currently trying to create some classes to do some Fourier Transformations.
I'm trying to do it by creating some unit tests first, then build the basic functionality.
The problem with this is, is that well, I can write one test to see if the algorithm works, and I know the expected outcome. Then I start building the big algorithm, and if it works my unit tests will pass.
My problem here is, it's not really TDD. Because usually you create tests that test a very basic feature of a class. Now my class basically executes one big algorithm, and I can't test the smaller parts of the algorithm, since they are not public (I've always been told you'd never want to test private methods).
How do you deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我看到两种可能的方法:
I see 2 possible ways:
我最近一直在纠结“什么是单位?”这确实是一个棘手的问题。
如果您有理由相信 FFT 的子单元特别容易出错,那么请设置边界条件并打破私有方法豁免的规则。
另一种说法是,子单元实际上是 FFT 使用其服务的单元,那么您就没有违反规则。
I've recently been battling with "what is a unit?" which is a tricky question indeed.
If you have reason to believe that the sub-units of an FFT are particularly error prone, then rig up the boundary conditions and break the rule that private methods are exempt.
Another way to say the same thing is the sub-unit is actually a unit whose services are used by the FFT, and then you are breaking no rule.
那么,如果您的类只有一个可测试方法(根据仅测试公共方法的标准),那么您别无选择,只能测试该方法,对吗?然而,这并不意味着它不是 TDD——而且您当然可以测试各种各样的输入值。这里的大部分工作将是寻找有趣的值 - 您的转换可能会失败的边缘情况是什么?是否存在无效输入以及如何处理?
有什么方法可以对许多值进行算法验证,例如调用已知良好的例程,使用一些关键的傅里叶相关识别,或者使用 FFT 来执行 乘法?
Well if your class only has a single testable method (per your criterion of only testing public methods), then you have little choice but to test only that method, right? That doesn't mean that it's not TDD, however - and you can certainly test a large variety of input values. Most of the work here will be finding the interesting values - what are the edge cases that your transform might fail on? Is there any invalid input and how is it handled?
Is there some way you can do algorithmic validation of many values, such as calling a known-good routine, using some key Fourier related identify, or perhaps using your FFT to do multiplication?
我认为,如果您无法测试算法的各个组件,则要么代码耦合非常紧密,要么代码非常程序化。
您可能必须将代码定义为单元并将这些单元设置为受保护的方法。只要该方法受到保护,它就会发送一个明确的消息,表明它不是 API 的一部分。
I think if you could not test individual components of your algorithm, either the code is very tightly coupled or the code is very procedural.
You might have to define your code as units and make these units as protected method. As long as the method is protected, it sends a clear message that it is not part of the API.