Python unittest的setUpClass不支持

2024-05-19 03:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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())

我的理解是,setUpClass()应该在TestFMP类实例化时执行一次,并提供对FMP\u对象和Locator\u对象的持续访问。但是,当我运行test\u方法时,出现以下错误:

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

当我尝试用self访问FMP\u object/Locator\u object时,得到了相同的结果。测试方法()中的前缀。你知道吗

你知道我做错了什么吗?你知道吗

我在python3.6上得到这个。你知道吗


Tags: pathtestselfobjectdefunittesttestcasemethod
1条回答
网友
1楼 · 发布于 2024-05-19 03:41:24

setupClass(cls)被调用,但您计算的结果不会被存储。您需要将结果赋给clsTestFMP类)上的一个属性,而不仅仅作为变量,然后您可以通过self检索这些结果,因为self可以访问cls属性(但不是相反)。你知道吗

像下面这样的事情可以实现你的目标:

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())

相关问题 更多 >

    热门问题