mockito-python icon indicating copy to clipboard operation
mockito-python copied to clipboard

Add support for lenient stubbed invocations

Open Oracking opened this issue 11 months ago • 6 comments

Current behaviour: When we call verifyStubbedInvocationsAreUsed it checks that all stubbed invocations are called at least once, ensuring we don't have unnecessary stubbing. This is often useful to have in afterEach hook. However, there are cases where we want some specific mocks to be skipped by this check. Java mockito has lenient which allows a stubbed invocation to be set up without being called. This is useful in a case where we want to always mock some call in the beforeEach regardless of whether it is called in the test body (see example below). Currently, there isn't support for this.

class TestCase:
    def setUp(self):
        mockito.when("external_module").real_call_that_should_always_be_stubbed(...).thenReturn("Some response")

    def tearDown(self):
        mockito.verifyStubbedInvocationsAreUsed()

    def test_some_behaviour(self):
        # Do some stuff that don't call the stub

    def test_some_other_behaviour(self):
        # Do some stuff that call the stub

Proposed Behaviour: Thinking this can be solved in one of two ways:

  1. Have an optional lenient argument added to when, when2, expect, patch. The actual name of the argument can be something other than lenient as we currently have strict and this can be confusing. Also Java Mockito's lenient argument seems to skip argument mismatch check so having the same name (but modified behaviour) could be misleading.
  2. Relax the validity check on the atleast argument in expect so zero can be passed as a valid argument. Hence in beforeEach, user can specify mockito.expect("external_module", atleast=0).real_call_that_should_always_be_stubbed(...).thenReturn("Some response"). And this will still pass verifyStubbedInvocationsAreUsed in afterEach hook even if no calls are made to stubbed invocation in the test body.

I think Option 2 will be the least invasive but I'm keen to hear others thoughts.

I will also be happy to raise a PR with the changes required

Oracking avatar Mar 01 '24 23:03 Oracking