Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JMockit Framework Overview


Published on

JMockit and mocking in Java tutorial - Expectations, Verifications APIs and mocking up

Published in: Technology
  • Very cool presentation of JMockIt, just something have been changed since the JMockIt upgrade. Now the JMockIt V1.0 has released, maybe it's time to update it?
    Are you sure you want to  Yes  No
    Your message goes here

JMockit Framework Overview

  1. 1. Mocking with JMockit Mario Peshev DevriX CTO, SCJP Consultant, Trainer
  2. 2. Contents <ul><li>What is Mocking </li></ul><ul><li>Where to use mocking </li></ul><ul><li>JMockit introduction </li></ul><ul><li>Expectations and Verifications </li></ul><ul><li>Annotations and Coverage </li></ul><ul><li>Comparison of mocking frameworks </li></ul>
  3. 3. What is Mocking <ul><li>Isolated class or method testing </li></ul><ul><li>Ignore dependencies of related classes when not necessary </li></ul><ul><li>Simplify testing environment by providing empty proxies instead of complex logical units </li></ul>
  4. 4. What is Mocking (2) <ul><li>A mock object represents a surreal interface or a class with modified output </li></ul><ul><li>Code behind is being skipped to reduce the effort of initialization before running a test case </li></ul>
  5. 5. Mocking Scheme DB Server Web Server Application with dependencies MOCKED
  6. 6. Why mock? <ul><li>Replace all collaborators with mocks </li></ul><ul><li>Avoid the use of Context with specific setup </li></ul><ul><li>Test only the core functionality of a class or a method </li></ul>
  7. 7. Mocking advantages <ul><li>Remove dependencies from external libraries and servers: </li></ul><ul><ul><li>Databases </li></ul></ul><ul><ul><li>Web servers </li></ul></ul><ul><ul><li>Sockets </li></ul></ul><ul><ul><li>Web services </li></ul></ul><ul><li>Less time for writing unit tests for legacy code </li></ul>
  8. 8. How does mocking work <ul><li>Two general types of mocking </li></ul><ul><li>Proxy based </li></ul><ul><ul><li>easymock, jmock </li></ul></ul><ul><li>Class loader remapping </li></ul><ul><ul><li>jmockit, powermock </li></ul></ul>
  9. 9. Proxy based <ul><li>Proxy based approach relies on reflection </li></ul><ul><li>Java Reflection API is a powerful toolset to inspect Java code at runtime </li></ul><ul><li>Different structures could be explored – classes, interfaces, fields, methods </li></ul><ul><ul><li>Even private methods could be called </li></ul></ul>
  10. 10. Proxy based (2) <ul><li>Reflection provides mechanism to create objects, invoke methods and access get/set field values and return types </li></ul><ul><li>Interfaces could be implemented dynamically via java.lang. reflect.Proxy </li></ul><ul><li>Proxy return values could be defined </li></ul>
  11. 11. Class loader mapping <ul><li>This method relies on the Instrumentation API </li></ul><ul><li>Instrumentation API is a set of features since Java 5 </li></ul><ul><li>It allows remapping of the classes to be called by the VM </li></ul>
  12. 12. Instrumentation API <ul><li>In package java.lang.instrument </li></ul><ul><li>Provides services that allow Java agents to instrument programs running on the JVM </li></ul><ul><li>Instrumentation does direct bytecode modification of methods and classes </li></ul><ul><ul><li>Uncatchable by debuggers </li></ul></ul>
  13. 13. Instrumentation API (2)
  14. 14. Remapping example <ul><li>We have a Book class to define Book model behavior to a model. </li></ul><ul><li>We need to separate DB logic dependences from the Book </li></ul><ul><li>So we define BookMock class and Instrumentation remaps VM links from Book to BookMock.class </li></ul>
  15. 15. JMockit
  16. 16. JMockit <ul><li>Open source mocking library </li></ul><ul><li>Under MIT license </li></ul><ul><li>Collection of tools to be used in testing environment together with JUnit or TestNG framework </li></ul><ul><li>Bytecode modifications done at runtime through internal ASM library </li></ul>
  17. 17. JMockit Components <ul><li>6 components in the toolkit: </li></ul><ul><ul><li>JMockit Core </li></ul></ul><ul><ul><li>JMockit Annotations </li></ul></ul><ul><ul><li>JMockit Expectations </li></ul></ul><ul><ul><li>JMockit Coverage </li></ul></ul><ul><ul><li>JMockit Hibernate Emulation </li></ul></ul><ul><ul><li>JMockit AOP </li></ul></ul>
  18. 18. JMockit vs. the World <ul><li>JMockit is far more complex, but more powerful than the other mocking frameworks </li></ul><ul><li>It allows mocking of static methods and final classes </li></ul><ul><li> </li></ul>
  19. 19. JMockit inside
  20. 20. Expectations API <ul><li>Provides a record-replay model </li></ul><ul><ul><li>Set one or more expectations </li></ul></ul><ul><ul><li>Define a real sample code using directly or not the mocked object </li></ul></ul><ul><li>Automatic verification of all expected invocations is transparent with JUnit/TestNG connection </li></ul>
  21. 21. Expectations API (2) <ul><li>Mock types could be defined as instance fields of the test class or of an Expectations anonymous subclass inside the recording phase </li></ul>new Expectations() { ClassToBeMocked mock; { … } }
  22. 22. Expectations API (3) <ul><li>Expectations could be specified of any kind of method invocation </li></ul><ul><ul><li>Interfaces, abstract classes, concrete final or non-final classes, static methods, constructors </li></ul></ul><ul><li>Private methods and constructors could have expectations too </li></ul>
  23. 23. Expectations API (4) <ul><li>By default, all expectations are strict </li></ul><ul><ul><li>For each expectation a matching invocation is expected and in the same order </li></ul></ul><ul><ul><li>If additional invocation to mocked type/instance is detected, assertion error will be thrown too </li></ul></ul><ul><li>Non-strict expectations could be defined – singular or in a specific block </li></ul>
  24. 24. Expectations API (5) <ul><li>A non-strict expectations could be invoked any number of times (0…N) and in arbitrary order </li></ul><ul><li>Unexpected invocations don’t cause errors to the test </li></ul><ul><li>Mocked objects could be passed as test method parameters (TestNG included) </li></ul>
  25. 25. Expectations Sample public class MockNoInterfaceClassTest { static class User { String name() { return &quot;joe&quot;; } } @Mocked User user; …
  26. 26. Expectations Sample (2) … @Test public void mockNoInterfaceFinalClass() { new Expectations() { {; returns(&quot;fred&quot;); }}; assertEquals(&quot;fred&quot;,; } }
  27. 27. Verifications API <ul><li>Additional phase for verify to the record-replay model </li></ul><ul><li>All other invocations in the test can be verified to have occurred (or not) after the replay phase </li></ul><ul><ul><li>It is possible to not have expectations but verifications only </li></ul></ul>
  28. 28. Verification API (2) <ul><li>Doesn’t make sense when we have 100% strict expectations </li></ul><ul><li>However, when we have mocked types with non-strict expectations, this is where we could make sure invocations are being called as required </li></ul>
  29. 29. Verification Demo static class UserService { void populateUser() { User user = new User(); user.setName(&quot;fred&quot;); user.setAge(31); } } @Mocked User user; …
  30. 30. Verification Demo (2) … @Test public void verifyInternalMethods() { new UserService().populateUser(); new FullVerificationsInOrder() { { User user = new User(); user.setName(&quot;fred&quot;); user.setAge(withAny(1)); } }; }
  31. 31. Verification Types <ul><li>InOrder </li></ul><ul><ul><li>The order of invocations in the Verification block has to match the original order </li></ul></ul><ul><li>Full </li></ul><ul><ul><li>Guarantees that _all_ invocations in the replay block must be verified in verification block </li></ul></ul><ul><li>Could define FullVerificationsInOrder too </li></ul>
  32. 32. JMockit test method template <ul><li>@Test </li></ul><ul><li>public void aTestMethod( <any number of mock parameters> ) { </li></ul><ul><ul><li>// Record phase : expectations on mocks are recorded; empty if there is nothing to record. </li></ul></ul><ul><ul><li>// Replay phase : invocations on mocks are &quot;replayed&quot;; here the code under test is exercised. </li></ul></ul><ul><ul><li>// Verify phase : expectations on mocks are verified; empty if there is nothing to verify. </li></ul></ul><ul><li>} </li></ul>
  33. 33. JMockit Mockups <ul><li>A different kind of API which adds functionality to mocking types </li></ul><ul><li>Mock classes are defined and applied for a method or a testing class </li></ul><ul><ul><li>Mock methods are @Mock annotated and behavior is defined that replaces the original method body </li></ul></ul><ul><ul><li>Number of invocations could be set too </li></ul></ul>
  34. 34. State-oriented mocking <ul><li>Useful for testing the argument values instead of checking invocations </li></ul><ul><ul><li>Allows complex data handling and verifications </li></ul></ul><ul><li>Achievable with mockit.Mockup<T> generic class for mockup creation </li></ul>
  35. 35. Annotations Demo @Test public void mockSystemNanoTime() { new MockUp<System>() { @Mock @SuppressWarnings(&quot;unused&quot;) long nanoTime() { return 0L; } }; assertSame(0L, System.nanoTime()); }
  36. 36. JMockit Coverage <ul><li>Code coverage API </li></ul><ul><li>Bytecode modification done only on runtime (constructions on demand) </li></ul><ul><li>1 .jar only – based on “ convention over configuration ” </li></ul><ul><li>Automatic analyze of all classes (specific set could be defined later) </li></ul>
  37. 37. JMockit Coverage (2) <ul><li>Output could be as XHTML report or any serialized file </li></ul><ul><li>Line-coverage and Path-coverage metrics </li></ul><ul><li>Incremental test runner </li></ul><ul><ul><li>Analyze only modified local files </li></ul></ul>
  38. 38. Coverage Report
  39. 39. Hibernate Emulation <ul><li>Designed for the speed of unit test and functionality of Hibernate-based integration tests </li></ul><ul><li>Fake Hibernate 3 Core API Implementation </li></ul><ul><li>O/R mapping data is ignored as well as real connections to database </li></ul>
  40. 40. JMockit installation <ul><li>Download jmockit from project homepage: </li></ul><ul><li>Copy jmockit.jar in your Eclipse project </li></ul><ul><li>Add the -Djavaagent=jmockit.jar (with relative or absolute path) to your JVM arguments when running Eclipse </li></ul><ul><li>Run with JDK and not JRE </li></ul>
  41. 41. JMockit with TestNG <ul><li>For TestNG support with JMockit, the Initializer listener needs to be added </li></ul><ul><ul><li>-listener mockit.integration.testng.Initializer as program argument </li></ul></ul><ul><ul><li>Or as a TestNG XML parameter in testng.xml: </li></ul></ul>
  42. 42. Running JMockit with TestNG Eclipse Demo
  43. 43. @Mocked and @Injectable <ul><li>@Mocked </li></ul><ul><ul><li>All instances of the given class (current and future) are mocked </li></ul></ul><ul><li>@Injectable </li></ul><ul><ul><li>Only the given instance of the class is mocked </li></ul></ul>
  44. 44. JMockit vs. PowerMock <ul><li>PowerMock is only extension to other mocking frameworks </li></ul><ul><li>JMockit provides a new Expectations API </li></ul><ul><li>PowerMock API is low level and requires specific API calls </li></ul><ul><li>Methods are mocked in a declarative way with specified partial mocking </li></ul>
  45. 45. JMockit vs. PowerMock (2) <ul><li>JMockit has support for mocking equals(), hashCode() and overriden methods </li></ul><ul><li>PowerMock uses custom class loaders which is heavy and could lead to conflicts </li></ul><ul><li>The –javaagent approach in JMockit is simpler and safer </li></ul>
  46. 46. JMockit vs. Mockito <ul><li>Every Mockito object invocation requires a call to its mocking API (between record and verify phases) </li></ul><ul><li>Mockito has inconsistences in the syntax used for invocation of mocked methods </li></ul><ul><li>Mockito has different syntax for calling methods returning values and void methods </li></ul>
  47. 47. JMockit vs. Mockito (2) <ul><li>In Mockito all invocations to mock objects during the test are allowed, never expected </li></ul><ul><ul><li>Verification is not automatic </li></ul></ul><ul><li>JMockit Expectations & Verifications gives plenty of options for best combination of strict (expected) and non-strict (allowed) mock invocations </li></ul>
  48. 48. JMockit vs. Mockito (3) <ul><li>Mockito needs additional object for in order and full verifications </li></ul><ul><li>JMockit gives a combination of VerificationsInOrder or FullVerifications (or FullVerificationsInOrder) </li></ul>
  49. 49. Questions?
  50. 50. DevriX Ltd <ul><li>Consulting services </li></ul><ul><li>Consulting in Java/PHP related technologies, database systems and platforms: </li></ul><ul><li>GWT </li></ul><ul><li>Swing </li></ul><ul><li>WordPress </li></ul><ul><li>CakePHP </li></ul><ul><li>Trainings </li></ul><ul><li>Core Java </li></ul><ul><li>Java and Database Management </li></ul><ul><li>Swing API </li></ul><ul><li>JEE </li></ul><ul><li>Tools and Automation Testing </li></ul><ul><li>Design Patterns </li></ul><ul><li>… </li></ul>