gpt4 book ai didi

unit-testing - 如何模拟由另一个类方法调用的类方法?

转载 作者:行者123 更新时间:2023-12-04 13:46:40 26 4
gpt4 key购买 nike

我有两个类方法的类。方法 A 调用方法 B,处理他的响应并返回它。方法 A 被其他代码使用。我想模拟方法 B,这样方法 A 就会调用他的模拟版本,就像下面的例子一样:
模块1.py

class SomethingGetter:
# method B - I want to mock it
@classmethod
def get_something(cls):
return 'something'

# method A - it should use response of mocked version of method A
@classmethod
def get_formatted_something(cls):
return f'formatted {cls.get_something()}'
模块2.py
from module1 import SomethingGetter

# this function should use SomethingGetter with mocked class mehotd
def something_printer():
print(SomethingGetter.get_formatted_something())
模块3.py
from unittest import mock
from module1 import SomethingGetter
from module2 import something_printer

# I want to use this function in test insted of SomethingGetter.get_something
def get_something_else():
return SomethingGetter.get_something() + ' else'


if __name__ == '__main__':
with mock.patch('module2.SomethingGetter', autospec=True) as patched:
patched.get_something = get_something_else
something_printer()
# it prints <MagicMock name='SomethingGetter.get_formatted_something()' id='139753624280704'>;
# but I expected that it would print "formatted something else"
我做错了什么?

最佳答案

通过修补 module2.SomethingGetter ,你还造成了get_formatted_something()要修补。

相反,您应该只修补 get_something()方法,存储对原始文件的引用:

original = SomethingGetter.get_something
with mock.patch.object(SomethingGetter, 'get_something', lambda: original() + ' else'):
something_printer()

关于unit-testing - 如何模拟由另一个类方法调用的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45865190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com