如何编写单元测试,其中每个测试用例都有不同的输入但输入相同? [英] How to write a unit-test where each test case has different input but does the same?

查看:40
本文介绍了如何编写单元测试,其中每个测试用例都有不同的输入但输入相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为某个 python 类创建一个单元测试.我有一个输入数据库和预期结果,UUT 应该为这些输入生成这些数据库.

I need to create a unit-test for some python class. I have a database of inputs and expected results which should be generated by the UUT for those inputs.

这是我想要做的伪代码:

Here is the pseudo-code of what I want to do:

for i=1 to NUM_TEST_CASES:
    Load input for test case i
    execute UUT on the input and save output of run
    Load expected result for test case i
    Compare output of run with the expected result

我可以使用 unittest 包来实现这一点,还是有一些更好的测试包可以用于此目的?

Can I achieve this using the unittest package or is there some better testing package for this purpose?

推荐答案

您描述测试的方式与一般的单元测试很奇怪.单元测试通常不会从外部文件加载测试数据或剩余结果.通常,它只是在单元测试中硬编码.

The way you describe testing is an odd match for Unit Testing in general. Unit testing does not -- typically -- load test data or rest results from external files. Generally, it's simply hard-coded in the unit test.

这并不是说您的计划行不通.只能说不典型.

That's not to say that your plan won't work. It's just to say that it's atypical.

你有两个选择.

  1. (我们做什么).编写一个小脚本来执行加载测试用例 i 的输入"和加载测试用例 i 的预期结果".使用它来生成所需的单元测试代码.(我们使用 Jinja2 模板从源文件编写 Python 代码.)

  1. (What we do). Write a little script that does the "Load input for test case i", and "Load expected result for test case i". Use this to generate the required unittest code. (We use Jinja2 templates to write Python code from source files.)

然后删除源文件.是的,删除它们.他们只会让你感到困惑.

Then delete the source files. Yes, delete them. They'll only confuse you.

剩下的是典型"形式的正确 Unittest 文件,其中包含测试用例的静态数据和预期结果.

What you have left is proper Unittest files in the "typical" form with static data for the test case and expected results.

编写您的 setUp 方法来执行加载测试用例 i 的输入"和加载测试用例 i 的预期结果".编写您的 test 方法来练习 UUT.

Write your setUp method to do the "Load input for test case i", and "Load expected result for test case i". Write your test method to exercise the UUT.

它可能看起来像这样.

class OurTest( unittest.TestCase ):
    def setUp( self ):
        self.load_data()
        self.load_results()
        self.uut = ... UUT ...
    def runTest( self ):
        ... exercise UUT with source data ...
        ... check results, using self.assertXXX methods ...

想要多次运行?一种方法来做这样的事情.

Want to run this many times? One way it to do something like this.

class Test1( OurTest ):
    source_file = 'this'
    result_file = 'that'

class Test2( OutTest ):
    source_file= 'foo'
    result_file= 'bar'

这将允许 unittest 主程序找到并运行您的测试.

This will allow the unittest main program to find and run your tests.

这篇关于如何编写单元测试,其中每个测试用例都有不同的输入但输入相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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