我在为一些django视图设置模拟时遇到问题。
backend.py
class Connector(object):
def get_this():
...
def get_that():
...
view_a.py
from backend import Connector
class AView(View):
def get_context_data(self, **kwargs):
connector = Connector()
things = connector.get_this(...)
view_b.py
class BView(View):
def get_context_data(self, **kwargs):
connector = Connector()
things = connector.get_that(...)
text_view_a.py
class ATest(TestCase):
@mock.patch('backend.Connector')
def test_simple(self, connector_mock):
mi = mock.return_value # The constructor
mi.get_this.return_value = ...
mi.get_that.return_value = ...
response = self.client.get(
reverse('...view_a'),
)
self.assertTrue(mi.get_this.called)
text_view_b.py
class BTest(TestCase):
@mock.patch('backend.Connector')
def test_simple(self, connector_mock):
mi = mock.return_value # The constructor
mi.get_this.return_value = ...
mi.get_that.return_value = ...
response = self.client.get(
reverse('...view_b'),
)
self.assertTrue(mi.get_that.called)
我所看到的行为是,它们都可以单独运行,但是当运行时只有第一个成功而其余部分失败。基本上它看起来只有第一个模拟设置/使用。我想这与使用自己的导入类副本的视图有关吗?
模拟此类后端类的最佳做法是什么时候?
保
答案 0 :(得分:2)
我自己修好了;我不得不嘲笑使用它的类而不是来自它的地方......
class BTest(TestCase):
@mock.patch('view_a.Connector')
def test_simple(self, connector_mock):
mi = mock.return_value # The constructor
mi.get_this.return_value = ...
mi.get_that.return_value = ...
response = self.client.get(
reverse('...view_b'),
)
self.assertTrue(mi.get_that.called)