Home > Net >  When should I use argument matcher or passing argument directly when mockito unit test
When should I use argument matcher or passing argument directly when mockito unit test

Time:07-26

I know the mechanism of the argument matchers. I'm confused when should I use different argument matchers or passing the argument directly. For example,

Mockito.when(function(arg1, arg2)).thenReturn(result)
Mockito.when(function(arg1, arg2)).thenThrow(exception)
Mockito.when(function(eq(arg1), eq(arg2))).thenReturn(result)
Mockito.when(function(eq(arg1), eq(arg2))).thenThrow(exception)
Mockito.when(function(anyString(), anyString())).thenReturn(result)
Mockito.when(function(anyString(), anyString())).thenThrow(exception)

What should I use in what situation?

CodePudding user response:

eq is the default "matcher" if you don't specify any matchers. You may find that you only need to use eq if you want to be extra-explicit or if you need to mix eq-style matching with other matchers like any: If you use at least one matcher in a call, all of the parameters need to use matchers.

// These two behave the same:
Mockito.when(function(   arg1 ,    arg2 )).thenReturn(result);
Mockito.when(function(eq(arg1), eq(arg2))).thenReturn(result);

// These two behave the same:
Mockito.when(function(   arg1 ,    arg2 )).thenThrow(exception);
Mockito.when(function(eq(arg1), eq(arg2))).thenThrow(exception);

// The first call mixes matchers and raw values, which isn't allowed.
Mockito.when(function(   arg1 , gt(0))).thenThrow(exception);  // BAD
Mockito.when(function(eq(arg1), gt(0))).thenThrow(exception);  // OK

With Matchers, you can choose your specificity: For one call eq(4) may be the most specific, gt(0) is somewhat general, and anyInt() is extremely general. Your flexibility here should be defined by your spec: For testTwoPlusTwo you probably want to validate that your value eq(4), but for other tests you might not care about the integer (anyInt()) and only test that the method call happens or that the other parameters are correct. Your engineering judgment will guide you here: If you are too flexible your test might not protect your code, but if you are too specific your test might be "brittle"—failing at random times or requiring maintenance as the code changes even when changed behavior is still within spec.

  • Related