Python Testing - Reset all mocks?

后端 未结 3 1275
情书的邮戳
情书的邮戳 2021-02-09 11:05

When doing unit-testing with Python / PyTest, if you do you not have patch decorators or with patch blocks throughout your code, is there a way to reset all mocks a

3条回答
  •  孤城傲影
    2021-02-09 11:31

    What I ended up doing was using the pytest-mock library. According to the Readme:

    This plugin installs a mocker fixture which is a thin-wrapper around the patching API provided by the excellent mock package, but with the benefit of not having to worry about undoing patches at the end of a test. (Emphasis added.)

    So now I can do: mocker.patch.object(module, 'method', return_value='hi'), and the patch will be removed at the end of the test. There is no need to use with any more so that this solution scales nicely if you have many mocks in one test or if you want to change mocks during the test.

提交回复
热议问题