Mockito with a hint of PowerMock


Published on

Demonstrate some great aspects of Mockito. Made for Mockito v1.8.5.

All examples can be found @

Ying Zhang (Dodo)

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Mockito with a hint of PowerMock

  1. 1.   with a hint of PowerMock Ying Zhang - 6/17/2011
  2. 2. A few terminologies <ul><li>Test Doubles Terminology defined by Gerard Meszaros.  </li></ul><ul><li>See: </li></ul><ul><li>  </li></ul><ul><li>Test Stub  </li></ul><ul><li>Hand coded object used for testing.  </li></ul><ul><li>e.g. myObject.setProperty(&quot;testPropertyValue&quot;); </li></ul><ul><li>  </li></ul><ul><li>Mock object </li></ul><ul><li>Expectations configured before calling the method under test. </li></ul><ul><li>e.g. when(myObject.getProperty()).thenReturn(&quot;testPropertyValue&quot;); </li></ul><ul><li>  </li></ul><ul><li>Test Spy </li></ul><ul><li>Verification occurs after the method under test has been called. </li></ul><ul><li>e.g. @Spy private List<String> logs = new ArrayList<String>(); </li></ul>
  3. 3. State vs Interaction testing <ul><li>State testing asserts properties on an object. e.g. assertEquals(15, person.getAge()); Interaction testing verifies the interactions between objects. e.g. Did my service invoke this method on dao1 and have no interactions with dao2? Mockito provides a framework for interaction testing. </li></ul>
  4. 4. What's the big deal with JUnit 4? <ul><li>It seems Eclipse v3.6 currently doesn't by default show the comment in the @Ignore annotation but other IDE's like Intellij does. </li></ul>
  5. 5. Eclipse static import setting <ul><li>Preferences -> Java -> Editor -> Content Assist -> Favorites </li></ul>
  6. 6. Eclipse static import <ul><li>  </li></ul>
  7. 7. Eclipse auto organize imports <ul><li>If you have Preferences -> Java -> Editor -> Save Actions -> Organize Imports turned on, you may want to update your settings on the static imports. </li></ul><ul><li>Change Preferences -> Java -> Code Style -> Organize Imports static imports setting to 1 instead of the default of 99 </li></ul><ul><li>This way when you save your java files in Eclipse, it will not change your org.junit.Assert.* import to org.junit.Assert.assertTrue import. The latter will require you to import again if you wish to use another method like assertEquals. </li></ul>
  8. 8. Unit Testing Patterns <ul><li>Given/When/Then or Arrange/Act/Assert - 3As rule </li></ul><ul><li>// arrange </li></ul><ul><li>Dog pomeranian = mock(Pomeranian.class); </li></ul><ul><li>when(pomeranian.getName()).thenReturn(&quot;Bubo&quot;); </li></ul><ul><li>when(myDao.findDogs()).thenReturn(Arrays.asList(pomeranian)); </li></ul><ul><li>// act </li></ul><ul><li>boolean result = myService.isValidDog(&quot;Bubo&quot;); </li></ul><ul><li>// assert </li></ul><ul><li>verify(logger).info(&quot;Bubo is a valid dog.&quot;); </li></ul><ul><li>assertTrue(result); </li></ul><ul><li>// name your tests well, don't say &quot;test&quot;, say &quot;should&quot; (maybe impractical?) </li></ul><ul><li>public void buboShouldBeAValidDog() { </li></ul><ul><li>} </li></ul>
  9. 9. My Pomeranian Bubo <ul><li>  </li></ul>
  10. 10. Why another mock framework? <ul><li>Originally wrote on top of EasyMock's code but since been rewritten </li></ul><ul><ul><li>Focused testing. Should let me focus test methods on specific behavior/interaction. Should minimize distractions like expecting/recording irrelevant interactions. </li></ul></ul><ul><ul><li>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. </li></ul></ul><ul><ul><li>Explicit language. Verification and stubbing code should be easy to discern, should distinguish from ordinary method calls / from any supporting code / assertions. </li></ul></ul><ul><ul><li>Simple stubbing model. Should bring the simplicity of good old hand crafted stubs without the burden of actually implementing a class. Rather than verifying stubs I want to focus on testing if stubbed value is used correctly. Only one type of mock, one way of creating mocks. So that it’s easy to share setup. </li></ul></ul><ul><ul><li>No framework-supporting code. No record(), replay() methods, no alien control/context objects. These don’t bring any value to the game. </li></ul></ul><ul><ul><li>Slim API. So that anyone can use it efficiently and produce clean code. API should push back if someone is trying to do something too smart: if the class is difficult to test – refactor the class. </li></ul></ul><ul><ul><li>Explicit errors. Verification errors should always point stack trace to failed interaction. I want to click on first stack element and navigate to failed interaction. </li></ul></ul><ul><ul><li>Clean stack trace. Part of TDDing is reading stack traces. It’s Red-Green-Refactor after all – I’ve got stack trace when it’s red. Stack trace should always be clean and hide irrelevant internals of a library. Although modern IDE can help here, I’d rather not depend on IDE neither on competence in using IDE… </li></ul></ul><ul><li>  </li></ul><ul><li>copied from </li></ul>
  11. 11. Mockito Syntax <ul><li>Everything you need to know is in their API </li></ul><ul><li> - great examples! Only 22 bullets up to v1.8.5 </li></ul><ul><li>  </li></ul><ul><li>// simple mock </li></ul><ul><li>MyObject myObject = mock(MyObject.class); </li></ul><ul><li>when(myObject.getMethod1()).thenReturn(value); </li></ul><ul><li>when(myObject.getMethod2(anyInt(), eq(&quot;hi&quot;)).thenReturn(value); </li></ul><ul><li>when(myObject.getMethod3()).thenThrow(exception); </li></ul><ul><li>  </li></ul><ul><li>// for void methods, use &quot;do&quot; doThrow(new RuntimeException()).when(myObject).clear(); </li></ul><ul><li>  </li></ul><ul><li>// annotations </li></ul><ul><li>@Mock MyObject myObject </li></ul>
  12. 12. Mockito Defaults <ul><li>If you mock an object, all of the methods on the mocked object return defaults. </li></ul><ul><li>  </li></ul><ul><li>Default answer of every Mockito mock. </li></ul><ul><ul><li>Returns appropriate primitive for primitive-returning methods </li></ul></ul><ul><ul><li>Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 and Integer-returning method returns 0, too) </li></ul></ul><ul><ul><li>Returns empty collection for collection-returning methods (works for most commonly used collection types) </li></ul></ul><ul><ul><li>Returns description of mock for toString() method </li></ul></ul><ul><ul><li>Returns null for everything else </li></ul></ul><ul><li>  </li></ul><ul><li>The default behavior can however be overridden.  For more info, read the bullet #14 in the API and the Mockito Answer enum doc . </li></ul>
  13. 13. PowerMock <ul><li>PowerMock is a framework that extends other mock libraries such as Mockito with more powerful capabilities </li></ul><ul><li>  </li></ul><ul><li> - mocking static methods and instantiations </li></ul><ul><li>Mocking on steroids - some argue you should not have to mock on that level. I do have an example later to show, in my opinion, a valid use of it. </li></ul><ul><li>  </li></ul><ul><li>  </li></ul>
  14. 14. Mockito Autowiring <ul><li>Say you have a controller with a few things autowired </li></ul><ul><li>You can use @Mock and @InjectMocks to easily inject them without any setters on the controller </li></ul>
  15. 15. Mockito InjectMocks Bug <ul><li>  </li></ul>
  16. 16. Mockito InjectMocks Bug Cont. <ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>  </li></ul><ul><li>I submitted a bug report for v1.8.5 and it got fixed right a way. I assume it will be released in the next new version. </li></ul>
  17. 17. Mockito InjectMocks Bug Workaround <ul><li>  </li></ul>
  18. 18. Mockito Argument Captors <ul><li>The controller... </li></ul>
  19. 19. Mockito Argument Captors Cont. <ul><li>You can also capture multiple arguments: </li></ul>
  20. 20. Mockito Deep Stub & Chained Returns <ul><li>  </li></ul><ul><li>Without deep stubs, you'd do </li></ul><ul><li>PostMethod postMethod = mock(PostMethod.class); </li></ul><ul><li>when(httpMethodHelper.createPostMethod(STATUS_URL)). thenReturn(postMethod) ; </li></ul><ul><li>when(postMethod.getResponseBodyAsString()). thenReturn(&quot;false&quot;) ; </li></ul>
  21. 21. Mockito Deep Stub Generics Bug <ul><li>For more info, visit Mockito bug report #251 </li></ul>
  22. 22. Mockito Matchers <ul><li>When mocking, you don't have to specify an exact argument, you could specify argument matchers, e.g. </li></ul><ul><ul><li>anyInt() </li></ul></ul><ul><ul><li>anyList() </li></ul></ul><ul><ul><li>anyLong() </li></ul></ul><ul><ul><li>anyMap()  </li></ul></ul><ul><ul><li>more on API </li></ul></ul><ul><li>  </li></ul><ul><li>Warning on argument matchers: If you are using argument matchers, all arguments have to be provided by matchers . </li></ul><ul><li>  </li></ul><ul><li>e.g.  </li></ul><ul><li>when(myObj.getMethod(anyLong(), eq(&quot;hi&quot;) ).thenReturn(&quot;foo&quot;); </li></ul>
  23. 23. Mockito Custom Matcher <ul><li>  </li></ul>
  24. 24. Mockito ThenAnswer <ul><li>Not a big fan of the syntax. It doesn't seem very slim. But maybe it's a limitation of Java not Mockito. </li></ul>
  25. 25. Mockito & Spring Hybrid <ul><li>AOP example </li></ul>
  26. 26. Mockito & Spring Hybrid Cont. <ul><li>WebServiceCaller... </li></ul>
  27. 27. Mockito & Spring Hybrid Cont. <ul><li>  </li></ul>
  28. 28. Mockito with Test Helper <ul><li>  </li></ul>
  29. 29. Mockito with Test Helper Cont. <ul><li>  </li></ul>
  30. 30. Mockito Limitation <ul><li>Because you may not mock instantiations in Mockito, the following helper class is required in this particular implementation </li></ul><ul><li>  </li></ul><ul><li>Personally, I'd rather not having to create a class just so I can test my service more conveniently. </li></ul><ul><li>So I searched around for alternatives and found... </li></ul>
  31. 31. PowerMock without Test Helper <ul><li>  </li></ul>
  32. 32. PowerMock without Test Helper Cont. <ul><li>  </li></ul>
  33. 33. MockitoExamples Project <ul><li>git clone </li></ul><ul><li>  </li></ul><ul><li>It's a maven project. If you use Eclipse, you need to have the m2eclipse plugin installed.   </li></ul><ul><li>Import -> Maven -> Existing Maven Projects -> Select MockitoExamples folder Add the following folders as source folders main test main/properties main/resources (Optional: change the JRE lib to whatever you wish to use) </li></ul><ul><li>When you run the entire test source folder as JUnit, the only test should fail is ExampleServiceTest.testDoSomething() due to the bug mentioned on a previous slide for version 1.8.5.  I hope to see it pass once a new version of Mockito is released.  </li></ul><ul><li>  </li></ul><ul><li>I welcome forking. </li></ul>
  34. 34. References <ul><li>Test Doubles (Mocking Terminologies)  </li></ul><ul><li>  - </li></ul><ul><li>  </li></ul><ul><li>Mockito Blog Entry by Its Author </li></ul><ul><li>  - </li></ul><ul><li>Latest Mockito API </li></ul><ul><li>  - </li></ul><ul><li>  </li></ul><ul><li>More in Mockito Matchers </li></ul><ul><li>  - </li></ul><ul><li>  </li></ul><ul><li>Aspect Oriented Programming with Spring </li></ul><ul><li>  - </li></ul><ul><li>PowerMock API </li></ul><ul><li>  - </li></ul><ul><li>MockitoExamples Git Repository </li></ul><ul><li>  - </li></ul>