Unit testing algorithms that involve random numbers

試著忘記壹切 提交于 2019-12-22 08:41:35

问题


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).


回答1:


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.




回答2:


Just select a seed and a number for some iteration (aka how many times you call that PRNG before actually using the values from it), and use these same data (seed & iteration) in your main code and in the unit tests. These data could be in a config file that can be both accessed by the main code and the unit tests.



来源:https://stackoverflow.com/questions/12877260/unit-testing-algorithms-that-involve-random-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!