Skip to main content
 首页 » 编程设计

python之unittest.TestCase 中的 setUp 方法是否知道当前的测试用例

2025年05月04日14EasonJim

unittest.TestCase 中的 setUp 方法是否知道下一个将要执行的测试用例是什么?例如:

import unittest 
 
class Tests(unittest.TestCase): 
    def setUp(self): 
        print "The next test will be: " + self.next_test_name() 
 
    def test_01(self): 
        pass 
 
    def test_02(self): 
        pass 
 
if __name__ == '__main__': 
    unittest.main() 

这样的代码应该在执行时产生:

The next test will be: test_01 
The next test will be: test_02 

请您参考如下方法:

不,unittest 不保证测试执行的顺序。

此外,您应该构建不依赖于任何特定顺序的单元测试。如果他们需要来自另一种测试方法的一些状态设置,那么根据定义,您不再拥有单元测试。

将要执行的当前测试方法名称位于self._testMethodName中,但使用它需要您自担风险(访问_private属性如有破损,恕不另行通知)。不要使用它来根据特定的测试方法自定义 setUp,更喜欢将需要不同设置的测试拆分到单独的测试类中。