SlideShare a Scribd company logo
Mocks Introduction
● Classic style
● Mockist style
● Different tools
● Links
Contents
● State verification
● Heavyweight dependencies
● Test doubles (Dummy, Fake, Stub, Mock)
Unit to be tested
DatabaseE-mail system
Other objects
Classic Style
Example. Dog and House
package com.sperasoft.test;
public class Dog {
private House home;
public boolean isPleasured() {
if (home == null) {
return false;
}
return (home.getWidth() * home.getHeight() *
home.getDepth() > 3);
}
public void settleIn(House home) {
this.home = home;
}
}
package com.sperasoft.test;
public interface House {
int getWidth();
int getHeight();
int getDepth();
}
Dog Class House Interface
package com.sperasoft.test;
public class HouseImpl implements House {
private int w;
private int h;
private int d;
public HouseImpl(int width, int height, int depth) {
w = width;
h = height;
d = depth;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public int getDepth() {
return d;
}
}
House Implementation
package com.sperasoft.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class DogTest {
@Test
public void testIsPleasuredWithBigHouse() {
Dog dog = new Dog();
House dogHouse = new HouseImpl(1, 2, 3);
dog.settleIn(dogHouse);
assertTrue(dog.isPleasured());
}
//other test methods
}
Classic Test
package com.sperasoft.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class DogTest {
@Test
public void testIsPleasuredWithBigHouse() {
Dog dog = new Dog();
House dogHouse = new House() {
public int getWidth() {
return 1;
}
public int getHeight() {
return 2;
}
public int getDepth() {
return 3;
}
};
dog.settleIn(dogHouse);
assertTrue(dog.isPleasured());
}
//other test methods
}
Classic Test with Stub
package com.sperasoft.test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.junit.Test;
public class DogTestJMockit {
@Mocked
private House houseMock;
@Test
public void testIsPleasuredWithBigHouse() {
new NonStrictExpectations() {
{
houseMock.getWidth(); result
= 1;
houseMock.getHeight(); result
= 2;
houseMock.getDepth(); result
= 3; maxTimes = 1;
}
};
Dog dog = new Dog();
dog.settleIn(houseMock);
assertTrue(dog.isPleasured());
}
//other test methods
}
Test with Mocks
Weather!
package com.sperasoft.test;
final public class Weather {
static public int getTemperature() {
return (int)(Math.random()*60 —
20);
}
}
package com.sperasoft.test;
public class Dog {
private House home;
public boolean isPleasured() {
if (home == null) {
return false;
}
if (Weather.getTemperature() > 30 || Weather.getTemperature() < 20)
{
return false;
}
return (home.getWidth() * home.getHeight() * home.getDepth() > 3);
}
public void settleIn(House home) {
this.home = home;
}
}
Dog & Weather
package com.sperasoft.test;
//...imports
import mockit.Mocked;
import mockit.NonStrictExpectations;
public class DogTestJMockit {
@Mocked
private House houseMock;
@Mocked
private Weather weatherMock;
@Test
public void testIsPleasuredWithBigHouse() {
new NonStrictExpectations() {
{
houseMock.getWidth(); result = 1;
houseMock.getHeight(); result = 2;
houseMock.getDepth(); result = 3; maxTimes = 1;
Weather.getTemperature(); result = 25; times = 1;
}
};
Dog dog = new Dog();
dog.settleIn(houseMock);
assertTrue(dog.isPleasured());
}
//other test methods
}
Mocking Weather
● Setup and verification are extended by expectations
● Behaviour verification
● Need Driven Development
● Test spies alternative (stubs with behaviour verifications)
Unit to be tested
MockMock
Mock
Mocks Style
Advantages of Mocks
● Immediate neighbours only
● Outside-in style
● Test isolation
● Good to test objects that don't change their state
● Additional knowledge
● Difficult to maintain
● Heavy coupling to an implementation
Have to use TDD. Tests first. Use loose expectations to avoid this.
● Overhead additional libraries settings
● Addictive
Disadvantages of Mocks
package com.sperasoft.test;
import static org.junit.Assert.assertTrue;
import org.easymock.EasyMock;
import org.junit.Test;
public class DogTestEasyMock {
@Test
public void testIsPleasuredWithBigHouse() {
Dog dog = new Dog();
House dogHouse = EasyMock.createMock(House.class);
EasyMock.expect(dogHouse.getWidth()).andReturn(1);
EasyMock.expect(dogHouse.getHeight()).andReturn(2);
EasyMock.expect(dogHouse.getDepth()).andReturn(3).times(0, 1);
EasyMock.replay(dogHouse);
dog.settleIn(dogHouse);
assertTrue(dog.isPleasured());
}
//other test methods
}
EasyMock
package com.sperasoft.test;
import static org.junit.Assert.assertTrue;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
public class DogTestJMock {
@Test
public void testIsPleasuredWithBigHouse() {
Mockery context = new Mockery();
Dog d = new Dog();
final House dogHouse = context.mock(House.class);
Expectations expectations = new Expectations() {
{
allowing(dogHouse).getWidth();
will(returnValue(1));
allowing(dogHouse).getHeight();
will(returnValue(2));
oneOf(dogHouse).getDepth();
will(returnValue(3));
}
};
context.checking(expectations);
d.settleIn(dogHouse);
assertTrue(d.isPleasured());
}
}
JMock
package com.sperasoft.test;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.mockito.Mockito;
public class DogTestMockito {
@Test
public void testIsPleasuredWithBigHouse() {
Dog dog = new Dog();
House dogHouse = Mockito.mock(House.class);
Mockito.when(dogHouse.getWidth()).thenReturn(1);
Mockito.when(dogHouse.getHeight()).thenReturn(2);
Mockito.when(dogHouse.getDepth()).thenReturn(3);
dog.settleIn(dogHouse);
assertTrue(dog.isPleasured());
Mockito.verify(dogHouse, Mockito.times(1)).getDepth();
}
//other test methods
}
Mockito
● M. Fowler «Mocks aren't stubs»
http://martinfowler.com/articles/mocksArentStubs.html
● Gerard Meszaros's book «Xunit test patterns»
http://xunitpatterns.com/
● Dan North's Behaviour Driven Development
http://dannorth.net/introducing-bdd/
● Jmock. http://www.jmock.org/
● EasyMock http://easymock.org/
● Mockito http://code.google.com/p/mockito/
● Jmockit http://code.google.com/p/jmockit/
Links
Questions?

More Related Content

PDF
DCN Practical
PDF
Core java pract_sem iii
PDF
Spock: A Highly Logical Way To Test
PDF
Spock framework
PPTX
#5 (Remote Method Invocation)
PPTX
Java practice programs for beginners
PDF
Java 8 - Nuts and Bold - SFEIR Benelux
PPTX
Java весна 2013 лекция 2
DCN Practical
Core java pract_sem iii
Spock: A Highly Logical Way To Test
Spock framework
#5 (Remote Method Invocation)
Java practice programs for beginners
Java 8 - Nuts and Bold - SFEIR Benelux
Java весна 2013 лекция 2

What's hot (19)

PDF
Advanced Java Practical File
PPTX
Smarter Testing With Spock
PPTX
Java 8 Puzzlers [as presented at OSCON 2016]
PDF
Java_practical_handbook
PDF
C++ Windows Forms L11 - Inheritance
PDF
C++ Windows Forms L02 - Controls P1
PPTX
The Groovy Puzzlers – The Complete 01 and 02 Seasons
PDF
C++ Windows Forms L05 - Controls P4
PDF
C++ Windows Forms L09 - GDI P2
PPT
Socket Programming
PDF
C++ Windows Forms L10 - Instantiate
PDF
6. Generics. Collections. Streams
DOCX
Java practical
PDF
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
PDF
Programming with Python and PostgreSQL
PDF
C++ Windows Forms L04 - Controls P3
PDF
Python summer course play with python (lab1)
PPTX
Optimizing Tcl Bytecode
PDF
Pdxpugday2010 pg90
Advanced Java Practical File
Smarter Testing With Spock
Java 8 Puzzlers [as presented at OSCON 2016]
Java_practical_handbook
C++ Windows Forms L11 - Inheritance
C++ Windows Forms L02 - Controls P1
The Groovy Puzzlers – The Complete 01 and 02 Seasons
C++ Windows Forms L05 - Controls P4
C++ Windows Forms L09 - GDI P2
Socket Programming
C++ Windows Forms L10 - Instantiate
6. Generics. Collections. Streams
Java practical
Gabriele Petronella - FP for front-end development: should you care? - Codemo...
Programming with Python and PostgreSQL
C++ Windows Forms L04 - Controls P3
Python summer course play with python (lab1)
Optimizing Tcl Bytecode
Pdxpugday2010 pg90
Ad

Viewers also liked (14)

PDF
English language at games
PDF
SQL Server -Service Broker - Reliable Messaging
PDF
Introduction to Maven
PDF
Gi = global illumination
PDF
SQL Server 2012 - Semantic Search
PDF
JIRA Development
PDF
Effective Мeetings
PDF
Unity3D Scripting: State Machine
PPTX
Code and Memory Optimisation Tricks
PDF
SQL Server 2012 - FileTables
PDF
Unreal Engine 4 Introduction
PDF
Apache Hadoop 1.1
PDF
Introduction to Elasticsearch
PDF
Web Services Automated Testing via SoapUI Tool
English language at games
SQL Server -Service Broker - Reliable Messaging
Introduction to Maven
Gi = global illumination
SQL Server 2012 - Semantic Search
JIRA Development
Effective Мeetings
Unity3D Scripting: State Machine
Code and Memory Optimisation Tricks
SQL Server 2012 - FileTables
Unreal Engine 4 Introduction
Apache Hadoop 1.1
Introduction to Elasticsearch
Web Services Automated Testing via SoapUI Tool
Ad

Similar to Mocks introduction (20)

KEY
Testing w-mocks
PDF
Mockito a software testing project a.pdf
PPT
Mockito with a hint of PowerMock
PPT
Xp Day 080506 Unit Tests And Mocks
ODP
Easymock Tutorial
PDF
Understanding Mocks
PPTX
Mock with Mockito
PDF
Mockito tutorial
PPTX
Refactoring Away from Test Hell
PDF
Android testing
PDF
Faking Hell
PPT
EasyMock for Java
ODP
Using Mockito
PPT
Testing – With Mock Objects
PPTX
Junit mockito and PowerMock in Java
PPTX
JUnit Test Case With Processminer modules.pptx
PPTX
Mock your way with Mockito
PPTX
Mocking - Visug session
PPTX
Junit, mockito, etc
PDF
JUnit & Mockito, first steps
Testing w-mocks
Mockito a software testing project a.pdf
Mockito with a hint of PowerMock
Xp Day 080506 Unit Tests And Mocks
Easymock Tutorial
Understanding Mocks
Mock with Mockito
Mockito tutorial
Refactoring Away from Test Hell
Android testing
Faking Hell
EasyMock for Java
Using Mockito
Testing – With Mock Objects
Junit mockito and PowerMock in Java
JUnit Test Case With Processminer modules.pptx
Mock your way with Mockito
Mocking - Visug session
Junit, mockito, etc
JUnit & Mockito, first steps

More from Sperasoft (20)

PDF
особенности работы с Locomotion в Unreal Engine 4
PDF
концепт и архитектура геймплея в Creach: The Depleted World
PPTX
Опыт разработки VR игры для UE4
PPTX
Организация работы с UE4 в команде до 20 человек
PPTX
Gameplay Tags
PDF
Data Driven Gameplay in UE4
PPTX
The theory of relational databases
PPTX
Automated layout testing using Galen Framework
PDF
Sperasoft talks: Android Security Threats
PDF
Sperasoft Talks: RxJava Functional Reactive Programming on Android
PDF
Sperasoft‬ talks j point 2015
PDF
MOBILE DEVELOPMENT with HTML, CSS and JS
PDF
Quick Intro Into Kanban
PDF
ECMAScript 6 Review
PDF
Console Development in 15 minutes
PDF
Database Indexes
PDF
Evolution of Game Development
PDF
Apache Cassandra
PDF
Test Methods
PDF
Unity Programming
особенности работы с Locomotion в Unreal Engine 4
концепт и архитектура геймплея в Creach: The Depleted World
Опыт разработки VR игры для UE4
Организация работы с UE4 в команде до 20 человек
Gameplay Tags
Data Driven Gameplay in UE4
The theory of relational databases
Automated layout testing using Galen Framework
Sperasoft talks: Android Security Threats
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft‬ talks j point 2015
MOBILE DEVELOPMENT with HTML, CSS and JS
Quick Intro Into Kanban
ECMAScript 6 Review
Console Development in 15 minutes
Database Indexes
Evolution of Game Development
Apache Cassandra
Test Methods
Unity Programming

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Approach and Philosophy of On baking technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
sap open course for s4hana steps from ECC to s4
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The AUB Centre for AI in Media Proposal.docx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Review of recent advances in non-invasive hemoglobin estimation
Building Integrated photovoltaic BIPV_UPV.pdf
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
MYSQL Presentation for SQL database connectivity
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Approach and Philosophy of On baking technology
Understanding_Digital_Forensics_Presentation.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
20250228 LYD VKU AI Blended-Learning.pptx
sap open course for s4hana steps from ECC to s4

Mocks introduction

  • 2. ● Classic style ● Mockist style ● Different tools ● Links Contents
  • 3. ● State verification ● Heavyweight dependencies ● Test doubles (Dummy, Fake, Stub, Mock) Unit to be tested DatabaseE-mail system Other objects Classic Style
  • 4. Example. Dog and House package com.sperasoft.test; public class Dog { private House home; public boolean isPleasured() { if (home == null) { return false; } return (home.getWidth() * home.getHeight() * home.getDepth() > 3); } public void settleIn(House home) { this.home = home; } } package com.sperasoft.test; public interface House { int getWidth(); int getHeight(); int getDepth(); } Dog Class House Interface
  • 5. package com.sperasoft.test; public class HouseImpl implements House { private int w; private int h; private int d; public HouseImpl(int width, int height, int depth) { w = width; h = height; d = depth; } public int getWidth() { return w; } public int getHeight() { return h; } public int getDepth() { return d; } } House Implementation
  • 6. package com.sperasoft.test; import static org.junit.Assert.*; import org.junit.Test; public class DogTest { @Test public void testIsPleasuredWithBigHouse() { Dog dog = new Dog(); House dogHouse = new HouseImpl(1, 2, 3); dog.settleIn(dogHouse); assertTrue(dog.isPleasured()); } //other test methods } Classic Test
  • 7. package com.sperasoft.test; import static org.junit.Assert.*; import org.junit.Test; public class DogTest { @Test public void testIsPleasuredWithBigHouse() { Dog dog = new Dog(); House dogHouse = new House() { public int getWidth() { return 1; } public int getHeight() { return 2; } public int getDepth() { return 3; } }; dog.settleIn(dogHouse); assertTrue(dog.isPleasured()); } //other test methods } Classic Test with Stub
  • 8. package com.sperasoft.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Test; public class DogTestJMockit { @Mocked private House houseMock; @Test public void testIsPleasuredWithBigHouse() { new NonStrictExpectations() { { houseMock.getWidth(); result = 1; houseMock.getHeight(); result = 2; houseMock.getDepth(); result = 3; maxTimes = 1; } }; Dog dog = new Dog(); dog.settleIn(houseMock); assertTrue(dog.isPleasured()); } //other test methods } Test with Mocks
  • 9. Weather! package com.sperasoft.test; final public class Weather { static public int getTemperature() { return (int)(Math.random()*60 — 20); } }
  • 10. package com.sperasoft.test; public class Dog { private House home; public boolean isPleasured() { if (home == null) { return false; } if (Weather.getTemperature() > 30 || Weather.getTemperature() < 20) { return false; } return (home.getWidth() * home.getHeight() * home.getDepth() > 3); } public void settleIn(House home) { this.home = home; } } Dog & Weather
  • 11. package com.sperasoft.test; //...imports import mockit.Mocked; import mockit.NonStrictExpectations; public class DogTestJMockit { @Mocked private House houseMock; @Mocked private Weather weatherMock; @Test public void testIsPleasuredWithBigHouse() { new NonStrictExpectations() { { houseMock.getWidth(); result = 1; houseMock.getHeight(); result = 2; houseMock.getDepth(); result = 3; maxTimes = 1; Weather.getTemperature(); result = 25; times = 1; } }; Dog dog = new Dog(); dog.settleIn(houseMock); assertTrue(dog.isPleasured()); } //other test methods } Mocking Weather
  • 12. ● Setup and verification are extended by expectations ● Behaviour verification ● Need Driven Development ● Test spies alternative (stubs with behaviour verifications) Unit to be tested MockMock Mock Mocks Style
  • 13. Advantages of Mocks ● Immediate neighbours only ● Outside-in style ● Test isolation ● Good to test objects that don't change their state
  • 14. ● Additional knowledge ● Difficult to maintain ● Heavy coupling to an implementation Have to use TDD. Tests first. Use loose expectations to avoid this. ● Overhead additional libraries settings ● Addictive Disadvantages of Mocks
  • 15. package com.sperasoft.test; import static org.junit.Assert.assertTrue; import org.easymock.EasyMock; import org.junit.Test; public class DogTestEasyMock { @Test public void testIsPleasuredWithBigHouse() { Dog dog = new Dog(); House dogHouse = EasyMock.createMock(House.class); EasyMock.expect(dogHouse.getWidth()).andReturn(1); EasyMock.expect(dogHouse.getHeight()).andReturn(2); EasyMock.expect(dogHouse.getDepth()).andReturn(3).times(0, 1); EasyMock.replay(dogHouse); dog.settleIn(dogHouse); assertTrue(dog.isPleasured()); } //other test methods } EasyMock
  • 16. package com.sperasoft.test; import static org.junit.Assert.assertTrue; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; public class DogTestJMock { @Test public void testIsPleasuredWithBigHouse() { Mockery context = new Mockery(); Dog d = new Dog(); final House dogHouse = context.mock(House.class); Expectations expectations = new Expectations() { { allowing(dogHouse).getWidth(); will(returnValue(1)); allowing(dogHouse).getHeight(); will(returnValue(2)); oneOf(dogHouse).getDepth(); will(returnValue(3)); } }; context.checking(expectations); d.settleIn(dogHouse); assertTrue(d.isPleasured()); } } JMock
  • 17. package com.sperasoft.test; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.mockito.Mockito; public class DogTestMockito { @Test public void testIsPleasuredWithBigHouse() { Dog dog = new Dog(); House dogHouse = Mockito.mock(House.class); Mockito.when(dogHouse.getWidth()).thenReturn(1); Mockito.when(dogHouse.getHeight()).thenReturn(2); Mockito.when(dogHouse.getDepth()).thenReturn(3); dog.settleIn(dogHouse); assertTrue(dog.isPleasured()); Mockito.verify(dogHouse, Mockito.times(1)).getDepth(); } //other test methods } Mockito
  • 18. ● M. Fowler «Mocks aren't stubs» http://martinfowler.com/articles/mocksArentStubs.html ● Gerard Meszaros's book «Xunit test patterns» http://xunitpatterns.com/ ● Dan North's Behaviour Driven Development http://dannorth.net/introducing-bdd/ ● Jmock. http://www.jmock.org/ ● EasyMock http://easymock.org/ ● Mockito http://code.google.com/p/mockito/ ● Jmockit http://code.google.com/p/jmockit/ Links