Mocks with Mockito API




      Camilo Lopes
   www.camilolopes.com
Agenda
•   About Mocks
•   Mocks API
•   Mockito API
•   Mocks with Mockito
•   Conclusion
What Mock is?
In one setence

“Mocks are object that simulates
 the behavior of real an object.”
Why Mocks?
•   Help design solution;
•   Avoid high coupling;
•   Promove high cohesion;
•   Easy to use;
•   Promove Agile development;
•   Improve performance in unit test;
Where can I use Mock?
•   DataBase;
•   WebServices;
•   NetWork
•   Classes;
How to use Mock?
Mocks API
What is the best?
In my opinion is...
Why?
Because...
Mockito API
•   Easy to use;
•   High learning Curve;
•   Excellent Documentation;
•   “stub-run-verify” concept;
•   Concept stub is separed of verification;
•   Clear code;
And the others?
•   Use “except-run-verify” concept; (it is not good)
•   Code is not as clear as Mockito;
•   Documentation is not as good as Mockito ‘s doc;
•   Verify and expect are bult-in in expect() method;
    (Mockito is separated. It is better)
Mockito Features
  Examples ahead
Exception
when(myobjectMock.buy(new BigDecimal("-5000.00"))).thenThrow(new
  Exception());
Matchers
when(myobjectMock.buy(any(BigDecimal.class)).thenReturn(true);


                     Note
Mockito offers some built-in such as: anyString,
 anyInt(), any(class). But we can create
 customized built-in. Our class must extends
 ArgumentMatcher.
void method
• doAnswer, doNothing, doThrow or doReturn

doThrow(new Exception()).when(mockObject).buy(new
  BigDecimal("-5000"))
Verify
  it possible check the number invocation of method
• atLeastOnce(), atLeast(int), atMost(int), never()

verify(mockobject,times(3)).buy(new BigDecimal("10000"))
More features
Check Mockito Documentation. There are many
  examples.

http://docs.mockito.googlecode.com/hg/org/mockito/
  Mockito.html
Conclusion
If you want to improve of quality in unit test use
   Mock.It will contribute to design, code,
   development etc.There are many APIs in
   market, but the most used are: EasyMock,
   Jmock and Mockito.
Thanks!!!!
References
http://code.google.com/p/mockito/
http://www.infoq.com/news/2008/06/mocks-q-of-when
http://www.easymock.org/
http://martinfowler.com/articles/mocksArentStubs.html

Mock with Mockito