简体   繁体   中英

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

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"}))

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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