Reputation: 439
I have a class player in which there is a private variable private int step=10
and a function moveLeft()
which decrements the x coordinate of the player by the value stored in variable step
Now I want to write a JUnit test case for the moveLeft() method so I create a player object and store it's initial position and then call the function moveLeft() on it.
But to verify that the player did move by step number of points in the x direction I need to do something like player.getPosition().x==initilX-step
But step is a private variable
in the class player. In this case, how can I go about writing a JUnit test for it?
Upvotes: 0
Views: 1148
Reputation: 718758
There are a number of ways to deal with this:
Write the tests as blackbox tests; i.e. don't make them depend on the state of the private variable at all. This can be harder to achieve, but it will have a couple of benefits:
It will make your tests independent of the implementation details associated with that variable.
It will cause you to focus your testing more on specified behavior of the API.
As Tom suggests: write a public
(or maybe package private) getter. It exposes the state, but the chances are that it doesn't matter. (Bear in mind that the pragmatic purpose of visibility modifiers is to prevent unwanted coupling. But unnecessary exposure of internals doesn't actually cause coupling. Some other code has to use the internals for there to be coupling.)
You could leave the variable as private
but have your test code use reflection to reach in and inspect (or even change) private variables.
You might be able to avoid this by mocking the class of the private variable in the unit tests ... or something like that. (This is probably not applicable here.)
Upvotes: 1
Reputation: 5677
Add a public getter in your Player
class :
public int getStep() {
return this.step;
}
Upvotes: 1