是否有任何方法可以为每个python子测验运行设置和拆除?
我的代码:
import unittest
class MyTestCase(unittest.TestCase):
def setUp(self):
print("setUp")
def tearDown(self):
print("tearDown")
def test_something(self):
for i in range(4):
with self.subTest():
self.assertEqual(True, True) # add assertion here
if __name__ == '__main__':
unittest.main()
在其中运行test test_something
,我们得到结果:
test_something (tests.ui.test_example.MyTestCase) ... setUp
tearDown
ok
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
您可以看到我使用 self.subtest()
来参数化我的测试,这很方便。问题是,我希望python Unitest呼叫设置
和拆卸
为每个 subtest
,即应将它们调用4次。但是,实际上它们仅调用一次(您可以从上面的测试输出中验证)。有什么方法可以实现它吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是subtest()方法的用途酶。在每个测试案例之前执行设置()和拆卸方法,因为您只有一个测试用例,因此两种方法只会调用一次。
请参阅:
如果您的子测试需要设置,则意味着有测试用例。
如果您不想有很多测试用例,请尝试在循环内手动调用设置()方法。
This is not the usecase of subTest() method. The Setup() and TearDown() methods are executed before each test case, since you only have one test case, theses two methods will only be called once.
See : https://docs.python.org/3/library/unittest.html#test-cases
If your subTests need a set-up that means there are test cases.
If you don't want to have many test cases, try to call the SetUp() methods manually inside your loop.