简体   繁体   中英

Python unittest's setUpClass does not work

I have the following code:

import unittest

class TestFMP(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        FMP_object = MyClass1(path, {})
        Locator_object = MyClass2(path)

    @classmethod
    def tearDownClass(cls):
        print('YYY')

    def test_method(self):

        self.assertEqual(FMP_object.method1(), Locator_object.method2())

My understanding is, that the setUpClass() should be executed once on instantiation of the TestFMP class, and provide constant access to FMP_object and Locator_object. However, when I run the test_method, I get the following error:

testcase = TestFMP()
testcase.test_method()

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-277-b11e25b4803c> in <module>
      1 testcase = TestFMP()
----> 2 testcase.test_method()

<ipython-input-276-dba1c1e55b1a> in test_method(self)
     12     def test_method(self):
     13 
---> 14         self.assertEqual(FMP_object.method1(), Locator_object.method2())

NameError: name 'FMP_object' is not defined

I get the same result when I attempt to access FMP_object/Locator_object with self. prefix in the test_method().

Any ideas on what I am doing wrong?

I am getting this on Python 3.6.

setupClass(cls) is called, but the results you computed aren't stored. You need to assign the results to an attribute on the cls ( TestFMP class), and not just as variables, then you can retrieve these results through the self as self can access cls attributes (but not the inverse).

Something like the following will achieve what you're after:

import unittest

class TestFMP(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # set `fmp` and `locator` onto the class through `cls` 
        cls.fmp = MyClass1(path, {})
        cls.locator = MyClass2(path)

    @classmethod
    def tearDownClass(cls):
        # Dispose of those resources through `cls.fmp` and `cls.locator`
        print('YYY')

    def test_method(self):
        # access through self: 
        self.assertEqual(self.fmp.method1(), self.locator.method2())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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