Home > other >  Cannot mock Enum values in JUnit 5
Cannot mock Enum values in JUnit 5

Time:02-03

I encounter "unnecessary stubbings" error due to the lines where I mock my variable with enum values:

when(productProjection.getType()).thenReturn(ProductType.USER_ADDED);

I did not mock ProductType, but even trying to mock as shown below, it does not make any sense:

@Mock
private ProductType productType;

So, how should I use enum in my unit test (I use JUnit5)? Or how to fix this problem?

CodePudding user response:

Sometimes, when you see an error like this running a set of tests, but not in the individual test, Mockito is reporting the error against the wrong test. This is because Mockito doesn't know that you didn't call the stubbed method, until the next test begins.

Imagine you've got tests like this.

Test 1:
    Stub method X
    Call method X

Test 2:
    Stub method X

Test 3:
    Stub method X
    Call method X

Then test 1 and test 2 will be fine, because you haven't done anything wrong. But if you're running all the tests in order, then when you start running test 3, Mockito detects that you stubbed a method and didn't call it, in test 2.

Of course, in this case, if you run test 3 by itself, there won't be any kind of warning from Mockito.

My advice would be to look at the test BEFORE the one that's giving you the warning. Your "unnecessary stubbing" is most likely to be in that one.

  •  Tags:  
  • Related