繁体   English   中英

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

[英]Does setUp method from unittest.TestCase know the current test case?

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 ,而希望将需要不同设置的测试拆分为单独的测试类。

class Tests(unittest.TestCase):
    def setUp(self):
        print "The next test will be: " + self.id()

    def test_01(self):
        pass

    def test_02(self):
        pass

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

会产生:

The next test will be: __main__.Tests.test_01
The next test will be: __main__.Tests.test_02

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM