Matchers.any() for null value in Mockito

后端 未结 4 1996
夕颜
夕颜 2020-12-25 09:46

Suppose I am having this object objectDemo which calls to the method objectDemoMethod with 2 parameters String and null.

4条回答
  •  一向
    一向 (楼主)
    2020-12-25 10:20

    The error message you are getting is expected since you are using argument matcher for only one argument and not the other. From Matchers Javadoc:

    If you are using argument matchers, all arguments have to be provided by matchers.

    Therefore, the fix is to use a matcher for the second parameter of the method as well. In this case, it would be a matcher matching null. Depending on the version of Mockito and Java, you can have:

    • Starting with Mockito 2, you can use ArgumentMatchers.isNull(). This works with Java 8 and above:

      verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull());
      

      Note that if you're running with Java 7 or older, you'll need an explicit cast to make this work, because the type inference in those versions of Java does not take into account the types of the method called:

      verify(objectDemo, times(1)).objectDemoMethod(any(String.class), (String) isNull());
      
    • If you're using Mockito 1, you can use the Matchers.isNull(clazz) instead:

      verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull(String.class));
      

    For the Java ≤ 7 or Mockito 1 cases, the examples uses a case where the second parameter was of type String: it would need to be replaced with the actual type of the method parameter.

提交回复
热议问题