0

I want to know others ways to implement a test with multiple patch.mocks like this:

class TestFunction(TestCase):
    @mock.patch('path.to.value3', side_effect=value3) # Value3 -> Response object
    @mock.patch('path.to.value2', return_value='value2')
    @mock.patch('path.to.value1', return_value='value1')
    def test_function(self, value1, value2, value3):
        response = function_being_tested(payload)
        assert response.status_code == 200

I tried adding a fixture like this but couldnt make it work:

class TestUpdateProduct(TestCase):
    def test_function(self, mock_function):
        response = function_being_tested(payload)
        assert response.status_code == 200


@pytest.fixture()
def mock_function(monkeypatch):
    monkeypatch.setattr('path.to.value3', value3)
    monkeypatch.setattr('path.to.value2','value2')
    monkeypatch.setattr('path.to.value1','value1')
Risker
  • 358
  • 3
  • 15
  • You can create a decorator that mocks any number of tests… see this example: https://stackoverflow.com/a/52710018/3888719 – Michael Delgado Jun 14 '22 at 15:00
  • You can use `mocker` in your fixture instead of `monkeypatch` and do the mocking the same way as in the first example. If you don't have `pytest-mock` installed, you can directly use `mock.patch` either in the context manager variant (nested), or use [start/stop](https://docs.python.org/3/library/unittest.mock.html#patch-methods-start-and-stop) (before/after the yield). – MrBean Bremen Jun 15 '22 at 05:56

0 Answers0