Verify object attribute value with mockito

前端 未结 2 857
暖寄归人
暖寄归人 2020-12-22 14:54

I have a method call which I want to mock with mockito. To start with I have created and injected an instance of an object on which the method will be called. My aim is to v

相关标签:
2条回答
  • 2020-12-22 15:44

    New feature added to Mockito makes this even easier,

    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
    verify(mock).doSomething(argument.capture());
    assertEquals("John", argument.getValue().getName());
    

    Take a look at Mockito documentation


    In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

    verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
    assertEquals("John", argument.getValue().getName());
    
    0 讨论(0)
  • 2020-12-22 15:55

    I think the easiest way for verifying an argument object is to use the refEq method:

    Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));
    

    It can be used even if the object doesn't implement equals(), because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq.

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