涉及随机数的单元测试算法 [英] Unit testing algorithms that involve random numbers

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

问题描述

我正在写一些关于分形和随机地形生成的代码.具体来说,到目前为止,我正在使用Diamond-Square算法.对于那些不知道的人,它基本上会获得四个值的平均值,并在每个步骤中添加一个随机数.我将如何测试结果?我应该使用已知的种子并手动计算平均值加上随机值,还是什么?我应该使用随机数在代码中计算结果吗?还是有另一种方法?另外,对逆向过程的一些思考(也称为TDD,在代码之前编写测试)将是不胜感激的.

I'm writting some code about fractals and random terrain generation. Specifically, I'm using the Diamond-Square algorithm as of now. For those of you who don't know, it basically obtains the average of four values, and adds a random number, every step. How wouldI go about testing the result? Should I use a known seed and calculate by hand the average plus the random value, or what? Should I, instead, calculate the result in the code, using the random numbers? Or is there another way? Also, some thought on the reverse process (a.k.a. TDD, writting tests before code) would be much appreciated).

推荐答案

您可以使用模拟框架模拟随机数的生成.这样,您就可以消除结果的随机性,并能够使用一组静态的预定义测试用例来测试您的代码.

You can use a mocking framework to mock your random number generation. This way you remove the randomness from your result and will be able to test your code with a static set of pre defined test cases.

在所有情况下,您都不在测试随机数的生成,而是在进行计算.而且,如果您有故障,那么您确实需要知道用于重现故障的随机数.

In all cases you aren't testing the random number generation, but the calculations you are making. And if you whould have a fault you realy need to know the random numbers used to reproduce the fault.

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

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