0

I'm trying to use mockito to mock a method that returns a different value based on the parameters passed to it, using differing values "aaa" and "bbb"

when(myServiceMock.mymethod("aaa", myEnum.ONE)).thenReturn(true);
when(myServiceMock.mymethod("bbb", myEnum.ONE)).thenReturn(false);

Why won't it let me do this? I'm getting an "UnnecessaryStubbingException" even though the first parameter of the stubbed method is different

dataman
  • 123
  • 9
  • This means that a call to `mymethod` with parameters `bbb` and `myEnum.ONE` does not actually happen. Either your code is breaking before the line where this call is made or the string is not getting passed as `bbb` – subasri_ Apr 07 '23 at 02:41

1 Answers1

0

The UnnecessaryStubbingException occurs when you try to stub a method but it's not actually used in the code being tested. This usually happens when there are multiple stubs for the same method, and Mockito detects that some of them are unnecessary.

In your case, the exception might be caused by the fact that you have not used the mocked method in your test code, so Mockito detects it and throws the exception.

To avoid this, you need to make sure that the method you are mocking is actually used in your test code.

For example the next code will work without any problems:

    @Test
    public void unnecessaryStubbings() {
        final MyService myServiceMock = Mockito.mock(MyService.class);
        when(myServiceMock.mymethod("aaa", myEnum.ONE)).thenReturn(true);
        when(myServiceMock.mymethod("bbb", myEnum.ONE)).thenReturn(false);
        Assertions.assertTrue(myServiceMock.mymethod("aaa", myEnum.ONE));
        Assertions.assertFalse(myServiceMock.mymethod("bbb", myEnum.ONE));
    }

where in the next case the UnnecessaryStubbingException will be thrown:

    @Test
    public void unnecessaryStubbings() {
        final MyService myServiceMock = Mockito.mock(MyService.class);
        when(myServiceMock.mymethod("aaa", myEnum.ONE)).thenReturn(true);
        when(myServiceMock.mymethod("bbb", myEnum.ONE)).thenReturn(false); // Unnecessary Stabbing
        Assertions.assertTrue(myServiceMock.mymethod("aaa", myEnum.ONE));
        // Assertions.assertFalse(myServiceMock.mymethod("bbb", myEnum.ONE));
    }

You can also read more about that exception and how to handle it in that thread.

Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34
  • In your first example, it's just asserting the value that you told the stub to return. I don't see the value in that. In my class, I'm building a list of values where false was returned, and I need to be able to verify that only the false ones are contained and no true ones, but I don't see how to do that – dataman Apr 06 '23 at 19:42