编写可重用(参数化)的 unittest.TestCase 方法 [英] Writing a re-usable (parametrized) unittest.TestCase method
问题描述
可能的重复:
如何在 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 测试生成器(仅用于功能测试,不是 TestCase 类)
- 鼻子参数化 作者:David Wolever(也用于测试用例类)
- Unittest 模板 by Boris Feld
- py.test 中的参数化测试
- parametrized-testcase 作者:Austin Bingham
- DDT(数据驱动测试) by Carles Barrobés,用于UnitTests
- 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屋!