问题描述
我想在单元测试中修补函数的返回值(原本评估起来很昂贵),但仍要测试其副作用(设置属性)。代码看起来像这样:
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 (将#修改为@)