Unit testing as applied to private methods
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 feat开发者_StackOverflowure 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?
I see 2 possible ways:
- If possible - to move the algorithm implementation to another class and split it to methods. Test methods after.
- Just write a bunch of tests that cover possible normal cases, edge cases and error cases.
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.
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?
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.
精彩评论