【问题标题】:Mock the method of a Python class and return a dynamic value模拟 Python 类的方法并返回动态值
【发布时间】:2019-06-07 03:20:18
【问题描述】:

如何使用 Python 的 unittest.mock 模块来模拟使用同一类成员的方法?

class NameHelper(object):
    def __init__(self):
        self.local_id = 0

    def next_id(self):
        self.local_id += 1
        return str(self.local_id)

注意,我是 patch.start and patch.stop,在 setUp 方法中进行修补:

class TestSomeClient(unittest.TestCase):

    def setUp(self):
        patcher = patch('helpers.name_helper.NameHelper')
        self.addCleanup(patcher.stop)
        self.mock_name_helper = patcher.start()

        # The actual mocked values
        self.mock_name_helper.return_value.local_id = 0
        self.mock_name_helper.return_value.next_id.return_value = 'mock-name'

显然,mock-name 不是一个明智的模拟返回值。返回值应使用NameHelperlocal_id 成员。

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

    我不确定为什么这个问题在没有 cmets 的情况下被否决。答案是,IMO,不清楚。

    patch.start and patch.stop 的 Python 文档提供了以下在 setUp 中修补的示例:

    class MyTest(TestCase):
         def setUp(self):
             self.patcher1 = patch('package.module.Class1')
             self.MockClass1 = self.patcher1.start()
    
         def tearDown(self):
             self.patcher1.stop()
    
    MyTest('test_something').run()
    

    但是,在修补整个班级时,这是一种误导。以下内容更有帮助:

    class MockClass1():
        pass
    
    class MyTest(TestCase):
        def setUp(self):
            self.patcher1 = patch('package.module.Class1')
            self.MockClass1 = self.patcher1.start()
            self.MockClass1.return_value = MockClass1()
    
        def tearDown(self):
            self.patcher1.stop()
    

    注意,附加行:

    self.MockClass1.return_value = MockClass1()
    

    return_value 应该是类 MockClass1 的新实例。应用于我的示例:

    class MockNameHelper(object):
        def __init__(self):
            self.local_id = 0
    
        def next_id(self):
            self.local_id += 1
            return str(self.local_id)
    
    class TestSomeClient(unittest.TestCase):
    
        def setUp(self):
            patcher = patch('helpers.name_helper.NameHelper')
            self.addCleanup(patcher.stop)
            self.MockNameHelper = patcher.start()
            self.MockNameHelper.return_value = MockNameHelper()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 2021-12-31
      • 2019-03-12
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多