python @patch自定义修补对象未更新

问题描述

我想用自己的模拟版本(func_to_be_mocked )修补返回类对象(ReturnValue)的函数ReturnValueMock)。我要测试的功能func_to_be_tested)正在对象上设置一些值。但是我的嘲笑对象没有更新并显示认值。 (即测试中的assert语句失败)。我想念什么?

to_test.py

class ReturnValue():
  def __init__(self):
    self.a = ""

class Totest():

  def func_to_be_mocked(self):
    return ReturnValue()

  def func_to_be_tested(self):
    ret_val = self.func_to_be_mocked()
    ret_val.a = "set"

test.py

from mock import patch
import unittest
from .to_test import ToTest

class ReturnValueMock():
  def __init__(self):
    self.a = ""


class Tests(unittest.TestCase):

  def setUp(self):
    self.ret_val = ReturnValueMock()

  @patch("to_test.ToTest.func_to_be_mocked")
  def test(self,mocked_func):
    mocked_func.return_val = self.ret_val
    Totest().func_to_be_tested()
    assert self.ret_val == "set"

到目前为止已经尝试过

  • 添加了打印语句,以验证被测函数中的对象与我作为模拟对象提供的对象相同(对象哈希码代码相同)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)