How to match a possible null parameter in Mockito

久未见 提交于 2020-12-28 05:45:02

问题


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());

回答1:


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)



回答2:


I got this to work by switching to any(String.class)

I find this a bit misleading, because the API seems to suggest that anyString() is just an alias for any(String.class) at least up till the 2.0 update. To be fair, the documentation does specify that anyString() only matches non-null strings. It just seems counter-intuitive to me.




回答3:


How about:

verify(c, times(4)).foo(anyObject(), anyObject());

Does that work for you?

Matchers.anyObject() allows for nulls.

Reference in Mockito docs:



来源:https://stackoverflow.com/questions/40225011/how-to-match-a-possible-null-parameter-in-mockito

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!