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

More Related Content

What's hot (20)

PPS
JUnit Presentation
priya_trivedi
 
PDF
Waits in Selenium | Selenium Wait Commands | Edureka
Edureka!
 
PPTX
Mockito
sudha rajamanickam
 
PPTX
JUnit- A Unit Testing Framework
Onkar Deshpande
 
PPTX
Exceptional Handling in Java
QaziUmarF786
 
PPTX
JUNit Presentation
Animesh Kumar
 
PPTX
Java Unit Testing
Nayanda Haberty
 
PPTX
Understanding Unit Testing
ikhwanhayat
 
PDF
Unit Testing with Jest
Maayan Glikser
 
PDF
Smoke Testing
Kanoah
 
PPTX
An Introduction to Unit Testing
Joe Tremblay
 
PPSX
Test Complete
RomSoft SRL
 
PPTX
Introduction to JUnit
Devvrat Shukla
 
PPTX
Java Logging
Zeeshan Bilal
 
PDF
Introduction to jest
pksjce
 
PDF
Manual software-testing-interview-questions-with-answers
Sachin Gupta
 
PDF
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 
PDF
Spring Meetup Paris - Back to the basics of Spring (Boot)
Eric SIBER
 
DOCX
Selenium interview-questions-freshers
Naga Mani
 
PPTX
Exception handling in java
pooja kumari
 
JUnit Presentation
priya_trivedi
 
Waits in Selenium | Selenium Wait Commands | Edureka
Edureka!
 
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Exceptional Handling in Java
QaziUmarF786
 
JUNit Presentation
Animesh Kumar
 
Java Unit Testing
Nayanda Haberty
 
Understanding Unit Testing
ikhwanhayat
 
Unit Testing with Jest
Maayan Glikser
 
Smoke Testing
Kanoah
 
An Introduction to Unit Testing
Joe Tremblay
 
Test Complete
RomSoft SRL
 
Introduction to JUnit
Devvrat Shukla
 
Java Logging
Zeeshan Bilal
 
Introduction to jest
pksjce
 
Manual software-testing-interview-questions-with-answers
Sachin Gupta
 
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 
Spring Meetup Paris - Back to the basics of Spring (Boot)
Eric SIBER
 
Selenium interview-questions-freshers
Naga Mani
 
Exception handling in java
pooja kumari
 

Viewers also liked (20)

PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PPT
Unit testing with java
Dinuka Malalanayake
 
PPTX
Junit 4.0
pallavikhandekar212
 
ODP
Easymock Tutorial
Sbin m
 
PDF
Unit testing with JUnit
Thomas Zimmermann
 
PDF
Unit testing best practices
nickokiss
 
PPTX
UNIT TESTING PPT
suhasreddy1
 
PDF
China: City kills 5,000 dogs to curb rabies outbreak
dogtrainingalways16
 
PDF
Test Case Potency Assessment
STAG Software Private Limited
 
PDF
Mockito tutorial for beginners
inTwentyEight Minutes
 
PPT
Assessing Unit Test Quality
guest268ee8
 
PDF
Getting started with jMock
ayman diab
 
PPT
Junit y Jmock
kaolong
 
PPTX
Jmock testing
dandb-technology
 
PPT
EasyMock for Java
Deepak Singhvi
 
PPT
Junit
Manav Prasad
 
PPTX
Automation testing & Unit testing
Kapil Rajpurohit
 
PPTX
Mocking in Python
Excella
 
PPSX
Junit
FAROOK Samath
 
ODP
Java code coverage with JCov. Implementation details and use cases.
Alexandre (Shura) Iline
 
Unit Testing in Java
Ahmed M. Gomaa
 
Unit testing with java
Dinuka Malalanayake
 
Easymock Tutorial
Sbin m
 
Unit testing with JUnit
Thomas Zimmermann
 
Unit testing best practices
nickokiss
 
UNIT TESTING PPT
suhasreddy1
 
China: City kills 5,000 dogs to curb rabies outbreak
dogtrainingalways16
 
Test Case Potency Assessment
STAG Software Private Limited
 
Mockito tutorial for beginners
inTwentyEight Minutes
 
Assessing Unit Test Quality
guest268ee8
 
Getting started with jMock
ayman diab
 
Junit y Jmock
kaolong
 
Jmock testing
dandb-technology
 
EasyMock for Java
Deepak Singhvi
 
Automation testing & Unit testing
Kapil Rajpurohit
 
Mocking in Python
Excella
 
Java code coverage with JCov. Implementation details and use cases.
Alexandre (Shura) Iline
 
Ad

Similar to JMockit Framework Overview (20)

PDF
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
PPTX
Mocking with Mockito
Paul Churchward
 
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
PDF
Unit testing - A&BP CC
JWORKS powered by Ordina
 
PPT
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
ODP
Embrace Unit Testing
alessiopace
 
KEY
Testing w-mocks
Macon Pegram
 
ODP
Mule ctf
D.Rajesh Kumar
 
PDF
System verilog important
elumalai7
 
PPTX
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
PPTX
Test api
Ivo Manolov
 
PDF
Software Engineering - RS3
AtakanAral
 
DOCX
systemverilog-interview-questions.docx
ssuser1c8ca21
 
PPT
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
PPT
Spring training
TechFerry
 
PPTX
JAVA PROGRAMMING presentation for engineering student.pptx
proboygamer007
 
PDF
Spring 3.1 and MVC Testing Support
Sam Brannen
 
ODP
S313352 optimizing java device testing with automatic feature discovering
romanovfedor
 
PPTX
Intro To Unit and integration Testing
Paul Churchward
 
PPTX
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
Mocking with Mockito
Paul Churchward
 
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
Embrace Unit Testing
alessiopace
 
Testing w-mocks
Macon Pegram
 
Mule ctf
D.Rajesh Kumar
 
System verilog important
elumalai7
 
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
Test api
Ivo Manolov
 
Software Engineering - RS3
AtakanAral
 
systemverilog-interview-questions.docx
ssuser1c8ca21
 
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
Spring training
TechFerry
 
JAVA PROGRAMMING presentation for engineering student.pptx
proboygamer007
 
Spring 3.1 and MVC Testing Support
Sam Brannen
 
S313352 optimizing java device testing with automatic feature discovering
romanovfedor
 
Intro To Unit and integration Testing
Paul Churchward
 
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
Ad

More from Mario Peshev (20)

PDF
Why Does an eCommerce Store Cost 200 to 100K And More?
Mario Peshev
 
PDF
Management Decision Making Process
Mario Peshev
 
PDF
The Future Of WordPress In 2020
Mario Peshev
 
PDF
What Makes PHP An Awesome Language
Mario Peshev
 
PDF
Top 6 Business Tips for October 2019
Mario Peshev
 
PDF
The Future of WordPress And WooCommerce
Mario Peshev
 
PPTX
Tips for Successful WordPress Enterprise Projects
Mario Peshev
 
PDF
WordPress Architecture for Tech-Savvy Managers
Mario Peshev
 
PDF
Business and Monetization Opportunities for Developers
Mario Peshev
 
PDF
Building SaaS with WordPress - WordCamp Netherlands 2016
Mario Peshev
 
PDF
WordPress Code Architecture
Mario Peshev
 
PDF
Virtual Company - Go Limitless
Mario Peshev
 
PDF
Debugging WordPress
Mario Peshev
 
PDF
Platforms based on WordPress
Mario Peshev
 
PDF
WordPress Theme Reviewers Team
Mario Peshev
 
PDF
Get Involved with WordPress
Mario Peshev
 
PDF
Contributing to WordPress
Mario Peshev
 
PDF
Start Your Website for Free!
Mario Peshev
 
PDF
Choosing a WordPress Theme
Mario Peshev
 
PDF
Sass in 5
Mario Peshev
 
Why Does an eCommerce Store Cost 200 to 100K And More?
Mario Peshev
 
Management Decision Making Process
Mario Peshev
 
The Future Of WordPress In 2020
Mario Peshev
 
What Makes PHP An Awesome Language
Mario Peshev
 
Top 6 Business Tips for October 2019
Mario Peshev
 
The Future of WordPress And WooCommerce
Mario Peshev
 
Tips for Successful WordPress Enterprise Projects
Mario Peshev
 
WordPress Architecture for Tech-Savvy Managers
Mario Peshev
 
Business and Monetization Opportunities for Developers
Mario Peshev
 
Building SaaS with WordPress - WordCamp Netherlands 2016
Mario Peshev
 
WordPress Code Architecture
Mario Peshev
 
Virtual Company - Go Limitless
Mario Peshev
 
Debugging WordPress
Mario Peshev
 
Platforms based on WordPress
Mario Peshev
 
WordPress Theme Reviewers Team
Mario Peshev
 
Get Involved with WordPress
Mario Peshev
 
Contributing to WordPress
Mario Peshev
 
Start Your Website for Free!
Mario Peshev
 
Choosing a WordPress Theme
Mario Peshev
 
Sass in 5
Mario Peshev
 

Recently uploaded (20)

PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
July Patch Tuesday
Ivanti
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 

JMockit Framework Overview

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