Reputation: 5660
Consider the function private void create (List<T> items)
. This code basically creates a tree provided an BFS traversed list. Now, assume this code returned root
and we could verify that it created tree, but doing traversals and verifying traversals match expectations. So far so good.
But :
Since this function is very complicated, should we be bother to test/verify that leftIndex
and rightIndex
calculations are done accuratately ?
If yes, then how to test those inner details of a function ?
In general, given a complex function, how to test the inner calculations which contribute to return value but are hidden from the use of API / function call ?
Upvotes: 4
Views: 770
Reputation: 69339
If you have a complicated private method that you feel would benefit from unit testing, a common approach is to make that method package-private so you can invoke it direct from a unit test. In your case, you might wish to make your traversal methods package-private, or produce a package-private getter method for root
.
But as a general rule of thumb, you should aim to unit test the contract of a particular class, without worrying greatly how that is achieved. That is, you should assure the expected outputs are produced based on a known set of inputs. The assumption is that the innards are working correctly if the outputs are correct. Code coverage tools can be useful for determining if your public API tests are exercising enough of your private code.
A desire to unit test the innards of a class may be a sign that the class has grown too large and would benefit from being decomposed into smaller, more testable classes. These classes can also be package-private, thus ensuring your overall public API is unaffected.
Upvotes: 6