• Save
Mockito with a hint of PowerMock
Upcoming SlideShare
Loading in...5
×
 

Mockito with a hint of PowerMock

on

  • 9,380 views

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 @
https://github.com/dodozhang21/MockitoExamples

Ying Zhang (Dodo) http://pure-essence.net

Statistics

Views

Total Views
9,380
Views on SlideShare
8,909
Embed Views
471

Actions

Likes
12
Downloads
0
Comments
0

2 Embeds 471

http://www.scoop.it 470
http://www.docseek.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Mockito with a hint of PowerMock Mockito with a hint of PowerMock Presentation Transcript

  •   with a hint of PowerMock Ying Zhang - 6/17/2011 http://pure-essence.net
  • A few terminologies
    • Test Doubles Terminology defined by Gerard Meszaros. 
    • See: http://tinyurl.com/testdoubles
    •  
    • 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>();
  • 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.
    View slide
  • 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.
    View slide
  • Eclipse static import setting
    • Preferences -> Java -> Editor -> Content Assist -> Favorites
  • Eclipse static import
    •  
  • 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.
  • 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() {
    • }
  • My Pomeranian Bubo
    •  
  • 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 http://monkeyisland.pl/2008/01/14/mockito
  • Mockito Syntax
    • Everything you need to know is in their API
    • http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Mockito.html - 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
  • 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 .
  • PowerMock
    • PowerMock is a framework that extends other mock libraries such as Mockito with more powerful capabilities
    •  
    • http://code.google.com/p/powermock/wiki/MockitoUsage13 - 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.
    •  
    •  
  • 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
  • Mockito InjectMocks Bug
    •  
  • Mockito InjectMocks Bug Cont.
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    • I submitted a bug report http://code.google.com/p/mockito/issues/detail?id=262 for v1.8.5 and it got fixed right a way. I assume it will be released in the next new version.
  • Mockito InjectMocks Bug Workaround
    •  
  • Mockito Argument Captors
    • The controller...
  • Mockito Argument Captors Cont.
    • You can also capture multiple arguments:
  • 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;) ;
  • Mockito Deep Stub Generics Bug
    • For more info, visit Mockito bug report #251
  • 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;);
  • Mockito Custom Matcher
    •  
  • 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.
  • Mockito & Spring Hybrid
    • AOP example
  • Mockito & Spring Hybrid Cont.
    • WebServiceCaller...
  • Mockito & Spring Hybrid Cont.
    •  
  • Mockito with Test Helper
    •  
  • Mockito with Test Helper Cont.
    •  
  • 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...
  • PowerMock without Test Helper
    •  
  • PowerMock without Test Helper Cont.
    •  
  • MockitoExamples Project
    • git clone git@github.com:dodozhang21/MockitoExamples.git
    •  
    • 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.
  • References
    • Test Doubles (Mocking Terminologies) 
    •   - http://tinyurl.com/testdoubles
    •  
    • Mockito Blog Entry by Its Author
    •   - http://monkeyisland.pl/2008/01/14/mockito/
    • Latest Mockito API
    •   - http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Mockito.html
    •  
    • More in Mockito Matchers
    •   - http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Matchers.html
    •  
    • Aspect Oriented Programming with Spring
    •   - http://static.springsource.org/spring/docs/3.0.x/reference/aop.html
    • PowerMock API
    •   - http://code.google.com/p/powermock/wiki/MockitoUsage13
    • MockitoExamples Git Repository
    •   - https://github.com/dodozhang21/MockitoExamples