编写可重用(参数化)的 unittest.TestCase 方法 [英] Writing a re-usable (parametrized) unittest.TestCase method

查看:52
本文介绍了编写可重用(参数化)的 unittest.TestCase 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何在 python 中生成动态(参数化)单元测试?

我正在使用 unittest 包编写测试,我想避免重复代码.我将进行许多测试,这些测试都需要非常相似的方法,但每次只有一个值不同.一个简单而无用的例子是:

I'm writing tests using the unittest package, and I want to avoid repeated code. I am going to carry out a number of tests which all require a very similar method, but with only one value different each time. A simplistic and useless example would be:

class ExampleTestCase(unittest.TestCase):

    def test_1(self):
        self.assertEqual(self.somevalue, 1)

    def test_2(self):
        self.assertEqual(self.somevalue, 2)

    def test_3(self):
        self.assertEqual(self.somevalue, 3)

    def test_4(self):
        self.assertEqual(self.somevalue, 4)

有没有办法编写上面的例子,而不是每次都重复所有的代码,而是编写一个通用的方法,例如

Is there a way to write the above example without repeating all the code each time, but instead writing a generic method, e.g.

    def test_n(self, n):
        self.assertEqual(self.somevalue, n)

并告诉 unittest 用不同的输入来尝试这个测试?

and telling unittest to try this test with different inputs?

推荐答案

一些可用于在 Python 中进行参数化测试的工具有:

Some of the tools available for doing parametrized tests in Python are:

  • Nose test generators (only for function tests, not TestCase classes)
  • nose-parametrized by by David Wolever (also for TestCase classes)
  • Unittest template by Boris Feld
  • Parametrized tests in py.test
  • parametrized-testcase by Austin Bingham
  • DDT (Data Driven Tests) by Carles Barrobés, for UnitTests

这篇关于编写可重用(参数化)的 unittest.TestCase 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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