请看下面的代码。我试图为我的项目实现一个测试套件。
import unittest
class TestClass1(unittest.TestCase):
def test_1_first(self):
print("First test case")
def test_2_second(self):
print("Second test case")
class TestClass2(unittest.TestCase):
def test_3_third(self):
print("Third test case")
def test_4_fourth(self):
print("Fourth test case")
if __name__ == "__main__":
# val = 1 <-- getting from user
# if val == 1:
# Execute test cases in TestClass2
# else
# Execute test cases in TestClass1\
unittest.main()
我将获得作为命令行参数的类名,并且需要根据参数运行每个测试类。这意味着我需要在运行时选择并运行一些测试用例类。那么,有谁能帮助我防止类在运行时中执行单元测试呢?问题是在执行时不允许像传递类名那样使用该方法
发布于 2018-07-17 00:47:02
这已经是内建了。您可以通过命令运行特定的类:
python -m unittest test_module.TestClass1
如果真的需要在scpript中这样做,可以将类传递给unittest.TestLoader().loadTestsFromName
,然后使用unittest.TextTestRunner().run(suite)
运行测试套件。看起来会是这样的:
test_suite = unittest.TestLoader().loadTestsFromName('__main__.TestClass1')
unittest.TextTestRunner().run(test_suite)
发布于 2018-07-17 00:45:59
unittest.main()
已经解析了sys.argv
以允许运行特定的类或单独的测试。
例如,如果您的脚本名为test.py
,则可以运行以下命令来只运行TestClass1
python test.py __main__.TestClass1
或运行以下命令只运行TestClass1.test_1_first
python test.py __main__.TestClass1.test_1_first
如果希望在脚本中执行此操作,可以将要运行的测试名称作为defaultTest
参数通过:
unittest.main(defaultTest='__main__.TestClass1')
https://stackoverflow.com/questions/51376509
复制相似问题