python unitest设置在不同上下文中的拆卸

2024-05-19 07:56:57 发布

您现在位置:Python中文网/ 问答频道 /正文

Deo python支持setUp()和tearDown()根据上下文的不同而不同?无论如何,我在问我是否可以做这样的事情:

setUp() {
    if(context1){
         do A;
    }
    else{
         do B;
    }
}


tearDown() {
    if(context1){
         do A;
    }
    else{
         do B;
    }
}

Tags: ifsetup事情doelseteardowndeocontext1
2条回答

您应该考虑为您需要的每个测试上下文执行两个不同的类(可能有一些共同的祖先),这样做会更容易。

类似的东西:

class BaseTest():
    def test_01a(self):
        pass

class Context1TestCase(BaseTest, unittest.TestCase):
    def setUp(self):
        # do what you need for context1

    def tearDown(self):
        # do what you need for context1

class Context2TestCase(BaseTest, unittest.TestCase):
    def setUp(self):
        # do what you need for context2

    def tearDown(self):
        # do what you need for context2

这样,^{cd1>}将在context1中执行一次,在context2中执行一次。

是的,就像你展示的那样:使用if块,并且只在条件为真时执行设置的特定部分。在

我想你得到的是对不同的测试使用不同的setUp和{}的不同版本。我建议你要么:

  • 使用正确的setUp/tearDown方法将测试拆分为不同的TestCase子类
  • 或者根本不要使用setUptearDown做这样的事情

    class MyTestCase:
        def _setup_for_foo_tests():
            # blah blah blah
        def _setup_for_bar_tests():
            # blah blah blah
        def test_foo_1():
            self._setup_for_foo_tests()
            # test code
        def test_foo_2():
            self._setup_for_foo_tests()
            # test code
        def test_bar_1():
            self._setup_for_bar_tests()
            # test code
        # etc etc etc
    

相关问题 更多 >

    热门问题