On 26/06/2015 09:02, Merrill Cornish wrote:
On 6/25/2015 3:52 PM, Jürgen Hunold wrote:
In my opinion, a test should never access private data. But there are times and legacy code where I had no other choice, too.
The classes I am testing use the PIMPL idiom. Therefore, at a bare minimum, the tests have to access the private pointer in the public class that points to the accompanying private class. Since all of the class's data is inside the private class, it make it extremely difficult to write unit tests that determine if the class state is correct. I see no value in the purist notion that I should have to jump through hundreds of hoops deducing the internal state /just/ so I can say my test never accessed any private data.
That's a misrepresentation of the "purist notion". The idea is that you only test a class through its public methods, because these are the only things that can be observed from "outside", and therefore describes the real behaviour that actually matters. One of the good things that this enables is that it becomes possible to completely change the internal implementation (perhaps to improve performance, perhaps to use a different helper library) and as long as the behaviour remains the same, all the tests continue to pass without changes. Tests that look at internal state are brittle to these sorts of changes, so it becomes harder to tell whether the test breakage is because the refactoring unintentionally changed behaviour or just that the test isn't checking the right thing any more. If it becomes hard to "deduce the internal state" then it's likely that your class has too many responsibilities, and you should consider breaking it up into smaller individually tested components and a top-level composite. (This also increases the chances that one of those components might be usefully reusable elsewhere.)