简体   繁体   English

更改使用补丁创建的模拟对象方法的副作用

[英]changing the side effect of a mock object's method created with patch

Hello I want to test a view of django. 您好,我想测试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"}))

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. 当我调试测试用例并进入视图时,在视图内部创建的对象确实是Mocks类型的。 But the get_value method doesn't use the side_effect function but returns a MockingObject also. 但是get_value方法不使用side_effect函数,但也会返回MockingObject。 How can I pass the change in the mocking objects in the django view? 如何在django视图中的模拟对象中传递更改? 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: 我所做的如下:

in the test function 在测试功能

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. 与我对其他模拟对象所做的一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM