SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
© Asprotunity Ltd
Giovanni Asproni
email: gasproni@asprotunity.com
twitter: @gasproni
linkedin: http://www.linkedin.com/in/gasproni
Faking Hell
Use, abuse and misuse of fakes, mocks and other test doubles
1
© Asprotunity Ltd
Test Doubles
• Sometimes we need to test classes that interact with other objects which are difficult to control
• The real object has nondeterministic behaviour (e.g., random number generator)
• The real object is difficult to set up (e.g., requiring a certain file system, database, or network
environment)
• The real object has behaviour that is hard to trigger (e.g., a network error)
• The real object is slow
• The real object has (or is) a user interface
• The test needs to ask the real object about how it was used (e.g., confirm that a callback
function was actually called)
• The real object does not yet exist (e.g., interfacing with other teams or new hardware
systems)
2
© Asprotunity Ltd
Test Doubles
• Dummies
• Stubs
• Spies
• Fakes
• Mocks
3
© Asprotunity Ltd
Dummies
• Dummy objects are passed around but never
actually used
• E.g., a mandatory argument in a constructor never
used during a specific test
4
© Asprotunity Ltd
Stubs
• Stubs provide canned answers to calls made during
the test
5
© Asprotunity Ltd
Spies
• Spies are stubs that also record some information
based on how they were called. (e.g., the number of
times a method has been called)
6
© Asprotunity Ltd 7
public class OrderStateTest {
private static String TALISKER = "Talisker";
private WarehouseStub warehouse = new WarehouseStub();
@Test
public void orderIsFilledIfEnoughInWarehouse() {
Order order = new Order(TALISKER, 50);
order.fill(warehouse);
assertTrue(order.isFilled())
assertTrue(warehouse.removeCalled);
}
@Test
public void orderDoesNotRemoveIfNotEnough() {
Order order = new Order(TALISKER, 51);
order.fill(warehouse);
assertFalse(order.isFilled());
assertFalse(warehouse.removeCalled);
}
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
public class WarehouseStub implements Warehouse {
public boolean removeCalled = false;
public void hasInventory(String brand, int amount) {
return “Talisker”.equals(brand) && amount <= 50
}
public void remove(String brand, int amount) {
removeCalled = true;
}
…..
}
© Asprotunity Ltd
Fakes
• Fake objects actually have working
implementations, but take some shortcuts which
make them not suitable for production (e.g., an in
memory database)
8
© Asprotunity Ltd 9
public class OrderStateTest {
private static String TALISKER = "Talisker";
private Warehouse warehouse = new WarehouseFake();
@Test
public void orderIsFilledIfEnoughInWarehouse() {
Order order = new Order(TALISKER, 50);
order.fill(warehouse);
assertTrue(order.isFilled())
}
@Test
public void orderDoesNotRemoveIfNotEnough() {
Order order = new Order(TALISKER, 51);
order.fill(warehouse);
assertFalse(order.isFilled());
}
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
public class WarehouseFake implements Warehouse {
private HashMap<String, Integer> inventoryByBrand;
public WarehouseFake() {
inventoryByBrand =
new HashMap<>(){{put(“Talisker”, 50);}}
}
public void hasInventory(String brand, int required) {
available = inventoryByBrand.get(brand)
return available != null && required <= available;
}
public void remove(String brand, int amount) {
available = inventoryByBrand.get(brand)
if (available == null || amount > available) {
// Manage the error…
}
else {
inventoryByBrand.put(brand, available - amount);
}
}
…..
}
© Asprotunity Ltd
Mocks
• Mocks are objects pre-programmed with
expectations which form a specification of the calls
they are expected to receive
10
© Asprotunity Ltd
History of MockObjects
• Invented at Connextra and XtC in 1999
• The initial purpose was to get rid of getters in testing
• Component composition
• Tell don’t ask
• Testing behaviours
• More at http://www.mockobjects.com/2009/09/brief-
history-of-mock-objects.html
11
© Asprotunity Ltd 12
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
@Test
public void fillingDoesNotRemoveIfNotEnoughInStock() {
Order order = new Order(TALISKER, 51);
Mockery context = new JUnit4Mockery();
Warehouse mockWarehouse = context.mock(Warehouse.class);
//setup - expectations
context.checking(new Expectations() {{
oneOf(mockWarehouse).hasInventory(with(any(String.class)), with(any(int.class)));
will(returnValue(false));
never(mockWarehouse).remove(with(any(String.class)), with(any(int.class)));
}});
order.fill(mockWarehouse));
context.assertIsSatisfied();
assertFalse(order.isFilled());
}
© Asprotunity Ltd
Mocks Aren’t Stubs
• Mocks are meant for testing behaviour
• Stubs and all other doubles are generally used for
testing state
• Classic TDD vs Mockist TDD (Classic school vs
London School of TDD)
13
http://martinfowler.com/articles/mocksArentStubs.html
© Asprotunity Ltd 14
public class OrderStateTest {
private static String TALISKER = "Talisker";
private Warehouse warehouse = new WarehouseStub();
@Test
public void orderIsFilledIfEnoughInWarehouse() {
Order order = new Order(TALISKER, 50);
order.fill(warehouse);
assertTrue(order.isFilled())
}
@Test
public void orderDoesNotRemoveIfNotEnough() {
Order order = new Order(TALISKER, 51);
order.fill(warehouse);
assertFalse(order.isFilled());
}
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
public class WarehouseStub implements Warehouse {
public void hasInventory(String brand, int amount) {
return “Talisker”.equals(brand) && amount <= 50
}
public void remove(String brand, int amount) {
// Intentionally blank
}
…..
}
© Asprotunity Ltd 15
public class OrderInteractionTest {
private static String TALISKER = "Talisker";
@Test
public void fillingRemovesInventoryIfInStock() {
//setup - data
Order order = new Order(TALISKER, 50);
Mockery context = new JUnit4Mockery();
Warehouse mockWarehouse = context.mock(Warehouse.class);
//setup - expectations
context.checking(new Expectations() {{
oneOf(mockWarehouse).hasInventory(TALISKER, 50);
will(returnValue(true));
oneOf(mockWarehouse).remove(TALISKER, 50);
}});
order.fill(mockWarehouse);
context.assertIsSatisfied();
assertTrue(order.isFilled());
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
© Asprotunity Ltd 16
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
@Test
public void fillingDoesNotRemoveIfNotEnoughInStock() {
Order order = new Order(TALISKER, 51);
Mockery context = new JUnit4Mockery();
Warehouse mockWarehouse = context.mock(Warehouse.class);
//setup - expectations
context.checking(new Expectations() {{
oneOf(mockWarehouse).hasInventory(with(any(String.class)), with(any(int.class)));
will(returnValue(false));
never(mockWarehouse).remove(with(any(String.class)), with(any(int.class)));
}});
order.fill(mockWarehouse));
context.assertIsSatisfied();
assertFalse(order.isFilled());
}
© Asprotunity Ltd 17
Outside-In And Middle-Out
Database
Client
GUI Domain layer Server
Walking skeleton
© Asprotunity Ltd
Sometimes we need to test
state, sometimes we need
to test behaviour, and
sometimes we need both
18
State Or Behaviour?
© Asprotunity Ltd
Problems Frequently Due To
• The design of the application is unfit for purpose
• The test has no clear purpose
• Plain old confusion
• …I just want to increase code coverage…
19
© Asprotunity Ltd
The Design Of The Application Is Unfit For
Purpose
• Too many dependencies to mock
• Too many interactions with a single mock object
• Mocks nested into each other
20
© Asprotunity Ltd
The Test Has No Clear Purpose
• Testing state or behaviour?
• Fakes or stubs used to test behaviour
• Use of mock objects used to test state
21
© Asprotunity Ltd 22
public class OrderStateTest {
private static String TALISKER = "Talisker";
private WarehouseStub warehouse = new WarehouseStub();
@Test
public void orderIsFilledIfEnoughInWarehouse() {
Order order = new Order(TALISKER, 50);
order.fill(warehouse);
assertTrue(order.isFilled())
assertTrue(warehouse.removeCalled);
}
@Test
public void orderDoesNotRemoveIfNotEnough() {
Order order = new Order(TALISKER, 51);
order.fill(warehouse);
assertFalse(order.isFilled());
assertFalse(warehouse.removeCalled);
}
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
public class WarehouseStub implements Warehouse {
public boolean removeCalled = false;
public void hasInventory(String brand, int amount) {
return “Talisker”.equals(brand) && amount <= 50
}
public void remove(String brand, int amount) {
removeCalled = true;
}
…..
}
© Asprotunity Ltd 23
public class OrderInteractionTest {
private static String TALISKER = "Talisker";
@Test
public void fillingRemovesInventoryIfInStock() {
//setup - data
Order order = new Order(TALISKER, 50);
Mockery context = new JUnit4Mockery();
Warehouse mockWarehouse = context.mock(Warehouse.class);
//setup - expectations
context.checking(new Expectations() {{
oneOf(mockWarehouse).hasInventory(TALISKER, 50);
will(returnValue(true));
oneOf(mockWarehouse).remove(TALISKER, 50);
}});
order.fill(mockWarehouse);
// We don’t check that context.assertIsSatisfied();
assertTrue(order.isFilled());
}
Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
© Asprotunity Ltd
Plain Old Confusion
• Testing the mocks
• Too many dependencies or interactions
• Partial mocking
24
© Asprotunity Ltd 25
…I just want to increase code coverage…
© Asprotunity Ltd
The Solution To Those Problems?
• Learn to listen to what the tests are telling you
• Avoid dubious practices as much as possible
• Partial mocks
• Mocking concrete classes
• Monkey patching
26
© Asprotunity Ltd 27
To Mock Or Not To Mock?
© Asprotunity Ltd
Test Doubles: Some Advantages
• Clarify which interactions are actually important for
the test
• Help in design protocols
• Make testing of some behaviours possible
• Allows for creation of faster tests
• Can alleviate dependencies on other teams
28
© Asprotunity Ltd
Test Doubles: Some (Alleged) Disadvantages
• Duplication of effort
• Changes of behaviour of the real object need to
be reflected in the test doubles
• Tests coupled to implementation (in case of mocks)
29
© Asprotunity Ltd
I’m Biased
• I find test doubles useful
• The important thing is to know which ones to use when
• …and when it’s best to use the real object
• The real object is“simple”to build and to interact with
• Full system tests
• Etc.
30
© Asprotunity Ltd 31
Questions?
© Asprotunity Ltd 32

Mais conteúdo relacionado

Mais procurados

Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest MatchersShai Yallin
 
No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012Alex Soto
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
Testing the waters of iOS
Testing the waters of iOSTesting the waters of iOS
Testing the waters of iOSKremizas Kostas
 
ActiveRecord Query Interface (1), Season 1
ActiveRecord Query Interface (1), Season 1ActiveRecord Query Interface (1), Season 1
ActiveRecord Query Interface (1), Season 1RORLAB
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsAndrei Pangin
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programingwahyuseptiansyah
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaMite Mitreski
 
Executable documentation
Executable documentationExecutable documentation
Executable documentationRussell Gold
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)Danny Preussler
 
Recommending Method Invocation Context Changes
Recommending Method Invocation Context ChangesRecommending Method Invocation Context Changes
Recommending Method Invocation Context ChangesBeat Fluri
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In DepthWO Community
 

Mais procurados (20)

Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012No SQL Unit - Devoxx 2012
No SQL Unit - Devoxx 2012
 
Server1
Server1Server1
Server1
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Testing the waters of iOS
Testing the waters of iOSTesting the waters of iOS
Testing the waters of iOS
 
ActiveRecord Query Interface (1), Season 1
ActiveRecord Query Interface (1), Season 1ActiveRecord Query Interface (1), Season 1
ActiveRecord Query Interface (1), Season 1
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
Executable documentation
Executable documentationExecutable documentation
Executable documentation
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
 
Lab4
Lab4Lab4
Lab4
 
Recommending Method Invocation Context Changes
Recommending Method Invocation Context ChangesRecommending Method Invocation Context Changes
Recommending Method Invocation Context Changes
 
COScheduler In Depth
COScheduler In DepthCOScheduler In Depth
COScheduler In Depth
 

Destaque

Software Configuration Management Problemas e Soluções
Software Configuration Management Problemas e SoluçõesSoftware Configuration Management Problemas e Soluções
Software Configuration Management Problemas e Soluçõeselliando dias
 
WANTED: Seeking Single Agile Knowledge Development Tool-set
WANTED: Seeking Single Agile Knowledge Development Tool-setWANTED: Seeking Single Agile Knowledge Development Tool-set
WANTED: Seeking Single Agile Knowledge Development Tool-setBrad Appleton
 
How do you deliver your applications to the cloud?
How do you deliver your applications to the cloud?How do you deliver your applications to the cloud?
How do you deliver your applications to the cloud?Michael Elder
 
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug Bass
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug BassGo2Group_secrets of high-performing software teams_EAD event_san jose_Doug Bass
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug BassGo2Group, Inc.
 
Is agile adoption losing steam?
Is agile adoption losing steam?Is agile adoption losing steam?
Is agile adoption losing steam?Go2Group, Inc.
 
Tui Travel - Overcoming the Challenges of Agile Methods
Tui Travel - Overcoming the Challenges of Agile MethodsTui Travel - Overcoming the Challenges of Agile Methods
Tui Travel - Overcoming the Challenges of Agile MethodsDBmaestro - Database DevOps
 
Trustworthy Transparency and Lean Traceability
Trustworthy Transparency and Lean TraceabilityTrustworthy Transparency and Lean Traceability
Trustworthy Transparency and Lean TraceabilityBrad Appleton
 
Continuous delivery made possible
Continuous delivery made possibleContinuous delivery made possible
Continuous delivery made possiblemimmozzo_
 
DBTA Data Summit : Eliminating the data constraint in Application Development
DBTA Data Summit : Eliminating the data constraint in Application DevelopmentDBTA Data Summit : Eliminating the data constraint in Application Development
DBTA Data Summit : Eliminating the data constraint in Application DevelopmentKyle Hailey
 
Delphix modernization whitepaper
Delphix  modernization whitepaperDelphix  modernization whitepaper
Delphix modernization whitepaperFranco_Dagosto
 
Delphix and DBmaestro
Delphix and DBmaestroDelphix and DBmaestro
Delphix and DBmaestroKyle Hailey
 
Kscope 2013 delphix
Kscope 2013 delphixKscope 2013 delphix
Kscope 2013 delphixKyle Hailey
 
Agile Configuration Management Environments
Agile Configuration Management EnvironmentsAgile Configuration Management Environments
Agile Configuration Management EnvironmentsBrad Appleton
 
Test case management and requirements traceability
Test case management and requirements traceabilityTest case management and requirements traceability
Test case management and requirements traceabilityGo2Group, Inc.
 
Delphix Workflow for SQL Server
Delphix Workflow for SQL ServerDelphix Workflow for SQL Server
Delphix Workflow for SQL Serverrcaccia
 
Preventing the Next Deployment Issue with Continuous Performance Testing and ...
Preventing the Next Deployment Issue with Continuous Performance Testing and ...Preventing the Next Deployment Issue with Continuous Performance Testing and ...
Preventing the Next Deployment Issue with Continuous Performance Testing and ...Correlsense
 
MuleSoft Connect 2015 - Go2Group presentation
MuleSoft Connect 2015 - Go2Group presentationMuleSoft Connect 2015 - Go2Group presentation
MuleSoft Connect 2015 - Go2Group presentationGo2Group, Inc.
 

Destaque (20)

Software Configuration Management Problemas e Soluções
Software Configuration Management Problemas e SoluçõesSoftware Configuration Management Problemas e Soluções
Software Configuration Management Problemas e Soluções
 
WANTED: Seeking Single Agile Knowledge Development Tool-set
WANTED: Seeking Single Agile Knowledge Development Tool-setWANTED: Seeking Single Agile Knowledge Development Tool-set
WANTED: Seeking Single Agile Knowledge Development Tool-set
 
P4 Branching Overview
P4 Branching OverviewP4 Branching Overview
P4 Branching Overview
 
How do you deliver your applications to the cloud?
How do you deliver your applications to the cloud?How do you deliver your applications to the cloud?
How do you deliver your applications to the cloud?
 
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug Bass
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug BassGo2Group_secrets of high-performing software teams_EAD event_san jose_Doug Bass
Go2Group_secrets of high-performing software teams_EAD event_san jose_Doug Bass
 
Is agile adoption losing steam?
Is agile adoption losing steam?Is agile adoption losing steam?
Is agile adoption losing steam?
 
Tui Travel - Overcoming the Challenges of Agile Methods
Tui Travel - Overcoming the Challenges of Agile MethodsTui Travel - Overcoming the Challenges of Agile Methods
Tui Travel - Overcoming the Challenges of Agile Methods
 
Trustworthy Transparency and Lean Traceability
Trustworthy Transparency and Lean TraceabilityTrustworthy Transparency and Lean Traceability
Trustworthy Transparency and Lean Traceability
 
Continuous delivery made possible
Continuous delivery made possibleContinuous delivery made possible
Continuous delivery made possible
 
DBTA Data Summit : Eliminating the data constraint in Application Development
DBTA Data Summit : Eliminating the data constraint in Application DevelopmentDBTA Data Summit : Eliminating the data constraint in Application Development
DBTA Data Summit : Eliminating the data constraint in Application Development
 
Delphix modernization whitepaper
Delphix  modernization whitepaperDelphix  modernization whitepaper
Delphix modernization whitepaper
 
Delphix and DBmaestro
Delphix and DBmaestroDelphix and DBmaestro
Delphix and DBmaestro
 
Kscope 2013 delphix
Kscope 2013 delphixKscope 2013 delphix
Kscope 2013 delphix
 
In (database) automation we trust
In (database) automation we trustIn (database) automation we trust
In (database) automation we trust
 
Jenkins Plugin
Jenkins PluginJenkins Plugin
Jenkins Plugin
 
Agile Configuration Management Environments
Agile Configuration Management EnvironmentsAgile Configuration Management Environments
Agile Configuration Management Environments
 
Test case management and requirements traceability
Test case management and requirements traceabilityTest case management and requirements traceability
Test case management and requirements traceability
 
Delphix Workflow for SQL Server
Delphix Workflow for SQL ServerDelphix Workflow for SQL Server
Delphix Workflow for SQL Server
 
Preventing the Next Deployment Issue with Continuous Performance Testing and ...
Preventing the Next Deployment Issue with Continuous Performance Testing and ...Preventing the Next Deployment Issue with Continuous Performance Testing and ...
Preventing the Next Deployment Issue with Continuous Performance Testing and ...
 
MuleSoft Connect 2015 - Go2Group presentation
MuleSoft Connect 2015 - Go2Group presentationMuleSoft Connect 2015 - Go2Group presentation
MuleSoft Connect 2015 - Go2Group presentation
 

Semelhante a Faking Hell

Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...LetAgileFly
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Danny Preussler
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)Tech in Asia ID
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsFandy Gotama
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 

Semelhante a Faking Hell (20)

Resilience mit Hystrix
Resilience mit HystrixResilience mit Hystrix
Resilience mit Hystrix
 
Resilience with Hystrix
Resilience with HystrixResilience with Hystrix
Resilience with Hystrix
 
03 - Testowanie GUI
03 - Testowanie GUI03 - Testowanie GUI
03 - Testowanie GUI
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Android testing
Android testingAndroid testing
Android testing
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 

Mais de Giovanni Asproni

Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)Giovanni Asproni
 
Remote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironmentRemote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironmentGiovanni Asproni
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemGiovanni Asproni
 
Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)Giovanni Asproni
 
Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)Giovanni Asproni
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemGiovanni Asproni
 
Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)Giovanni Asproni
 
Writing usableap isinpractice
Writing usableap isinpracticeWriting usableap isinpractice
Writing usableap isinpracticeGiovanni Asproni
 

Mais de Giovanni Asproni (9)

Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
Remote Mob Programming In A High Stakes Environment (Agile Manchester 2023)
 
Remote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironmentRemote mobprogrammingina highstakesenvironment
Remote mobprogrammingina highstakesenvironment
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your System
 
Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)Scaling Agile Done Right (XP 2017 version)
Scaling Agile Done Right (XP 2017 version)
 
Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)Scaling Agile Done Right (Agile Manchester 2017)
Scaling Agile Done Right (Agile Manchester 2017)
 
Creating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your SystemCreating An Incremental Architecture For Your System
Creating An Incremental Architecture For Your System
 
Design For Testability
Design For TestabilityDesign For Testability
Design For Testability
 
Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)Methodology Patterns (Agile Cambridge 2014)
Methodology Patterns (Agile Cambridge 2014)
 
Writing usableap isinpractice
Writing usableap isinpracticeWriting usableap isinpractice
Writing usableap isinpractice
 

Último

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 

Último (20)

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Faking Hell

  • 1. © Asprotunity Ltd Giovanni Asproni email: gasproni@asprotunity.com twitter: @gasproni linkedin: http://www.linkedin.com/in/gasproni Faking Hell Use, abuse and misuse of fakes, mocks and other test doubles 1
  • 2. © Asprotunity Ltd Test Doubles • Sometimes we need to test classes that interact with other objects which are difficult to control • The real object has nondeterministic behaviour (e.g., random number generator) • The real object is difficult to set up (e.g., requiring a certain file system, database, or network environment) • The real object has behaviour that is hard to trigger (e.g., a network error) • The real object is slow • The real object has (or is) a user interface • The test needs to ask the real object about how it was used (e.g., confirm that a callback function was actually called) • The real object does not yet exist (e.g., interfacing with other teams or new hardware systems) 2
  • 3. © Asprotunity Ltd Test Doubles • Dummies • Stubs • Spies • Fakes • Mocks 3
  • 4. © Asprotunity Ltd Dummies • Dummy objects are passed around but never actually used • E.g., a mandatory argument in a constructor never used during a specific test 4
  • 5. © Asprotunity Ltd Stubs • Stubs provide canned answers to calls made during the test 5
  • 6. © Asprotunity Ltd Spies • Spies are stubs that also record some information based on how they were called. (e.g., the number of times a method has been called) 6
  • 7. © Asprotunity Ltd 7 public class OrderStateTest { private static String TALISKER = "Talisker"; private WarehouseStub warehouse = new WarehouseStub(); @Test public void orderIsFilledIfEnoughInWarehouse() { Order order = new Order(TALISKER, 50); order.fill(warehouse); assertTrue(order.isFilled()) assertTrue(warehouse.removeCalled); } @Test public void orderDoesNotRemoveIfNotEnough() { Order order = new Order(TALISKER, 51); order.fill(warehouse); assertFalse(order.isFilled()); assertFalse(warehouse.removeCalled); } } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html public class WarehouseStub implements Warehouse { public boolean removeCalled = false; public void hasInventory(String brand, int amount) { return “Talisker”.equals(brand) && amount <= 50 } public void remove(String brand, int amount) { removeCalled = true; } ….. }
  • 8. © Asprotunity Ltd Fakes • Fake objects actually have working implementations, but take some shortcuts which make them not suitable for production (e.g., an in memory database) 8
  • 9. © Asprotunity Ltd 9 public class OrderStateTest { private static String TALISKER = "Talisker"; private Warehouse warehouse = new WarehouseFake(); @Test public void orderIsFilledIfEnoughInWarehouse() { Order order = new Order(TALISKER, 50); order.fill(warehouse); assertTrue(order.isFilled()) } @Test public void orderDoesNotRemoveIfNotEnough() { Order order = new Order(TALISKER, 51); order.fill(warehouse); assertFalse(order.isFilled()); } } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html public class WarehouseFake implements Warehouse { private HashMap<String, Integer> inventoryByBrand; public WarehouseFake() { inventoryByBrand = new HashMap<>(){{put(“Talisker”, 50);}} } public void hasInventory(String brand, int required) { available = inventoryByBrand.get(brand) return available != null && required <= available; } public void remove(String brand, int amount) { available = inventoryByBrand.get(brand) if (available == null || amount > available) { // Manage the error… } else { inventoryByBrand.put(brand, available - amount); } } ….. }
  • 10. © Asprotunity Ltd Mocks • Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive 10
  • 11. © Asprotunity Ltd History of MockObjects • Invented at Connextra and XtC in 1999 • The initial purpose was to get rid of getters in testing • Component composition • Tell don’t ask • Testing behaviours • More at http://www.mockobjects.com/2009/09/brief- history-of-mock-objects.html 11
  • 12. © Asprotunity Ltd 12 Adapted from: http://martinfowler.com/articles/mocksArentStubs.html @Test public void fillingDoesNotRemoveIfNotEnoughInStock() { Order order = new Order(TALISKER, 51); Mockery context = new JUnit4Mockery(); Warehouse mockWarehouse = context.mock(Warehouse.class); //setup - expectations context.checking(new Expectations() {{ oneOf(mockWarehouse).hasInventory(with(any(String.class)), with(any(int.class))); will(returnValue(false)); never(mockWarehouse).remove(with(any(String.class)), with(any(int.class))); }}); order.fill(mockWarehouse)); context.assertIsSatisfied(); assertFalse(order.isFilled()); }
  • 13. © Asprotunity Ltd Mocks Aren’t Stubs • Mocks are meant for testing behaviour • Stubs and all other doubles are generally used for testing state • Classic TDD vs Mockist TDD (Classic school vs London School of TDD) 13 http://martinfowler.com/articles/mocksArentStubs.html
  • 14. © Asprotunity Ltd 14 public class OrderStateTest { private static String TALISKER = "Talisker"; private Warehouse warehouse = new WarehouseStub(); @Test public void orderIsFilledIfEnoughInWarehouse() { Order order = new Order(TALISKER, 50); order.fill(warehouse); assertTrue(order.isFilled()) } @Test public void orderDoesNotRemoveIfNotEnough() { Order order = new Order(TALISKER, 51); order.fill(warehouse); assertFalse(order.isFilled()); } } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html public class WarehouseStub implements Warehouse { public void hasInventory(String brand, int amount) { return “Talisker”.equals(brand) && amount <= 50 } public void remove(String brand, int amount) { // Intentionally blank } ….. }
  • 15. © Asprotunity Ltd 15 public class OrderInteractionTest { private static String TALISKER = "Talisker"; @Test public void fillingRemovesInventoryIfInStock() { //setup - data Order order = new Order(TALISKER, 50); Mockery context = new JUnit4Mockery(); Warehouse mockWarehouse = context.mock(Warehouse.class); //setup - expectations context.checking(new Expectations() {{ oneOf(mockWarehouse).hasInventory(TALISKER, 50); will(returnValue(true)); oneOf(mockWarehouse).remove(TALISKER, 50); }}); order.fill(mockWarehouse); context.assertIsSatisfied(); assertTrue(order.isFilled()); } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
  • 16. © Asprotunity Ltd 16 Adapted from: http://martinfowler.com/articles/mocksArentStubs.html @Test public void fillingDoesNotRemoveIfNotEnoughInStock() { Order order = new Order(TALISKER, 51); Mockery context = new JUnit4Mockery(); Warehouse mockWarehouse = context.mock(Warehouse.class); //setup - expectations context.checking(new Expectations() {{ oneOf(mockWarehouse).hasInventory(with(any(String.class)), with(any(int.class))); will(returnValue(false)); never(mockWarehouse).remove(with(any(String.class)), with(any(int.class))); }}); order.fill(mockWarehouse)); context.assertIsSatisfied(); assertFalse(order.isFilled()); }
  • 17. © Asprotunity Ltd 17 Outside-In And Middle-Out Database Client GUI Domain layer Server Walking skeleton
  • 18. © Asprotunity Ltd Sometimes we need to test state, sometimes we need to test behaviour, and sometimes we need both 18 State Or Behaviour?
  • 19. © Asprotunity Ltd Problems Frequently Due To • The design of the application is unfit for purpose • The test has no clear purpose • Plain old confusion • …I just want to increase code coverage… 19
  • 20. © Asprotunity Ltd The Design Of The Application Is Unfit For Purpose • Too many dependencies to mock • Too many interactions with a single mock object • Mocks nested into each other 20
  • 21. © Asprotunity Ltd The Test Has No Clear Purpose • Testing state or behaviour? • Fakes or stubs used to test behaviour • Use of mock objects used to test state 21
  • 22. © Asprotunity Ltd 22 public class OrderStateTest { private static String TALISKER = "Talisker"; private WarehouseStub warehouse = new WarehouseStub(); @Test public void orderIsFilledIfEnoughInWarehouse() { Order order = new Order(TALISKER, 50); order.fill(warehouse); assertTrue(order.isFilled()) assertTrue(warehouse.removeCalled); } @Test public void orderDoesNotRemoveIfNotEnough() { Order order = new Order(TALISKER, 51); order.fill(warehouse); assertFalse(order.isFilled()); assertFalse(warehouse.removeCalled); } } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html public class WarehouseStub implements Warehouse { public boolean removeCalled = false; public void hasInventory(String brand, int amount) { return “Talisker”.equals(brand) && amount <= 50 } public void remove(String brand, int amount) { removeCalled = true; } ….. }
  • 23. © Asprotunity Ltd 23 public class OrderInteractionTest { private static String TALISKER = "Talisker"; @Test public void fillingRemovesInventoryIfInStock() { //setup - data Order order = new Order(TALISKER, 50); Mockery context = new JUnit4Mockery(); Warehouse mockWarehouse = context.mock(Warehouse.class); //setup - expectations context.checking(new Expectations() {{ oneOf(mockWarehouse).hasInventory(TALISKER, 50); will(returnValue(true)); oneOf(mockWarehouse).remove(TALISKER, 50); }}); order.fill(mockWarehouse); // We don’t check that context.assertIsSatisfied(); assertTrue(order.isFilled()); } Adapted from: http://martinfowler.com/articles/mocksArentStubs.html
  • 24. © Asprotunity Ltd Plain Old Confusion • Testing the mocks • Too many dependencies or interactions • Partial mocking 24
  • 25. © Asprotunity Ltd 25 …I just want to increase code coverage…
  • 26. © Asprotunity Ltd The Solution To Those Problems? • Learn to listen to what the tests are telling you • Avoid dubious practices as much as possible • Partial mocks • Mocking concrete classes • Monkey patching 26
  • 27. © Asprotunity Ltd 27 To Mock Or Not To Mock?
  • 28. © Asprotunity Ltd Test Doubles: Some Advantages • Clarify which interactions are actually important for the test • Help in design protocols • Make testing of some behaviours possible • Allows for creation of faster tests • Can alleviate dependencies on other teams 28
  • 29. © Asprotunity Ltd Test Doubles: Some (Alleged) Disadvantages • Duplication of effort • Changes of behaviour of the real object need to be reflected in the test doubles • Tests coupled to implementation (in case of mocks) 29
  • 30. © Asprotunity Ltd I’m Biased • I find test doubles useful • The important thing is to know which ones to use when • …and when it’s best to use the real object • The real object is“simple”to build and to interact with • Full system tests • Etc. 30
  • 31. © Asprotunity Ltd 31 Questions?