单元测试具有随机行为的方法 [英] Unit testing a method with random behaviour

查看:22
本文介绍了单元测试具有随机行为的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我正在开发的游戏编写单元测试用例.游戏开始时,玩家的位置是随机的,我有两个问题:

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. 由于播放器的位置是随机的,我无法确定一次通过的测试用例会再次通过.例如,它可以在大部分时间通过,但如果玩家碰巧位于障碍物前面则失败.
  2. 我必须在一个测试用例中测试所有情况.例如,在测试玩家是否正确移动时,我必须检查是否存在障碍物以及算法是否考虑了该障碍物.

我对此并不满意,但我看不到出路.测试具有部分随机行为的方法是否可以接受?

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?

推荐答案

我建议你将你的随机源(随机数生成器或其他)视为依赖.然后,您可以通过提供假 RNG 或具有已知种子的已知输入来测试它.这消除了测试中的随机性,同时将其保留在真实代码中.

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.

如果你伪造 RNG,你可以测试如果它自然地将玩家定位在障碍物上会发生什么 - 它如何将玩家移开,等等.当然,这取决于了解类如何使用 RNG,但就我个人而言,我对单元测试作为具有一些内部知识的白盒测试"感到满意.

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.

这篇关于单元测试具有随机行为的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆