Tom
Tom

Reputation: 2444

What is the difference between mock() and stub() when using Mockito?

They both seem to do the same thing - why would you use one in preference to the other?

org.mockito.Mockito.stub()
org.mockito.Mockito.mock()

Upvotes: 22

Views: 17333

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86459

You can use a mock object to verify that you have called it in the way expected. In Mockito, mocked objects are automatically stubs, and verification occurs explicitly.

From Mockito's "Why do we need another mocking framework?":

 Separation of stubbing and verification. Should let me code in line with intuition: 
 stub before execution, selectively verify interactions afterwards. I don’t 
 want any verification-related code before execution.

You can stub the behavior of calls before they're called. For example (from the Mockito home page):

 when( mockedList.get(0)).thenReturn( "first" );

You can verify interactions with mocked objects after they're called. For example:

 verify( mockedList ).add("one");

Upvotes: 16

Related Questions