是否有任何方法可以为每个python子测验运行设置和拆除?

发布于 2025-01-25 11:08:43 字数 871 浏览 3 评论 0 原文

我的代码:

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次。但是,实际上它们仅调用一次(您可以从上面的测试输出中验证)。有什么方法可以实现它吗?

My code:

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()

Run the test test_something in it, and we get the result:

test_something (tests.ui.test_example.MyTestCase) ... setUp
tearDown
ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

You can see I use self.subTest() to parameterize my test, which is convenient. The problem is, I want python unittest to call setUp and tearDown for each subTest, i.e. they should be called 4 times each. However, they are actually only called once each (You can verify that from the test output above). Is there any way to achieve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残疾 2025-02-01 11:08:43

这不是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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文