如何解决如何修补函数的返回值,但仍在python unittest中获得副作用
我想在单元测试中修补函数的返回值(原本评估起来很昂贵),但仍要测试其副作用(设置属性)。代码看起来像这样:
class MyClass:
def __init__():
self.my_attribute = None
# this function returns some string but also sets the value of self.my_attribute
def my_function():
self.my_attribute = 'sth'
return 'sth_else'
class MyTestCase(unittest.TestCase):
@mock.patch(MyClass.my_function,return_value='test_value')
def test_my_function(self,mock_function):
#when
my_instance = MyClass()
my_return = my_instance.my_function()
#then
self.assertEqual(my_instance.my_attribute,'sth')
但是,由于对该函数进行了修补,它无法运行(对吗?),因此也没有副作用。有办法强迫副作用出现吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。