【问题标题】:Connecting mock and client in django's tests在 django 的测试中连接模拟和客户端
【发布时间】:2011-11-14 21:21:13
【问题描述】:

我编写了两个类:System 和 Order,它们代表类似于“在线票务分发商店”的东西。

下单很容易:

order = Order('title', set(['1', '2', '5']))
System.fill(order)

但我想测试我的 views.fill_order 函数,并检查它是否正确地从 POST 参数中填写订单。为此,我可以像这样使用模拟和客户端:

from core.order import Order
from core.system import System
from django.test.client import Client
from mock import Mock, sentinel

self.logged_client = Client()
# skipping logging process

Order = Mock(sentinel.return_value)
System = Mock()
System.fill = Mock()

# sending hypotetic POST
self.logged_client.post('/my_view_url/', {'title': self.PHANTOM, 'seat_numbers': '1I', 'seat_numbers': '3IV'})

System.fill.assert_called_with(Order.return_value)
Order.assert_called_with(self.PHANTOM, set(['1I', '2II', '3IV']))

但是......它不起作用(断言失败)。如何解决?

我知道这是因为在我的 views.fill_order 函数中我这样做了:

from core.system import System
from core.order import Order

再一次,但是如何强制在测试期间持续模拟这些类?

【问题讨论】:

    标签: django testing mocking


    【解决方案1】:

    成功模拟的关键是记住,您需要替换模块中实际使用它们的对象,而不是定义测试的地方。所以,在你的情况下,你想导入视图模块并替换那里的类:

    from core.whatever import views
    views.System = my_mock_system
    views.Order = my_mock_order
    

    【讨论】:

      【解决方案2】:

      在模拟和使用客户端时它不起作用,因为它似乎正在启动一个不同的项目实例,没有模拟类。 我没有成功,唯一的方法似乎是实例化类本身......

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 2021-09-30
        • 1970-01-01
        相关资源
        最近更新 更多