Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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()
like image 220
Tom Avatar asked Mar 10 '11 14:03

Tom


1 Answers

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");
like image 157
Andy Thomas Avatar answered Sep 20 '22 09:09

Andy Thomas