【问题标题】:Do setUp and tearDown methods run for each method or at the beginning and at the end of TestCase是否为每个方法或在 TestCase 的开头和结尾运行 setUp 和 tearDown 方法
【发布时间】:2018-07-16 14:17:17
【问题描述】:

属于同一个TestCase成员的测试方法会相互影响吗?

在 python unittest 中,我试图理解,如果我在测试方法中更改变量,变量是否会在其他测试方法中更改。还是每个方法都运行 setUp 和 tearDown 方法,然后为每个方法重新设置变量?

我是说

AsdfTestCase(unittest.TestCase):
    def setUp(self):
        self.dict = {
                     'str': 'asdf',
                     'int': 10
                    }
    def tearDown(self):
        del self.dict

    def test_asdf_1(self):
        self.dict['str'] = 'test string'

    def test_asdf_2(self):
        print(self.dict)

所以我在问 test_asdf_2() 将打印哪个输出 'asdf''test_string'

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

    是的,setUp 和 tearDown 在测试用例类中的每个测试(即名称中以“test”开头的函数)之前运行。考虑这个例子:

    # in file testmodule
    import unittest
    
    class AsdfTestCase(unittest.TestCase):
        def setUp(self)      : print('setUp called')
        def tearDown(self)   : print('tearDown called')
        def test_asdf_1(self): print( 'test1 called' )
        def test_asdf_2(self): print( 'test2 called' )
    

    从命令行调用它:

     $ python3 -m unittest -v testmodule
    test_asdf_1 (testmodule.AsdfTestCase) ... setUp called
    test1 called
    tearDown called
    ok
    test_asdf_2 (testmodule.AsdfTestCase) ... setUp called
    test2 called
    tearDown called
    ok
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s
    
    OK
    

    (因此,是的,在您的示例中,由于 setUp 被重新执行,它会 pring 'asdf',覆盖测试 2 引起的更改)

    【讨论】:

    • 谢谢,在setUp 和tearDown 方法中使用print 是一种简单易懂的方法。应该想到
    【解决方案2】:

    每个测试用例都是孤立的。 setup 方法在每个 Test Case 之前运行,而 teardown 在每个 Test Case 之后运行。

    所以回答您的问题,如果您更改测试用例中的变量,它不会影响其他测试用例。

    通过编写测试代码,您走在了正确的道路上。当你自己做时,它总是一个更好的学习体验。不过,这就是你的答案。

    示例代码:

    import unittest
    
    class AsdfTest(unittest.TestCase):
      def setUp(self):
        print "Set Up"
        self.dict = {
          'str': 'asdf',
          'int': 10
        }
    
      def tearDown(self):
        print "Tear Down"
        self.dict = {}
    
      def test_asdf_1(self):
        print "Test 1"
        self.dict['str'] = 'test string'
        print self.dict
    
      def test_asdf_2(self):
        print "Test 2"
        print self.dict
    
    if __name__ == '__main__':
      unittest.main()
    

    输出:

    Set Up
    Test 1
    {'str': 'test string'}
    Tear Down
    .Set Up
    Test 2
    {}
    Tear Down
    .
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s
    
    OK
    

    您可以看到设置方法在每次测试之前运行。然后在每次测试后运行 tear down 方法。

    【讨论】:

    • 感谢您的回答,我编辑了我的问题以便更好地解释自己。如果你再看一遍我会很高兴
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2011-09-05
    • 2011-12-09
    • 1970-01-01
    相关资源
    最近更新 更多