模拟 - 测试是否在不指定参数的情况下调用方法

[英]Mock - testing if a method is called without specifying arguments


I'm mocking out Django's send_mail function using the Mock library:

我正在使用Mock库嘲笑Django的send_mail函数:

from django.core.mail import send_mail
send_mail = Mock()

My problem arises when I want to assert that send_mail was called. I can't use assert_called_with or related methods because they expect arguments, which I won't fully know/don't want to type out (it involves templates) in the testing environment. I just want to know the method has been called. Print statements clearly indicate that it is called, yet if I try this:

当我想断言send_mail被调用时,我的问题出现了。我不能使用assert_called_with或相关的方法,因为他们期望参数,我不会完全知道/不想在测试环境中输入(它涉及模板)。我只想知道已经调用的方法。打印语句清楚地表明它被调用,但如果我尝试这样做:

self.assertEqual(send_mail.called, True) 

I get an error, as the called attribute is still False. How can I test if a method has been called without having to specify attributes.

我收到一个错误,因为被调用的属性仍为False。如何在不必指定属性的情况下测试方法是否已被测试。

1 个解决方案

#1


6  

You haven't mocked the send_mail method correctly. You only rebound the name in your own module, not anywhere else.

您尚未正确模拟send_mail方法。您只能在自己的模块中反弹名称,而不是其他任何地方。

This would be a correct rebinding:

这将是一个正确的重新绑定:

from django.core import mail
mail.send_mail = Mock()

but it's easier to use the patch() context manager / decorator:

但是使用patch()上下文管理器/装饰器更容易:

with patch('django.core.mail.send_mail') as mocked_send_mail:
    # run your tests
    self.assertTrue(mocked_send_mail.called)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2014/01/21/ab052d3b011944321b8f7a11e0c2a60c.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号