【问题标题】:Check the instance of a Mocked method called once检查调用一次的模拟方法的实例
【发布时间】:2020-04-01 17:05:05
【问题描述】:

我的函数在数据库中查找Actor 对象并使用传递的参数调用其do_something() 方法。

from my_app.models import Actor

def my_function(id, stuff):
    actor = Actor.objects.get(id=id)
    return actor.do_something(stuff)

我希望我的单元测试检查两件事:
1.my_function找到我想要的Actor
2、my_function按预期调用了actor的do_something方法。

from unittest import mock
from django.test import TestCase
from my_app.models import Actor
from my_app.views import my_function


class ViewsTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        self.actor = Actor.objects.create(id=42, name='John')

    def test_my_function(self):
        with mock.patch.object(Actor, 'do_something') as mock_do:
            my_function(id=42, stuff='a-short-string')
            mock_do.assert_called_once_with('a-short-string')

这可以确保 my_function 像我想要的那样调用 do_something,但我不知道如何确保它找到了我让他找到的 Actor。即使my_function 找到了错误的演员,这个测试也会通过。有什么办法可以检查吗?

【问题讨论】:

    标签: python django mocking python-unittest django-unittest


    【解决方案1】:

    首先,我不确定这是否是在模拟方法的self 参数上断言的最佳实践。

    通过将autospec=True 添加到您的模拟语句中,self 参数本身将可以在模拟对象call_args 中访问。为了更清楚,您的测试用例将是这样的:

    from unittest import mock
    from django.test import TestCase
    from my_app.models import Actor
    from my_app.views import my_function
    
    
    class ViewsTestCase(TestCase):
    
        @classmethod
        def setUpTestData(cls):
            self.actor = Actor.objects.create(id=42, name='John')
    
        def test_my_function(self):
            with mock.patch.object(Actor, 'do_something', autospec=True) as mock_do:
                                                          ^^^^^^^^^^^^^
                my_function(id=42, stuff='a-short-string')
                mock_do.assert_called_once_with(self.actor, 'a-short-string')
    

    【讨论】:

    • 这正是我所需要的,正如你所说,Autospeccing 使 self 参数在模拟方法中可用。谢谢你的帮助。我还发现有人问这个并得到了这个答案:stackoverflow.com/questions/20257252/…
    猜你喜欢
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多