OPK
OPK

Reputation: 4180

How to test unexpected return results in jUnit

I am writing a test case for the Pacman game. One thing I am confused and not sure how to proceed.

I have a method int move(int stpes); It returns an int value and to indicates the Pacman movement steps.

For example, if move(3) returns 3, Pacman moved 3 steps.

If move(3) returns -1, that means Pacman died, eaten by ghost.

Now, the ghost movement was random, I have a different method handles this. So I my test case, I cannot control if the Pacman will die or not. So my test cases passes when ghost not eat Pacman. For instance, I use: assertEquals(2, move(2)); to test Pacman moves 2 steps.But how do I write test when -1 was returned?

UPDATE:

So here is what my move() method looks like, I have a ghost movement method randomGhostMovement() that gets called inside the move() method:

int move(int stpes){
    for(int i=0; i< steps; i++){
        randomGhostMovement();
        //rest of logic omitted.
    }
}

Upvotes: 0

Views: 135

Answers (2)

shingekinolinus
shingekinolinus

Reputation: 129

If you are using java.util.Random, you can provide a random seed.

A random seed can be any long value. Using the same random seed each time will guarantee the same random numbers are generated.

For example:

    long randomSeed = 1449443188342L;
    Random random = new Random(randomSeed);
    for (int i = 0; i < 5; i++) {
        System.out.println("random number: " + random.nextInt(10));
    }

No matter how many times I run this code, I still get the same output:

random number: 3
random number: 2
random number: 7
random number: 8
random number: 0

If the random numbers generated each time are exactly the same, then the ghosts movement becomes predictable. You can set up a new game using a certain random seed, record what actions will cause Pacman to die, then write a test case which uses the exact same seed.

Upvotes: 1

piotrek
piotrek

Reputation: 14520

you have a few different problems.

  1. you have a method/class that does many different things. move takes x and returns x or -1. that's somehow complex and useless. how about having a class GameState with method isPacmanDead. in general: separate your game into many tiny steps and use logic-less layer to simply call them in a loop.
  2. testing random numbers. refactor your code to be able to manually move ghosts and then create another logic-less layer that draws a random number and provide it to moveGhost method. then in your tests you can ignore the random layer and do fully deterministic tests. another useful technique is to use dependency injection to provide source-of-randomness and in tests mock it to it generates whatever values you wish

Upvotes: 1

Related Questions