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

mUserRepo.getUser(null);

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s