SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von Sperasoft

Apache Cassandra
Apache CassandraApache Cassandra
Apache Cassandra
Sperasoft
 

Mehr von 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
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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