Mockito - how to mock/verify a method call which accepts a new object?

与世无争的帅哥 提交于 2019-12-02 09:03:29

You have a few options:

  1. Implement equals and hashCode on SampleObj. Because you didn't wrap fooList in a matcher, Mockito checks with List.equals, which checks equals for corresponding objects in each List. The default behavior of Object.equals is that a.equals(b) iff a == b--that is, objects are equal iff they refer to the same instance--but you're welcome to override that if every SampleObj("foobar") equals every other SampleObj("foobar").

  2. Use a Hamcrest Matcher you write.

    private static Matcher<List<SampleObj>> isAListWithObjs(String... strings) {
      return new AbstractMatcher<List<SampleObj>>() {
        @Override public boolean matches(Object object) {
          // return true if object is a list of SampleObj corresponding to strings
        }
      };
    }
    
    // in your test
    verify(mockedAnotherService).method2(argThat(isAnObjListWith("another param")));
    

    Note that you could also just make a Matcher of a single SampleObj, and then use a Hamcrest wrapper like hasItem. See more matchers here.

  3. Use a Captor to check equals your own way:

    public class YourTest {
      // Populated with MockitoAnnotations.initMocks(this).
      // You can also use ArgumentCaptor.forClass(...), but with generics trouble.
      @Captor ArgumentCaptor<List<SampleObj>> sampleObjListCaptor;
    
      @Test public void testMethod1() {
        // ...
        verify(mockedAnotherService).method2(sampleObjListCaptor.capture());
        List<SampleObj> sampleObjList = sampleObjListCaptor.getValue();
    
        assertEquals(1, sampleObjList.size());
        assertEquals("another param", sampleObjList.get(0).getTitle());
      }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!