具有随机输出的测试功能 [英] Testing functions with random output

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

问题描述

  • 我正在研究一个测试项目,以测试神经网络库...
  • 问题在于该库有时使用随机数.
  • 我需要导出测试用例(输入,预期输出,实际输出)...

有人知道如何在进行操作和评估输出时将测试用例(输入,预期输出,实际输出)导出为使用随机数的函数吗?

Does anybody have an idea how to derive test cases (input,expected output,actual output) to a function that uses random numbers when taking actions and evaluating outputs??

推荐答案

是的,您必须运行足够多的案例以使随机性平均化,或者使随机源成为函数或方法的另一个输入因此您可以独立进行测试.

Yes, you either have to run a large enough number of cases so that the randomness averages out, or you make the random source another input to your function or method so you can test it independently.

第一种示例(这是Python,但是原理可以在任何语言中应用).

An example of the first kind (this is Python, but the principle can apply in any language).

def test_random_number():
    total = sum(random.uniform(0, 1) for _ in xrange(1000))
    assert 100 < total < 900

因此,如果不幸的话,此测试可能会失败,但是它仍然是一个合理的测试,因为它几乎始终都可以通过,并且进行这种测试非常简单.

So this test can fail if you're unlucky, but it's still a reasonable test since it'll pass nearly all the time, and it's pretty simple to make this kind of test.

要正确地"执行操作,您需要注入随机源.

To do things 'properly', you need to inject the random source.

class DefaultRandomBehavior(object):
    def pick_left_or_right(self):
        return random.choice(['left', 'right'])

class AardvarkModeller(object):
    def __init__(self, random_source=None):
        self.random_source = random_source or DefaultRandomBehavior()

    def aardvark_direction(self):
        r = self.random_source.pick_left_or_right()
        return 'The aardvark faces ' + r

现在,您可以通过模拟或伪造DefaultRandomBehavior类来对其进行单元测试,从而完全避开不确定性.

Now you can unit test this by either mocking out or faking the DefaultRandomBehavior class, thus completely side-stepping the non-determinism.

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

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