如何在 python unittest 中指定特定于测试的设置和拆卸

how to specify test specific setup and teardown in python unittest

我想用两个不同的设置创建 unittest 测试,并在同一个 class 中用两个不同的测试创建 tearDown methon。

每个测试都将在 python 单元测试框架中使用其特定的 setUp 和 tearDown 方法。

谁能帮帮我。

    class processtestCase(unittest.TestCase):

         print "start the process test cases " 

        def setUp1(self): 
             unittest.TestCase.setUp(self)

        def test_test1(self): 
              "test Functinality" 

        def tearDown1(self): 
             unittest.TestCase.tearDown(self) 

        def setUp2(self): 
            unittest.TestCase.setUp2(self) 

        def test_test2(self): 
            "test Functinality" 

        def tearDown2(self): 
            unittest.TestCase.tearDown2(self) '

if __name__ == '__main__':
        unittest.main()

在问题中,您提到您有两个测试,每个测试都有自己的设置和拆卸。至少有两条路可以走:

您可以将 setUptearDown 代码嵌入到每个测试中:

class FooTest(unittest.TestCase):
    def test_0(self):
        ... # 1st setUp() code
        try:
            ... # 1st test code
        except:
            ... # 1st tearDown() code
            raise

    def test_1(self):
        ... # 2nd setUp() code
        try:
            ... # 2nd test code
        except:
            ... # 2nd tearDown() code
            raise

或者,您可以将 class 拆分为两个 class:

class FooTest0(unittest.TestCase):
    @classmethod
    def setUp(cls):
        ...

    @classmethod
    def tearDown(cls):
        ...

    def test(self):
       ...

第一个选项 class 更少,更短,更直接。第二个选项更干净地分离了设置夹具和清理它,然后是测试代码本身。它还可以在未来证明添加更多测试。

您应该根据您的具体情况和您的个人喜好来判断权衡。