单元测试可以具有随机行为的方法 [英] Unit testing a method that can have random behaviour

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

问题描述

今天下午我遇到了这种情况,所以我想问问你们是做什么的.

I ran across this situation this afternoon, so I thought I'd ask what you guys do.

我们有一个用于用户密码重置的随机密码生成器,在解决问题的同时,我决定将例程移到我的(缓慢增长的)测试工具中.

We have a randomized password generator for user password resets and while fixing a problem with it, I decided to move the routine into my (slowly growing) test harness.

我想测试生成的密码是否符合我们制定的规则,但函数的结果当然会随机化(或者,伪随机化).

I want to test that passwords generated conform to the rules we've set out, but of course the results of the function will be randomized (or, well, pseudo-randomized).

你们会在单元测试中做什么?生成一堆密码,检查它们都通过并认为足够好了吗?

What would you guys do in the unit test? Generate a bunch of passwords, check they all pass and consider that good enough?

推荐答案

单元测试每次运行都应该做同样的事情,否则你可能会遇到单元测试只是偶尔失败的情况,这可能是调试起来真的很痛苦.

A unit test should do the same thing every time that it runs, otherwise you may run into a situation where the unit test only fails occasionally, and that could be a real pain to debug.

尝试每次都用相同的种子播种你的伪随机数(在测试中,这不是在生产代码中).这样你的测试每次都会生成相同的输入集.

Try seeding your pseudo-randomizer with the same seed every time (in the test, that is--not in production code). That way your test will generate the same set of inputs every time.

如果您无法控制种子并且无法防止您正在测试的函数被随机化,那么我猜您会陷入不可预测的单元测试中.:(

If you can't control the seed and there is no way to prevent the function you are testing from being randomized, then I guess you are stuck with an unpredictable unit test. :(

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

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