Using Mockito, how do I verify a method was a called with a certain argument?

后端 未结 3 597
旧时难觅i
旧时难觅i 2020-12-08 09:23

I\'m using Mockito 1.9.0. How would i verify that a method got called exactly once, and that one of the fields passed to it contained a certain value? In my JUnit test, I

3条回答
  •  独厮守ぢ
    2020-12-08 10:20

    Building off of Mamboking's answer:

    ContractsDao mock_contractsDao = mock(ContractsDao.class);
    when(mock_contractsDao.save(anyString())).thenReturn("Some result");
    
    m_orderSvc.m_contractsDao = mock_contractsDao;
    m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
    m_prog.work(); 
    

    Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

    ArgumentCaptor savedCaptor = ArgumentCaptor.forClass(String.class);
    verify(mock_contractsDao).save(savedCaptor.capture());
    assertTrue(savedCaptor.getValue().contains("substring I want to find");
    

    If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

    ArgumentCaptor> savedCaptor = ArgumentCaptor.forClass(Collection.class);
    verify(mock_contractsDao).save(savedCaptor.capture());
    assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);
    

    You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

提交回复
热议问题