SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Python summer course play with python (lab1)
Python summer course  play with python  (lab1)Python summer course  play with python  (lab1)
Python summer course play with python (lab1)
iloveallahsomuch
 
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
Donal Fellows
 

Tendances (19)

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

En vedette

Unity3D Scripting: State Machine
Unity3D Scripting: State MachineUnity3D Scripting: State Machine
Unity3D Scripting: State Machine
Sperasoft
 
Apache Hadoop 1.1
Apache Hadoop 1.1Apache Hadoop 1.1
Apache Hadoop 1.1
Sperasoft
 

En vedette (14)

English language at games
English language at gamesEnglish language at games
English language at games
 
SQL Server -Service Broker - Reliable Messaging
SQL Server -Service Broker - Reliable MessagingSQL Server -Service Broker - Reliable Messaging
SQL Server -Service Broker - Reliable Messaging
 
Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to Maven
 
Gi = global illumination
Gi = global illuminationGi = global illumination
Gi = global illumination
 
SQL Server 2012 - Semantic Search
SQL Server 2012 - Semantic SearchSQL Server 2012 - Semantic Search
SQL Server 2012 - Semantic Search
 
JIRA Development
JIRA DevelopmentJIRA Development
JIRA Development
 
Effective Мeetings
Effective МeetingsEffective Мeetings
Effective Мeetings
 
Unity3D Scripting: State Machine
Unity3D Scripting: State MachineUnity3D Scripting: State Machine
Unity3D Scripting: State Machine
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks
 
SQL Server 2012 - FileTables
SQL Server 2012 - FileTables SQL Server 2012 - FileTables
SQL Server 2012 - FileTables
 
Unreal Engine 4 Introduction
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 Introduction
 
Apache Hadoop 1.1
Apache Hadoop 1.1Apache Hadoop 1.1
Apache Hadoop 1.1
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to Elasticsearch
 
Web Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolWeb Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI Tool
 

Similaire à Mocks introduction

Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
JUSTSTYLISH3B2MOHALI
 
public class Point {   Insert your name here    private dou.pdf
public class Point {    Insert your name here    private dou.pdfpublic class Point {    Insert your name here    private dou.pdf
public class Point {   Insert your name here    private dou.pdf
anandshingavi23
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
Technopark
 
Java весна 2013 лекция 5
Java весна 2013 лекция 5Java весна 2013 лекция 5
Java весна 2013 лекция 5
Technopark
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
aquadreammail
 

Similaire à Mocks introduction (20)

TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving Testing
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Lecture6
Lecture6Lecture6
Lecture6
 
Please help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdfPlease help!!I wanted to know how to add a high score to this prog.pdf
Please help!!I wanted to know how to add a high score to this prog.pdf
 
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca JDD2015: Where Test Doubles can lead you...  - Sebastian Malaca
JDD2015: Where Test Doubles can lead you... - Sebastian Malaca
 
Google guava
Google guavaGoogle guava
Google guava
 
applet.docx
applet.docxapplet.docx
applet.docx
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
public class Point {   Insert your name here    private dou.pdf
public class Point {    Insert your name here    private dou.pdfpublic class Point {    Insert your name here    private dou.pdf
public class Point {   Insert your name here    private dou.pdf
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
 
TDD Hands-on
TDD Hands-onTDD Hands-on
TDD Hands-on
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Java весна 2013 лекция 5
Java весна 2013 лекция 5Java весна 2013 лекция 5
Java весна 2013 лекция 5
 
Awt
AwtAwt
Awt
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
 

Plus de Sperasoft

Apache Cassandra
Apache CassandraApache Cassandra
Apache Cassandra
Sperasoft
 

Plus de Sperasoft (20)

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

Dernier

“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
Muhammad Subhan
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 

Dernier (20)

“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 

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