Reputation: 876
Assume that a stack has the following functions, pop
, push
, peek
and toArray
.
If I would like to write a unit test for, say, the push operation, how can this be done without knowing the underlying implementation? One possibility is to push something to an empty stack and test the stack.toArray()
against expected result, but that involves a function that is not under test.
Upvotes: 2
Views: 667
Reputation: 1134
You bring up kind of an interesting question. In truth, you have to test an ADT based on usage patterns, not individual methods.
Consider the requirements for a stack:
Well, that's certainly testable, but it's built into the return type, which is void
or unit
.
There's nothing directly observable about just the push action. Rather, it's specific combinations of actions that define a behaviour.
Hmm. This tests push
, but as you noted, you can't really resolve the second half without the other stack functions.
In a case like this, does it matter what happens when you push? No! What you care about is that some sequence of operations leads to a verifiable and consistent result.
This is true of unit testing in general: when you can, test each function individually. But when it doesn't make sense to do so, use patterns of behaviour instead.
Part of the reason you can't assume that pushing to the stack has an immediate result is that you're never given that guarantee. For example, imagine that your stack implementation uses a fancy buffer: each time you push, it adds the element to the buffer, but doesn't place it on the formal stack yet. Then, when you call peek
or pop
, it takes care of all the buffered items at once, then performs the operation. To you, the internals are invisible: all you care is that the total behaviour was consistent with that of a stack.
And that is, in essence, what makes it an ADT. We care about patterns of behaviour, not detailed implementation.
Upvotes: 2
Reputation: 31648
You can't really test the functions in isolation. If you want to test push()
you have to pop()
in order to test that that the elements pop out in the correct sequence.
You don't need to use toArray()
unless you want to write tests for it as well.
Upvotes: 1