Your SlideShare is downloading. ×
Mockito with a hint of PowerMock
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Mockito with a hint of PowerMock


Published on

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

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

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1.   with a hint of PowerMock Ying Zhang - 6/17/2011
  • 2. A few terminologies
    • Test Doubles Terminology defined by Gerard Meszaros. 
    • See:
    • Test Stub 
    • Hand coded object used for testing. 
    • e.g. myObject.setProperty("testPropertyValue");
    • Mock object
    • Expectations configured before calling the method under test.
    • e.g. when(myObject.getProperty()).thenReturn("testPropertyValue");
    • Test Spy
    • Verification occurs after the method under test has been called.
    • e.g. @Spy private List<String> logs = new ArrayList<String>();
  • 3. State vs Interaction testing
    • 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.
  • 4. What's the big deal with JUnit 4?
    • It seems Eclipse v3.6 currently doesn't by default show the comment in the @Ignore annotation but other IDE's like Intellij does.
  • 5. Eclipse static import setting
    • Preferences -> Java -> Editor -> Content Assist -> Favorites
  • 6. Eclipse static import
  • 7. Eclipse auto organize imports
    • If you have Preferences -> Java -> Editor -> Save Actions -> Organize Imports turned on, you may want to update your settings on the static imports.
    • Change Preferences -> Java -> Code Style -> Organize Imports static imports setting to 1 instead of the default of 99
    • 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.
  • 8. Unit Testing Patterns
    • Given/When/Then or Arrange/Act/Assert - 3As rule
    • // arrange
    • Dog pomeranian = mock(Pomeranian.class);
    • when(pomeranian.getName()).thenReturn(&quot;Bubo&quot;);
    • when(myDao.findDogs()).thenReturn(Arrays.asList(pomeranian));
    • // act
    • boolean result = myService.isValidDog(&quot;Bubo&quot;);
    • // assert
    • verify(logger).info(&quot;Bubo is a valid dog.&quot;);
    • assertTrue(result);
    • // name your tests well, don't say &quot;test&quot;, say &quot;should&quot; (maybe impractical?)
    • public void buboShouldBeAValidDog() {
    • }
  • 9. My Pomeranian Bubo
  • 10. Why another mock framework?
    • Originally wrote on top of EasyMock's code but since been rewritten
      • Focused testing. Should let me focus test methods on specific behavior/interaction. Should minimize distractions like expecting/recording irrelevant interactions.
      • 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.
      • Explicit language. Verification and stubbing code should be easy to discern, should distinguish from ordinary method calls / from any supporting code / assertions.
      • 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.
      • No framework-supporting code. No record(), replay() methods, no alien control/context objects. These don’t bring any value to the game.
      • 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.
      • 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.
      • 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…
    • copied from
  • 11. Mockito Syntax
    • Everything you need to know is in their API
    • - great examples! Only 22 bullets up to v1.8.5
    • // simple mock
    • MyObject myObject = mock(MyObject.class);
    • when(myObject.getMethod1()).thenReturn(value);
    • when(myObject.getMethod2(anyInt(), eq(&quot;hi&quot;)).thenReturn(value);
    • when(myObject.getMethod3()).thenThrow(exception);
    • // for void methods, use &quot;do&quot; doThrow(new RuntimeException()).when(myObject).clear();
    • // annotations
    • @Mock MyObject myObject
  • 12. Mockito Defaults
    • If you mock an object, all of the methods on the mocked object return defaults.
    • Default answer of every Mockito mock.
      • Returns appropriate primitive for primitive-returning methods
      • Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 and Integer-returning method returns 0, too)
      • Returns empty collection for collection-returning methods (works for most commonly used collection types)
      • Returns description of mock for toString() method
      • Returns null for everything else
    • The default behavior can however be overridden.  For more info, read the bullet #14 in the API and the Mockito Answer enum doc .
  • 13. PowerMock
    • PowerMock is a framework that extends other mock libraries such as Mockito with more powerful capabilities
    • - mocking static methods and instantiations
    • 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.
  • 14. Mockito Autowiring
    • Say you have a controller with a few things autowired
    • You can use @Mock and @InjectMocks to easily inject them without any setters on the controller
  • 15. Mockito InjectMocks Bug
  • 16. Mockito InjectMocks Bug Cont.
    • 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.
  • 17. Mockito InjectMocks Bug Workaround
  • 18. Mockito Argument Captors
    • The controller...
  • 19. Mockito Argument Captors Cont.
    • You can also capture multiple arguments:
  • 20. Mockito Deep Stub & Chained Returns
    • Without deep stubs, you'd do
    • PostMethod postMethod = mock(PostMethod.class);
    • when(httpMethodHelper.createPostMethod(STATUS_URL)). thenReturn(postMethod) ;
    • when(postMethod.getResponseBodyAsString()). thenReturn(&quot;false&quot;) ;
  • 21. Mockito Deep Stub Generics Bug
    • For more info, visit Mockito bug report #251
  • 22. Mockito Matchers
    • When mocking, you don't have to specify an exact argument, you could specify argument matchers, e.g.
      • anyInt()
      • anyList()
      • anyLong()
      • anyMap() 
      • more on API
    • Warning on argument matchers: If you are using argument matchers, all arguments have to be provided by matchers .
    • e.g. 
    • when(myObj.getMethod(anyLong(), eq(&quot;hi&quot;) ).thenReturn(&quot;foo&quot;);
  • 23. Mockito Custom Matcher
  • 24. Mockito ThenAnswer
    • Not a big fan of the syntax. It doesn't seem very slim. But maybe it's a limitation of Java not Mockito.
  • 25. Mockito & Spring Hybrid
    • AOP example
  • 26. Mockito & Spring Hybrid Cont.
    • WebServiceCaller...
  • 27. Mockito & Spring Hybrid Cont.
  • 28. Mockito with Test Helper
  • 29. Mockito with Test Helper Cont.
  • 30. Mockito Limitation
    • Because you may not mock instantiations in Mockito, the following helper class is required in this particular implementation
    • Personally, I'd rather not having to create a class just so I can test my service more conveniently.
    • So I searched around for alternatives and found...
  • 31. PowerMock without Test Helper
  • 32. PowerMock without Test Helper Cont.
  • 33. MockitoExamples Project
    • git clone
    • It's a maven project. If you use Eclipse, you need to have the m2eclipse plugin installed.  
    • 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)
    • 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. 
    • I welcome forking.
  • 34. References
    • Test Doubles (Mocking Terminologies) 
    •   -
    • Mockito Blog Entry by Its Author
    •   -
    • Latest Mockito API
    •   -
    • More in Mockito Matchers
    •   -
    • Aspect Oriented Programming with Spring
    •   -
    • PowerMock API
    •   -
    • MockitoExamples Git Repository
    •   -