Unit testing a method with random behaviour

前端 未结 6 377
梦如初夏
梦如初夏 2020-12-17 08:44

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
6条回答
  •  -上瘾入骨i
    2020-12-17 09:18

    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.

提交回复
热议问题