Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to verify that the class I'm testing calls the correct dependency class's method. So I'm trying to match the method parameters, but I don't really care about the actual values in this test, because I don't want to make my test brittle.

However, I'm running into trouble setting it up because Mockito has decided that the behaviour I'm expecting is a bug: https://github.com/mockito/mockito/issues/134

So what't the correct way to define an ArgumentMatcher for a parameter that might be null?

With issue #134 "fixed", this code fails because the matchers only match in the first case. How can I define a matcher to work in all 4 cases?

MyClass c = mock(MyClass.class);

c.foo("hello", "world");
c.foo("hello", null);
c.foo(null, "world");
c.foo(null, null);

verify(c, times(4)).foo(anyString(), anyString());
question from:https://stackoverflow.com/questions/40225011/how-to-match-a-possible-null-parameter-in-mockito

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
239 views
Welcome To Ask or Share your Answers For Others

1 Answer

From the javadocs of any()

Since Mockito 2.1.0, only allow non-null String. As this is a nullable reference, the suggested API to match null wrapper would be isNull(). We felt this change would make tests harness much safer that it was with Mockito 1.x.

So, the way to match nullable string arguments is explicit declaration:

nullable(String.class)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...