Is unit testing alone ever a good reason to expose private instance variables via getters?

JavaUnit Testing

Java Problem Overview


I have a class used for navigating back and forth through a list of ordered pages. The pages are generally but not always accessed sequentially. Sometimes one or more pages may be skipped based on certain rules.

To manage this, I maintain two stacks, forward and backward, to track which pages have previously been visited in either direction.

As far as the functionality of this class is concerned, there is no reason for it to expose these stacks. However, when unit testing the navigation methods, first(), next(), previous() and last(), which all reorganize the stacks and return the appropriate page, I need to check that the stacks are in the right "state" at the end of the process.

For example, calling first() should cause the forward stack to be cleared and every other page that has previously been visited to be pushed into the backward stack.

Is this alone a good enough reason to provide getters for the forward and backward stacks? One reason I am hesitant to do so is that I worry that this also exposes them to (perhaps inadvertent) outside manipulation that might cause the class to malfunction. What if a client clears a stack for example?

UPDATE

Some people have suggested that this question is a duplicate of the one posted here. I think the 2 questions aren't quite the same. The other question discusses the idea of refactoring a private method to make it public in order to be able to test it. This question, on the other hand, is specifically about testing public methods by examining the internal state of the object under test. I think there is a subtle but significant difference there, and the accepted answer clearly shows how to test the very same public methods without examining internal state.

Java Solutions


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGitahi Ng'ang'aView Question on Stackoverflow