单元测试函数返回随机结果 [英] Unit Testing with functions that return random results

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

问题描述

我不认为这是特定于语言或框架,但我使用xUnit.net和C#。

I don't think that this is specific to a language or framework, but I am using xUnit.net and C#.

我有一个函数返回一个随机的日期在一定范围内。我通过在一个日期,并返回日期始终为1至40年的范围给定的日期之前

I have a function that returns a random date in a certain range. I pass in a date, and the returning date is always in range of 1 to 40 years before the given date.

现在我只是不知道是否有一个很好的方式进行单元测试这一点。最好的办法似乎是即创建一个循环,让功能运行100次,并断言,每一个这些100的结果是在所需范围内,这是我目前的做法。

Now I just wonder if there is a good way to unit test this. The best approach seems to be to create a loop and let the function run i.e. 100 times and assert that every of these 100 results are in the desired range, which is my current approach.

我也意识到,除非我能够控制我的随机生成器,不会有一个完美的解决方案(毕竟,结果是随机的),但我不知道什么样的方法时,你必须测试功能,返回你拿随机结果在一定的范围内?

I also realize that unless I am able to control my Random generator, there will not be a perfect solution (after all, the result IS random), but I wonder what approaches you take when you have to test functionality that returns a random result in a certain range?

推荐答案

在除了测试该函数返回的日期在所需范围内,要确保结果是均匀分布。您所描述的测试将传递一个简单的返回你发送的日期功能!

In addition to testing that the function returns a date in the desired range, you want to ensure that the result is well-distributed. The test you describe would pass a function that simply returned the date you sent in!

因此​​,除了调用该函数多次和测试结果保持在所需范围内,我也试图评估的分布,也许是通过将结果在水桶和检查的水桶有结果的人数大致持平在完成后。您可能需要超过100个电话来获得稳定的结果,但这并不听起来像一个昂贵的(运行时明智的)功能,让您可以轻松地运行了几K的迭代。

So in addition to calling the function multiple times and testing that the result stays in the desired range, I would also try to assess the distribution, perhaps by putting the results in buckets and checking that the buckets have roughly equal numbers of results after you are done. You may need more than 100 calls to get stable results, but this doesn't sound like an expensive (run-time wise) function, so you can easily run it for a few K iterations.

我以前有一个问题,非均匀随机功能..他们可以是一个真正的痛苦,这是值得的测试早期。

I've had a problem before with non-uniform "random" functions.. they can be a real pain, it's worth testing for early.

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

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