Mockito for int primitive

后端 未结 2 1475
梦如初夏
梦如初夏 2021-02-06 23:18

If I am using a Wrapper class type variable as argument Mockito test case is getting pass but, how to write Mockito test case for int primitive type variable which is an argumen

相关标签:
2条回答
  • 2021-02-06 23:43

    I know that the question has been more than 4 years and 8 months old but for the sake of clear solution as of today, I am posting this

    In my case, the method signature to be tested is

    public SomeObject create(String code, int status)
    

    so the test code for verifying the argument values when the method was invoked would be following

    verify(this.service).create(
            argThat(code -> "dummy_code".equals(code)),
            intThat(status -> status == 105));
    

    If I go with the argThat even for int (or any primitive types) then mockito throws NPE

    Currently I am using org.mockito:mockito-core:jar:2.15.0 which must have been advanced considering the time when the question was asked! But thinking that this might be helpful to people... Thanks,

    0 讨论(0)
  • 2021-02-07 00:01

    You may have some trouble with any or argThat for primitive-type arguments to when and verify. Those Object-centric methods do their work with side-effects correctly, but they tend to return null for a dummy return value, which doesn't work for Java unwrapping primitives via auto-boxing.

    Luckily, the org.mockito.ArgumentMatchers class has a full complement of primitive-centric methods (of which I've listed the int methods here):

    static int anyInt()
    static int eq(int value)
    static int intThat(org.hamcrest.ArgumentMatcher<java.lang.Integer> matcher)
    

    See all of them at the documentation for the ArgumentMatchers class.

    0 讨论(0)
提交回复
热议问题