SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
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?

Más contenido relacionado

La actualidad más candente

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
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]Baruch Sadogursky
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbookManusha Dilan
 
C++ Windows Forms L11 - Inheritance
C++ Windows Forms L11 - Inheritance C++ Windows Forms L11 - Inheritance
C++ Windows Forms L11 - Inheritance Mohammad Shaker
 
C++ Windows Forms L02 - Controls P1
C++ Windows Forms L02 - Controls P1C++ Windows Forms L02 - Controls P1
C++ Windows Forms L02 - Controls P1Mohammad Shaker
 
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 SeasonsBaruch Sadogursky
 
C++ Windows Forms L05 - Controls P4
C++ Windows Forms L05 - Controls P4C++ Windows Forms L05 - Controls P4
C++ Windows Forms L05 - Controls P4Mohammad Shaker
 
C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2Mohammad Shaker
 
C++ Windows Forms L10 - Instantiate
C++ Windows Forms L10 - InstantiateC++ Windows Forms L10 - Instantiate
C++ Windows Forms L10 - InstantiateMohammad Shaker
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
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...Codemotion
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
C++ Windows Forms L04 - Controls P3
C++ Windows Forms L04 - Controls P3C++ Windows Forms L04 - Controls P3
C++ Windows Forms L04 - Controls P3Mohammad Shaker
 
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 BytecodeDonal Fellows
 

La actualidad más candente (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
 

Destacado

English language at games
English language at gamesEnglish language at games
English language at gamesSperasoft
 
SQL Server -Service Broker - Reliable Messaging
SQL Server -Service Broker - Reliable MessagingSQL Server -Service Broker - Reliable Messaging
SQL Server -Service Broker - Reliable MessagingSperasoft
 
Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to MavenSperasoft
 
Gi = global illumination
Gi = global illuminationGi = global illumination
Gi = global illuminationSperasoft
 
SQL Server 2012 - Semantic Search
SQL Server 2012 - Semantic SearchSQL Server 2012 - Semantic Search
SQL Server 2012 - Semantic SearchSperasoft
 
JIRA Development
JIRA DevelopmentJIRA Development
JIRA DevelopmentSperasoft
 
Effective Мeetings
Effective МeetingsEffective Мeetings
Effective МeetingsSperasoft
 
Unity3D Scripting: State Machine
Unity3D Scripting: State MachineUnity3D Scripting: State Machine
Unity3D Scripting: State MachineSperasoft
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks Sperasoft
 
SQL Server 2012 - FileTables
SQL Server 2012 - FileTables SQL Server 2012 - FileTables
SQL Server 2012 - FileTables Sperasoft
 
Unreal Engine 4 Introduction
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 IntroductionSperasoft
 
Apache Hadoop 1.1
Apache Hadoop 1.1Apache Hadoop 1.1
Apache Hadoop 1.1Sperasoft
 
Introduction to Elasticsearch
Introduction to ElasticsearchIntroduction to Elasticsearch
Introduction to ElasticsearchSperasoft
 
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 ToolSperasoft
 

Destacado (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
 

Similar a Mocks introduction

TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingDavid Rodenas
 
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.pdfJUSTSTYLISH3B2MOHALI
 
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 PROIDEA
 
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.pdfanandshingavi23
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
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 RavenDBtdc-globalcode
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Java весна 2013 лекция 5
Java весна 2013 лекция 5Java весна 2013 лекция 5
Java весна 2013 лекция 5Technopark
 
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.pdfaquadreammail
 

Similar a 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
 

Más de Sperasoft

особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4Sperasoft
 
концепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted Worldконцепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted WorldSperasoft
 
Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4Sperasoft
 
Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек Sperasoft
 
Gameplay Tags
Gameplay TagsGameplay Tags
Gameplay TagsSperasoft
 
Data Driven Gameplay in UE4
Data Driven Gameplay in UE4Data Driven Gameplay in UE4
Data Driven Gameplay in UE4Sperasoft
 
The theory of relational databases
The theory of relational databasesThe theory of relational databases
The theory of relational databasesSperasoft
 
Automated layout testing using Galen Framework
Automated layout testing using Galen FrameworkAutomated layout testing using Galen Framework
Automated layout testing using Galen FrameworkSperasoft
 
Sperasoft talks: Android Security Threats
Sperasoft talks: Android Security ThreatsSperasoft talks: Android Security Threats
Sperasoft talks: Android Security ThreatsSperasoft
 
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 AndroidSperasoft
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft
 
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 JSSperasoft
 
Quick Intro Into Kanban
Quick Intro Into KanbanQuick Intro Into Kanban
Quick Intro Into KanbanSperasoft
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 ReviewSperasoft
 
Console Development in 15 minutes
Console Development in 15 minutesConsole Development in 15 minutes
Console Development in 15 minutesSperasoft
 
Database Indexes
Database IndexesDatabase Indexes
Database IndexesSperasoft
 
Evolution of Game Development
Evolution of Game DevelopmentEvolution of Game Development
Evolution of Game DevelopmentSperasoft
 
Apache Cassandra
Apache CassandraApache Cassandra
Apache CassandraSperasoft
 
Test Methods
Test MethodsTest Methods
Test MethodsSperasoft
 
Unity Programming
Unity Programming Unity Programming
Unity Programming Sperasoft
 

Más 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
 

Último

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 CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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 Scriptwesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Último (20)

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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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