Mockito anyString() vs any() – null handling

Sometimes, when I mock a method in Mockito, I used anyString instead of any and I get into a mess and my test fails. Why?

given(mUserRepo.getUser(anyString(). any())).willReturn(new User());

And what will happen if


UserRepo is called with null? Well, the matcher doesn’t work and the test fails. anyString() does not work with null values. If you pass null to a mocked service then use any() as a matcher.

You may also like...