SlideShare a Scribd company logo
Advanced Unit Testing for Java By Denilson Nastacio Mastering  Mock Objects
Your Host Denilson Nastacio 14 years in software development Quality Enthusiast Rational Unified Process practitioner RTP Scrolls ( http://rtpscrolls.blogspot.com ) SourcePatch ( http://sourcepatch.blogspot.com ) LinkedIn ( http://www.linkedin.com/in/nastacio )
Agenda Concepts Intercepting methods Declaring expectations Tools Q&A
Different levels of abstraction Code logic Tests whether isolated methods respect their exposed contract Guarantees that there are no broken code paths No runtime dependencies: mock objects Integration test (by developer, not QA organization) Tests combination of classes and runtime environment Require runtime support Detect incompatibilities between components Residual code logic tests Function test (by developer, not QA organization) Real end-user scenarios Residual code logic and integration test. A C E D B A C E B A C E D B
Ideal resource allocation Code logic Integration Function QA Function Test Development Dev QA System Test Runtime dependencies Cost per volume of code
The case against system dependencies on unit testing Complex Create user accounts, upgrade OS, install fixpacks, etc Slow Minutes to recycle servers between tests Unnecessary During development, you want to test the code, purge logic errors before starting test integration
Code logic test Classes tested in isolation Black box testing Based on declared interfaces, not actual implementation Guarantees that methods respect their declared interfaces Good to validate public APIs Bad for validating exceptions related to environment problems White box testing Based on implementation, usually due to incomplete specifications Typical of test written after the fact Concerned with exhaustive test of all lines in the actual source code Good to verify exception handling when combined with mock objects
Mock environments for Java
Classes of mock environments Environment simulators Respond like the real environment Pros: Simulate complex behavior without environment dependencies Cons: Few simulators available, maintaining a simulator rivals the complexity of maintaining a real application Mock object frameworks Same interfaces as the real environment Developer must preset the mock objects with the expected responses Pros: Mock objects can be generated quickly for any environment Cons: Presetting mock objects for unit tests may require lots of code
Mock libraries JMockit Instructs the JVM to replace calls to any method with code under your control One-two punch with JMock against bunkered initialization within the production code, such as calls to constructors or static methods Use JMockit to intercept calls to static methods deep into the production code and return JMock pre-programmed objects. http://jmockit.dev.java.net   JMock Pre-program objects to expect calls and return values of your choice Instruct the production code to “talk to” mocked object instead of actual system dependency Mocks interfaces and classes. http://www.jmock.org
Anatomy of JMock in a test fixture @Test public   void  testTransferFunds()  throws  Exception { org.jmock.Mockery context =  new  Mockery(); context.setImposteriser(ClassImposteriser. INSTANCE ); final   float  testAmount = 300; final  BankAccount sourceAccount = context.mock(BankAccount. class ,  "source" ); final  BankAccount targetAccount = context.mock(BankAccount. class ,  "target" ); org.jmock.Expectations expect =  new  Expectations() { {   one(sourceAccount).withdraw(testAmount); one(targetAccount).deposit(testAmount); } }; context.checking(expect); Transaction tx =  new  Transaction(); tx.transferFunds(testAmount, sourceAccount, targetAccount);   context.assertIsSatisfied(); } Create mock Context Create mock instances Programs mock instances Adds expectation to mock context. Asks context whether all expectations were met.
Anatomy of JMockit in a test fixture – Inlined mock @Mocked   private   final  BankSOAUtil  unused  =  null ; @Test public   void  testBankAccountSOA()  throws  Exception { String inputDir =  "abc" ; final  String inputFile =  "AndrewBankAccountData.xml" ; new  mockit.Expectations() { { BankSOAUtil. getInputStream ((URL)withNotNull()); returns( new  FileInputStream(inputFile)); } }; // Bank account constructor reads its configuration using // BankSOAUtil.getInputStream BankAccount bc =  new  BankAccount( "userid" ,  "password" ); Assert. assertEquals ( "Andrew" , bc.getCustomerName()); } Inlined mocked expectation Programming the expectation Marking class to be mocked
Anatomy of JMockit in a test fixture – Using a mock class public void testBankAccountSOA() throws Exception {s Mockit.setUpMocks(MockBankSOAUtil.class); String inputFile = "AndrewBankAccountData.xml"; // Bank account constructor reads its configuration using  // BankSOAUtil. getInputStream BankAccount bc = new BankAccount(...); Assert.assertEquals("Andrew", bc.getCustomerName()); Mockit.tearDownMocks(); } @MockClass(realClass = BankSOAUtil.class) public static class  MockBankSOAUtil  { private static String inputFile = null; @Mock(invocations = 1) public static InputStream  getInputStream (URL inputUrl) throws IOException { return new FileInputStream(inputFile) ; } public static void setInputFile(String inputFile) { MockDogearUtil.inputFile = inputFile ; } } Instructs the JVM about the mock classes to be used Instructs the JVM to stop using JMockit mocks. Declares the production class to be mocked Indicates which methods of the production class should be mocked
Which one should I use? JMockit Can intercept any call to the JVM Significant improvements on expectation support during 2009 Supports bytecode level coverage metrics My new favorite JMock Used to have better control over behavior of mocked object, my former favorite Needs production code to provide “entry points” to receive the mocked objects
Building mock expectations Required versus allowed Is it important that the mocked method is called? JMock: allowing/ignored/one JMockit: Expectations, Verifications, and sub-classes Specific versus loose Is it important that the mocked method is called with a specific parameter? Both JMock and JMockit offer out-of-the-box mathcers for concepts like 'same value', 'same class', 'inherited from a class', 'null', 'not null', and others
When results matter – 1 of 3 What if results from dependency matter? public   class  ExternalClass { public  String somethingWithAReturnValue(String input) { return   "DEF" ; }
When results matter – JMock  2 of 3 final  ExternalClass ecMock = context.mock(ExternalClass. class ); org.jmock.Expectations expect =  new  org.jmock.Expectations() { { one(ecMock).somethingWithAReturnValue( &quot;specific value&quot; ); will( returnValue ( &quot;someReturnValue&quot; )); } }; final  ExternalClass ecMock = context.mock(ExternalClass. class ); org.jmock.Expectations expect =  new  org.jmock.Expectations() { { one(ecMock).somethingWithAReturnValue(with( any (String. class ))); will( returnValue ( &quot;someReturnValue&quot; )); } }; Use with(any(Class <T> type)) to instruct the  JMock mock to ignore input parameters
When results matter – Jmockit -  3 of 3 new mockit.Expectations () {  ExternalClass EcMock; { ecMock.somethingWithAReturnValue( &quot;specific value&quot; ); returns( &quot;someReturnValue&quot; )); } }; new mockit.Expectations () {  ExternalClass EcMock; { ecMock.somethingWithAReturnValue(withAny( &quot;&quot; ); returns( &quot;someReturnValue&quot; )); } }; Use withAny(Class <T> type)) to instruct the  JMockit mock to ignore input parameters
Other great companion tools DDTUnit http://ddtunit.sourceforge.net/ Cobertura http://cobertura.sourceforge.net/   Note: JMockit has its own code coverage support

More Related Content

PPT
JMockit Framework Overview
PPT
JMockit
PPTX
Mockito vs JMockit, battle of the mocking frameworks
PPTX
Unit Testing in Java
DOCX
Test Driven Development
PDF
Testdriven Development using JUnit and EasyMock
PPTX
PPT
EasyMock for Java
JMockit Framework Overview
JMockit
Mockito vs JMockit, battle of the mocking frameworks
Unit Testing in Java
Test Driven Development
Testdriven Development using JUnit and EasyMock
EasyMock for Java

What's hot (20)

PDF
Unit testing, principles
PPT
Unit testing with java
PDF
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
PDF
PPTX
Java Unit Testing
PPSX
PDF
Living With Legacy Code
PDF
Spring Certification Questions
PPTX
JUNit Presentation
PPTX
The definitive guide to java agents
PPT
Google mock for dummies
PDF
JAVASCRIPT Test Driven Development & Jasmine
PDF
The Art of Unit Testing - Towards a Testable Design
PDF
JUnit Pioneer
PPT
Working Effectively With Legacy Code
PDF
Java object oriented programming - OOPS
PPTX
Applying TDD to Legacy Code
PDF
Write testable code in java, best practices
PPTX
JUnit- A Unit Testing Framework
PPT
Unit testing, principles
Unit testing with java
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Java Unit Testing
Living With Legacy Code
Spring Certification Questions
JUNit Presentation
The definitive guide to java agents
Google mock for dummies
JAVASCRIPT Test Driven Development & Jasmine
The Art of Unit Testing - Towards a Testable Design
JUnit Pioneer
Working Effectively With Legacy Code
Java object oriented programming - OOPS
Applying TDD to Legacy Code
Write testable code in java, best practices
JUnit- A Unit Testing Framework
Ad

Viewers also liked (20)

PDF
Test driven development - JUnit basics and best practices
PDF
Unit testing with Junit
PDF
Unit testing with JUnit
PPTX
AngularJS & Job
PDF
Hicss 42 Presentation
PDF
Thinking beyond RDBMS - Building Polyglot Persistence Java Applications Devf...
PDF
Developing modern java web applications with java ee 7 and angular js
PDF
Introduction to Browser DOM
PDF
Becoming a professional software developer
PDF
Open shift for java(ee) developers
PDF
Working effectively with OpenShift
ODP
Simple Mobile Development With Ionic - Ondrisek
PDF
Interacting with the DOM (JavaScript)
ODP
A Happy Cloud Friendly Java Developer with OpenShift
PDF
Surviving as a Professional Software Developer
PPTX
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
PDF
Java EE 6 and NoSQL Workshop DevFest Austria
PDF
Bringing spatial love to your python application
PDF
Developing Great Apps with Apache Cordova
PPT
Indic threads java10-spring-roo-and-the-cloud
Test driven development - JUnit basics and best practices
Unit testing with Junit
Unit testing with JUnit
AngularJS & Job
Hicss 42 Presentation
Thinking beyond RDBMS - Building Polyglot Persistence Java Applications Devf...
Developing modern java web applications with java ee 7 and angular js
Introduction to Browser DOM
Becoming a professional software developer
Open shift for java(ee) developers
Working effectively with OpenShift
Simple Mobile Development With Ionic - Ondrisek
Interacting with the DOM (JavaScript)
A Happy Cloud Friendly Java Developer with OpenShift
Surviving as a Professional Software Developer
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
Java EE 6 and NoSQL Workshop DevFest Austria
Bringing spatial love to your python application
Developing Great Apps with Apache Cordova
Indic threads java10-spring-roo-and-the-cloud
Ad

Similar to Mastering Mock Objects - Advanced Unit Testing for Java (20)

PPTX
JUnit Test Case With Processminer modules.pptx
KEY
Testing w-mocks
PDF
Understanding Mocks
PDF
An Introduction To Unit Testing and TDD
PDF
31b - JUnit and Mockito.pdf
PPTX
Mock with Mockito
PDF
Unit testing basic
PPT
Mockito with a hint of PowerMock
PDF
Android Test Driven Development & Android Unit Testing
PPTX
Test-Driven Development
PDF
Mockito tutorial
PDF
Mockito a software testing project a.pdf
PPT
Testing – With Mock Objects
PPTX
Junit, mockito, etc
PDF
Devday2016 real unittestingwithmockframework-phatvu
PPTX
Introduction to JUnit testing in OpenDaylight
PPT
Xp Day 080506 Unit Tests And Mocks
PDF
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
ODP
Easymock Tutorial
PPTX
TDD - Unit Testing
JUnit Test Case With Processminer modules.pptx
Testing w-mocks
Understanding Mocks
An Introduction To Unit Testing and TDD
31b - JUnit and Mockito.pdf
Mock with Mockito
Unit testing basic
Mockito with a hint of PowerMock
Android Test Driven Development & Android Unit Testing
Test-Driven Development
Mockito tutorial
Mockito a software testing project a.pdf
Testing – With Mock Objects
Junit, mockito, etc
Devday2016 real unittestingwithmockframework-phatvu
Introduction to JUnit testing in OpenDaylight
Xp Day 080506 Unit Tests And Mocks
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
Easymock Tutorial
TDD - Unit Testing

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Per capita expenditure prediction using model stacking based on satellite ima...
Understanding_Digital_Forensics_Presentation.pptx
Big Data Technologies - Introduction.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reach Out and Touch Someone: Haptics and Empathic Computing
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectroscopy.pptx food analysis technology
sap open course for s4hana steps from ECC to s4
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Advanced methodologies resolving dimensionality complications for autism neur...

Mastering Mock Objects - Advanced Unit Testing for Java

  • 1. Advanced Unit Testing for Java By Denilson Nastacio Mastering Mock Objects
  • 2. Your Host Denilson Nastacio 14 years in software development Quality Enthusiast Rational Unified Process practitioner RTP Scrolls ( http://rtpscrolls.blogspot.com ) SourcePatch ( http://sourcepatch.blogspot.com ) LinkedIn ( http://www.linkedin.com/in/nastacio )
  • 3. Agenda Concepts Intercepting methods Declaring expectations Tools Q&A
  • 4. Different levels of abstraction Code logic Tests whether isolated methods respect their exposed contract Guarantees that there are no broken code paths No runtime dependencies: mock objects Integration test (by developer, not QA organization) Tests combination of classes and runtime environment Require runtime support Detect incompatibilities between components Residual code logic tests Function test (by developer, not QA organization) Real end-user scenarios Residual code logic and integration test. A C E D B A C E B A C E D B
  • 5. Ideal resource allocation Code logic Integration Function QA Function Test Development Dev QA System Test Runtime dependencies Cost per volume of code
  • 6. The case against system dependencies on unit testing Complex Create user accounts, upgrade OS, install fixpacks, etc Slow Minutes to recycle servers between tests Unnecessary During development, you want to test the code, purge logic errors before starting test integration
  • 7. Code logic test Classes tested in isolation Black box testing Based on declared interfaces, not actual implementation Guarantees that methods respect their declared interfaces Good to validate public APIs Bad for validating exceptions related to environment problems White box testing Based on implementation, usually due to incomplete specifications Typical of test written after the fact Concerned with exhaustive test of all lines in the actual source code Good to verify exception handling when combined with mock objects
  • 9. Classes of mock environments Environment simulators Respond like the real environment Pros: Simulate complex behavior without environment dependencies Cons: Few simulators available, maintaining a simulator rivals the complexity of maintaining a real application Mock object frameworks Same interfaces as the real environment Developer must preset the mock objects with the expected responses Pros: Mock objects can be generated quickly for any environment Cons: Presetting mock objects for unit tests may require lots of code
  • 10. Mock libraries JMockit Instructs the JVM to replace calls to any method with code under your control One-two punch with JMock against bunkered initialization within the production code, such as calls to constructors or static methods Use JMockit to intercept calls to static methods deep into the production code and return JMock pre-programmed objects. http://jmockit.dev.java.net JMock Pre-program objects to expect calls and return values of your choice Instruct the production code to “talk to” mocked object instead of actual system dependency Mocks interfaces and classes. http://www.jmock.org
  • 11. Anatomy of JMock in a test fixture @Test public void testTransferFunds() throws Exception { org.jmock.Mockery context = new Mockery(); context.setImposteriser(ClassImposteriser. INSTANCE ); final float testAmount = 300; final BankAccount sourceAccount = context.mock(BankAccount. class , &quot;source&quot; ); final BankAccount targetAccount = context.mock(BankAccount. class , &quot;target&quot; ); org.jmock.Expectations expect = new Expectations() { { one(sourceAccount).withdraw(testAmount); one(targetAccount).deposit(testAmount); } }; context.checking(expect); Transaction tx = new Transaction(); tx.transferFunds(testAmount, sourceAccount, targetAccount); context.assertIsSatisfied(); } Create mock Context Create mock instances Programs mock instances Adds expectation to mock context. Asks context whether all expectations were met.
  • 12. Anatomy of JMockit in a test fixture – Inlined mock @Mocked private final BankSOAUtil unused = null ; @Test public void testBankAccountSOA() throws Exception { String inputDir = &quot;abc&quot; ; final String inputFile = &quot;AndrewBankAccountData.xml&quot; ; new mockit.Expectations() { { BankSOAUtil. getInputStream ((URL)withNotNull()); returns( new FileInputStream(inputFile)); } }; // Bank account constructor reads its configuration using // BankSOAUtil.getInputStream BankAccount bc = new BankAccount( &quot;userid&quot; , &quot;password&quot; ); Assert. assertEquals ( &quot;Andrew&quot; , bc.getCustomerName()); } Inlined mocked expectation Programming the expectation Marking class to be mocked
  • 13. Anatomy of JMockit in a test fixture – Using a mock class public void testBankAccountSOA() throws Exception {s Mockit.setUpMocks(MockBankSOAUtil.class); String inputFile = &quot;AndrewBankAccountData.xml&quot;; // Bank account constructor reads its configuration using // BankSOAUtil. getInputStream BankAccount bc = new BankAccount(...); Assert.assertEquals(&quot;Andrew&quot;, bc.getCustomerName()); Mockit.tearDownMocks(); } @MockClass(realClass = BankSOAUtil.class) public static class MockBankSOAUtil { private static String inputFile = null; @Mock(invocations = 1) public static InputStream getInputStream (URL inputUrl) throws IOException { return new FileInputStream(inputFile) ; } public static void setInputFile(String inputFile) { MockDogearUtil.inputFile = inputFile ; } } Instructs the JVM about the mock classes to be used Instructs the JVM to stop using JMockit mocks. Declares the production class to be mocked Indicates which methods of the production class should be mocked
  • 14. Which one should I use? JMockit Can intercept any call to the JVM Significant improvements on expectation support during 2009 Supports bytecode level coverage metrics My new favorite JMock Used to have better control over behavior of mocked object, my former favorite Needs production code to provide “entry points” to receive the mocked objects
  • 15. Building mock expectations Required versus allowed Is it important that the mocked method is called? JMock: allowing/ignored/one JMockit: Expectations, Verifications, and sub-classes Specific versus loose Is it important that the mocked method is called with a specific parameter? Both JMock and JMockit offer out-of-the-box mathcers for concepts like 'same value', 'same class', 'inherited from a class', 'null', 'not null', and others
  • 16. When results matter – 1 of 3 What if results from dependency matter? public class ExternalClass { public String somethingWithAReturnValue(String input) { return &quot;DEF&quot; ; }
  • 17. When results matter – JMock 2 of 3 final ExternalClass ecMock = context.mock(ExternalClass. class ); org.jmock.Expectations expect = new org.jmock.Expectations() { { one(ecMock).somethingWithAReturnValue( &quot;specific value&quot; ); will( returnValue ( &quot;someReturnValue&quot; )); } }; final ExternalClass ecMock = context.mock(ExternalClass. class ); org.jmock.Expectations expect = new org.jmock.Expectations() { { one(ecMock).somethingWithAReturnValue(with( any (String. class ))); will( returnValue ( &quot;someReturnValue&quot; )); } }; Use with(any(Class <T> type)) to instruct the JMock mock to ignore input parameters
  • 18. When results matter – Jmockit - 3 of 3 new mockit.Expectations () { ExternalClass EcMock; { ecMock.somethingWithAReturnValue( &quot;specific value&quot; ); returns( &quot;someReturnValue&quot; )); } }; new mockit.Expectations () { ExternalClass EcMock; { ecMock.somethingWithAReturnValue(withAny( &quot;&quot; ); returns( &quot;someReturnValue&quot; )); } }; Use withAny(Class <T> type)) to instruct the JMockit mock to ignore input parameters
  • 19. Other great companion tools DDTUnit http://ddtunit.sourceforge.net/ Cobertura http://cobertura.sourceforge.net/ Note: JMockit has its own code coverage support