更改使用补丁创建的模拟对象的方法的副作用 [英] changing the side effect of a mock object's method created with patch
问题描述
您好,我想测试Django的视图.在视图内部,我创建了两个对象,我想模拟它们的某些方法.测试看起来像这样
Hello I want to test a view of django. Inside of the view I create two objects which I want to mock some of their methods. The test looks like this
@mock.patch('payments_system.views.FirstObject')
@mock.patch('payments_system.helper_functions.SecondObject')
def test_make_payment_view_with_success(self, MockFirstObject, MockSecondObject):
MockFirstObject.get_value.side_effect = get_value_side_effect //this function is defined and implemented outside my testcase class
MockSecondObject.is_valid.return_value = True
factory = RequestFactory()
request = factory.post(reverse('cardinal-term_url'), data=dict(PaRes="test_parese", MD=None))
self._add_session_to_request(request)
session_data = dict(amount=1000, Centinel_PIType="VISA", Card_Number="40000000000000001", ExpMonth=06,
ExpYear=2016, Cvv2='123')
request = self._add_session_data_to_request(request, **session_data)
response = term_url(request)
self.assertRedirects(response, reverse('payments_system-success', kwargs={"token": "some_token"}))
当我调试测试用例并进入视图时,在视图内部创建的对象确实是Mocks类型的.但是get_value方法不使用side_effect函数,但也会返回MockingObject.如何在django视图中的模拟对象中传递更改?修补程序版本是否与以下版本相同?
When I debug my testcase and step in to my view, it is true that the objects created inside the view are of type of the Mocks. But the get_value method doesn't use the side_effect function but returns a MockingObject also. How can I pass the change in the mocking objects in the django view? Is the patch version the same as the following?
MockFirstObject = MagicMock(spec=payments_system.views.FirstObject)
MockSecondObject = MagicMock(spec=payments_system.helper_functions.SecondOjbect)
我需要做更多的事情吗?
Do I need to do something more?
推荐答案
我最终设法解决了我的问题.我所做的是以下事情:
I finnaly managed to solve my issue. What I did was the following:
在测试功能中
mock_object1_instance = MockFirstObject1.return_value
mock_object1_instance.get_value.side_effect = get_value_side_effect
与其他模拟对象相同.
the same I did for the other mock object.
这篇关于更改使用补丁创建的模拟对象的方法的副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!