Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a method with random behaviour

Tags:

unit-testing

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:

  1. 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.
  2. 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?

like image 449
forceal Avatar asked Sep 28 '10 11:09

forceal


People also ask

Should unit tests use random values?

No. Random values in unit tests cause them to be not repeatable. As soon as one test will pass and another will fail without any change, people lose confidence in them, undermining their value. Printing a reproduction script is not enough.

Which method is used for unit testing?

Unit Testing Techniques:Black Box Testing - Using which the user interface, input and output are tested. White Box Testing - used to test each one of those functions behaviour is tested. Gray Box Testing - Used to execute tests, risks and assessment methods.

What are the two types of unit testing techniques?

There are 2 types of Unit Testing: Manual, and Automated.


1 Answers

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.

like image 105
Jon Skeet Avatar answered Sep 23 '22 09:09

Jon Skeet