101

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.

Community
  • 1
  • 1
Gitahi Ng'ang'a
  • 901
  • 3
  • 10
  • 23
  • This is quite a common question, both on SO and else where. To save repeating myself check the possible duplicates suggested. I've added my thoughts to a blog post too, because this is such a common misunderstanding http://blog.shaunfinglas.co.uk/2015/05/testing-private-code.html – Finglas Jul 28 '15 at 08:10
  • If your question is *specifically about testing public methods by examining the internal state of the object under test,* then that's what should be in the title. – Robert Harvey Jul 29 '15 at 16:59

0 Answers0