我写了两个类: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
再一次,但是如何强制在测试期间持续模拟这些类?
最佳答案
成功模拟的关键是记住您需要替换模块中实际使用对象的地方,而不是定义测试的地方。因此,在您的情况下,您想要导入 View 模块并替换那里的类:
from core.whatever import views
views.System = my_mock_system
views.Order = my_mock_order
关于django - 在 Django 的测试中连接模拟和客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8128272/