Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 have

@Before public void setupMainProg() {      // Initialize m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc     ...     m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc); }   // setupMainProg  @Test public void testItAll() throws GeneralSecurityException, IOException {      m_prog.work();   } 

The method "work" calls a method of "m_orderSvc" (one of the arguments passed in to the object). "m_orderSvc," in turn contains a member field, "m_contractsDao". I want to verify that "m_contractsDao.save" got called exactly once and that the argument passed to it contains a certain value.

This may be a little confusing. Let me know how I can clarify my question and I'm happy to do so.

like image 938
Dave Avatar asked Aug 03 '12 20:08

Dave


People also ask

How do you verify a method called in Mockito?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.

How do you know if a method is mocked?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.


1 Answers

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

ContractsDao mock_contractsDao = mock(ContractsDao.class); when(mock_contractsDao.save(any(String.class))).thenReturn("Some result"); 

Then inject the mock into m_orderSvc and call your method.

m_orderSvc.m_contractsDao = mock_contractsDao; m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc); m_prog.work();  

Finally, verify that the mock was called properly:

verify(mock_contractsDao, times(1)).save("Parameter I'm expecting"); 
like image 123
mamboking Avatar answered Sep 23 '22 00:09

mamboking