我正在使用 Python
unittest
库测试一个模块。我想使用不同的参数调用 unt 测试方法,但希望每个调用都是一个单独的测试用例:
import unittest
class TestStringMethods(unittest.TestCase):
def test_all(self):
for x in range(10):
self.do_test_one(x)
def do_test_one(self,x):
print( "Testing " + str(x) )
self.assertTrue( x != 5 )
if __name__ == '__main__':
unittest.main()
此报道:
Testing 0
Testing 1
Testing 2
Testing 3
Testing 4
Testing 5
F
======================================================================
FAIL: test_all (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "so.py", line 8, in test_all
self.do_test_one(x)
File "so.py", line 12, in do_test_one
self.assertTrue( x != 5 )
AssertionError: False is not true
----------------------------------------------------------------------
Ran 1 test in 0.014s
FAILED (failures=1)
我希望每个功能都是一个单独的测试:
Testing 0
Testing 1
Testing 2
Testing 3
Testing 4
Testing 5
F
======================================================================
FAIL: test_all (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "so.py", line 8, in test_all
self.do_test_one(x)
File "so.py", line 12, in do_test_one
self.assertTrue( x != 5 )
AssertionError: False is not true
----------------------------------------------------------------------
Testing 6
Testing 7
Testing 8
Testing 9
Ran 10 test in 0.014s
FAILED (passed=9, failures=1)
有可能实现吗?
test_all()
函数将在第一次失败时中止。为了做你想做的事,你需要参数化测试。不幸的是 unittest
不支持这一点。我建议您查看pytest
。它允许你做类似的事情。您可以创建一个采用参数的测试,而不是使用显式循环来运行测试。然后定义要用于该参数的所有值组合的列表。这允许跑步者对每个值运行独立测试。
这段代码可以帮助您。参数化装饰器将设置 test_one 函数中的每个值,然后将测试每个值。
import pytest
values = [y for y in range(10)]
@pytest.mark.parametrize("x", values)
def test_one(x):
print("Testing " + str(x))
assert x != 5