【发布时间】:2020-02-07 04:00:40
【问题描述】:
我想通过模拟在单元测试中用新函数替换实例方法“set_email_id”。实例方法返回 email_id 字段,但我想要一个新函数来打印相同的字段。我不确定要使用哪个模拟功能。我阅读了有关 side_effect、mock.object 等的信息。我无法让它发挥作用。
脚本:
class Myclass(models.Model):
email_id = models.CharField(max_length=128, null=True, blank=True)
def return_email_id(self):
return self.email_id
def run():
my_class = Myclass()
my_class.email_id = 1
#want to moke this call
my_class.return_email_id()
单元测试:
@patch('models.Myclass.return_email_id')
def test(self, mock_email_id):
def new_method():
# this should replace the instance method
print(self.email_id)
# I know this wouldn't work. I just wanted to show it as an example
mock_email_id.side_effect = new_method()
【问题讨论】:
-
如果该实例仅用于测试,您可以使用任何可调用对象覆盖它:
instance.set_email_id = lambda self: …或您选择的 Mock。顺便说一句,如果您看到它的实际作用,该方法的名称会有些误导。 -
我更改了方法的名称。谢谢。你能详细说明覆盖实例吗?它不只是为了测试而存在。我基本上是在测试“run()”函数,我希望“my_class.return_email_id()”在实例中打印 email_id 字段。
标签: python unit-testing class mocking side-effects