Assuming you want to build automated tests for the following (very simple, if odd) class.
// Calculates the distance between neighboring values in a vector
// and provides functions to return the distance from one index to the following
// or to find the first occurrence of a specified distance
class NeighborDistanceFinder
{
public:
NeighborDistanceFinder(std::vector<int> inputVector)
: m_neighborVector(inputVector) { };
int getDistanceToNextIndex(int index) const
{
if (index >= 0 && index < m_neighborVector.size() - 1)
return calculateDistance(index, index + 1);
throw "Provided index is invalid";
}
int getIndexOfFirstOccurenceOfDistance(int distance) const
{
for (int index = 0; index < m_neighborVector.size() - 1; i++)
{
if (calculateDistance(index, index + 1) == distance)
return index;
}
throw "Distance not found";
}
private:
std::vector<int> m_neighborVector;
int calculateDistance(int index, int otherIndex) const
{
const int lastIndex = m_neighborVector.size() - 1;
if (index < 0 || otherIndex < 0 || index > lastIndex || otherIndex > lastIndex)
throw "Index of of bounds"; //This should never happen
return m_neighborVector.at(index) - m_neighborVector.at(otherIndex);
}
}
In such a simple class the bounds check for calculateDistance()
is probably overkill, but imagine the condition to check being more complex than a simple bounds check and more functions calling calculateDistance()
, functions mucking around with m_neighborVector
and soon it looks more and more appealing...
In any case, with this masterwork at hand we suddendly realize we did not do TDD and don't have any unit tests. Well, no fear, they are simple enough to add (... a few hours later ...). Done.
But there is a gap in in our code coverage: we cannot reach throw "Index of of bounds";
(unless I made a mistake in writing this example...). Well, of course, we catch the out-of-bounds cases in the two public functions invoking it, and the function is private so we cannot invoke it directly (as we lack reflection in C++). I know, static code analysis should be able to tell us that this is essentially dead code, but again: Imagine the condition being more complex.
So what should be done concerning this very-defensive private function at this point?
- The gap is fine - you don't need (and will never get) 100% coverage - just move on.
- This is overkill defensive programming in a private function - get rid of the check, FFS.
- You need to cover this - move the function to protected or make your test a friend class etc.
- And now for something completely different?
vector::at
already throwsstd::out_of_range
, so I would say both "Provided index is invalid" and "Index of of bounds" are superfluous