如何重用使用unittest.testcase编写的测试

2024-03-18

我已经使用单元测试编写了一些测试,如下所示,我想在另一个我遇到困难并需要帮助的类中重用它们。 代码片段如下。

    MyTestClass.py
    Class MyTestClass(unittest.TestCase):   
        @classmethod
        def test_TC01_set(self):
            self.devAddr = "127.0.0.0"
            self.teststoSkip = 'TC02'

        def skip(type):
            if type in self.teststoSkip:
                self.skipTest('skipped!!') #unittest.Testcase method

        def test_TC02(self):
            self.skip('TC02')
            print 'test_TC02 will do other tasks'

        def test_TC03(self):
            self.skip('TC03')
            print 'test_TC03 will do other tasks'

这会工作得很好。现在我想在另一个类中重用相同的测试用例。说,

    RegressionMyTest.py
    from MyTestClass import MyTestClass
    Class RegressionMyTest(MyTestClass):
        @classmethod
        def setupmytest(self):
            self.test_TC01_set(self)#this will work fine since it is accessing classmethod
            self.tes_TC02(self)#cant access like this since it is not a class method
            self.tes_TC03(self)#cant access like this since it is not a class method

如何在 RegressionMyTest 中重用 MyTestClass 中的测试,以便 MyTestClass 和 RegressionMyTest 都应该在使用 nostests/unittest 单独运行时工作。


通常测试应该断言代码以某种方式运行,所以我不确定在测试套件之间实际共享测试是否有意义(我认为这不会非常明确)

Python 测试用例只是 Python 类,测试运行程序会自省以查找从以下位置开始的方法:test_。因此,您可以像使用普通类一样使用继承。

如果您需要共享功能,您可以创建一个具有共享初始化方法/辅助方法的基类。或者使用跨测试所需的实用函数创建测试混合。

    class BaseTestCase(unittest.TestCase):
      def setUp(self):
         # ran by all subclasses
    
      def helper(self):
        # help
    
    class TestCaseOne(BaseTestCase):
    
       def setUp(self):
          # additional setup
          super(TestCaseOne, self).setUp()

      def test_something(self):
          self.helper() # <- from base

也许您不想在基类上定义设置方法,而只想使用基类中定义的一些辅助方法在子类上定义?很多选择!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何重用使用unittest.testcase编写的测试 的相关文章

随机推荐