I am writing unit test cases for a game I am working on. When the game starts, the player is positioned randomly, and I have two problems with that:
- Since the player is positioned randomly, I cannot be sure that a test case that passes once will pass again. For example, it could pass most of the time, but fail if the player happens to be positioned in front of an obstacle.
- I have to test all situations in one test case. For example, when testing whether the player moves correctly, I have to check whether there was an obstacle and if it was considered by the algorithm.
I’m not really happy with that, but I don’t see a way out. Is it acceptable to test methods with partially random behaviour?
I suggest you treat your source of randomness (a random number generator or whatever) as a dependency. Then you can test it with known inputs by providing either a fake RNG or one with a known seed. That removes the randomness from the test, while keeping it in the real code.
If you fake the RNG, you can test what happens if it would naturally position the player on an obstacle – how it moves the player out of the way, etc. Of course that relies on knowing how the class uses the RNG, but personally I’m happy enough with unit tests acting as “white box tests” with some internal knowledge.