SlideShare a Scribd company logo
Just 
Mock 
It 
Mocks 
and 
Stubs 
Presented by Gavin Pickin 
Slides: http://gpickin.com/itb2014/ 
Website: http://gpickin.com 
Twitter: @gpickin
Introduc)on 
• Follow 
along 
with 
resources 
from 
h6p://gpickin.com/itb2014/ 
• If 
you 
want 
to 
find 
out 
more 
about 
me, 
my 
website 
has 
more 
than 
enough 
informa)on
20 
Second 
Agenda 
• Unit 
Tes)ng 
-­‐ 
Recap 
• What 
is 
Mocking 
• What 
is 
a 
Mock 
/ 
Stub 
• Why 
Mock 
• Let’s 
look 
at 
some 
Mocking
Unit 
Tes)ng 
“unit 
tes)ng 
is 
a 
soOware 
verifica)on 
and 
valida)on 
method 
in 
which 
a 
programmer 
tests 
if 
individual 
units 
of 
source 
code 
are 
fit 
for 
use. 
A 
unit 
is 
the 
smallest 
testable 
part 
of 
an 
applica)on” 
-­‐ 
wikipedia
Unit 
Tes)ng 
• Can 
improve 
code 
quality 
-­‐> 
quick 
error 
discovery 
• Code 
confidence 
via 
immediate 
verifica)on 
• Can 
expose 
high 
coupling 
• Will 
encourage 
refactoring 
to 
produce 
> 
testable 
code 
• Remember: 
Tes)ng 
is 
all 
about 
behavior 
and 
expecta)ons
Bugs 
Hurt
Bugs 
Hurt 
• Bugs 
hurt 
– 
the 
later 
in 
the 
process, 
the 
harder 
to 
fix. 
• Test 
Early 
and 
OOen 
– Find 
them 
before 
they 
rot 
your 
founda)on 
• Testable 
Code 
is 
Maintainable 
Code
Unit 
Tes)ng 
Basics
Test 
Driven 
Development
Important 
Tests 
• Unit 
Tes)ng 
– Test 
behavior 
of 
individual 
objects 
• Integra)on 
Tes)ng 
– Test 
En)re 
Applica)on 
from 
Top 
Down 
• UI 
verifica)on 
tes)ng 
– Verifica)on 
via 
HTML/Visual 
elements
Important 
Tes)ng 
Tools 
• TestBox 
(Run 
BDD 
and 
MXUnit 
style) 
• IDE 
-­‐ 
CF 
Builder 
/ 
Eclipse 
• Mocking 
Framework 
• ANT 
• Jenkins, 
Bamboo, 
Teamcity, 
other 
Cis 
• Selenium 
• Jmeter 
or 
Webstress 
Tool, 
Apache 
AB
What 
is 
Mocking? 
According 
to 
Merriam 
Webster 
• to 
laugh 
at 
or 
make 
fun 
of 
(someone 
or 
something) 
especially 
by 
copying 
an 
ac)on 
or 
a 
way 
of 
behaving 
or 
speaking 
• to 
imitate 
(as 
a 
mannerism) 
closely
What 
is 
Mocking? 
"A 
mock 
object 
is 
an 
object 
that 
takes 
the 
place 
of 
a 
‘real’ 
object 
in 
such 
a 
way 
that 
makes 
tes)ng 
easier 
and 
more 
meaningful, 
or 
in 
some 
cases, 
possible 
at 
all" 
by 
Sco6 
Bain 
-­‐ 
Emergent 
Design
Mocks
Mocks
Mocks
Mocks
Stub 
Object 
• A 
stub 
is 
an 
empty 
container, 
that 
represents 
an 
Object. 
• This 
can 
be 
useful 
for 
represen)ng 
CFCs 
and 
Objects 
that 
haven’t 
been 
wri6en 
yet.
Why 
use 
Mocking 
• Isolate 
your 
SUT 
-­‐> 
SoOware 
Under 
Test 
• To 
build 
against 
interfaces 
& 
contracts 
• Building 
against 
missing 
integra)on 
pieces 
• To 
control 
data 
and 
expecta)ons 
• Mock 
components 
whose 
behavior 
is 
undesirable 
or 
hard 
to 
control
Why 
Mock? 
• How 
do 
you 
test 
when 
helper 
components 
that 
are 
not 
built 
yet? 
• How 
do 
you 
do 
controlled 
excep)ons? 
• How 
do 
you 
test 
& 
control 
external 
API 
calls? 
• How 
do 
you 
control 
results 
from 
ColdFusion 
tags 
or 
func)ons? 
• How 
do 
you 
control 
network 
connec)ons? 
Do 
you 
pull 
the 
network 
plug?
Why 
Mock? 
How 
do 
you 
test 
code 
like 
this? 
<cfdirectory 
ac)on=”list” 
directory=”#arguments.path#” 
name=”qResults”> 
<ck6p 
url=”#arguments.urlPath#” 
results=”qResults”> 
<cfmail 
to=”#to#” 
from=”#from#” 
subject=”#subject#”>#content#</cfmail> 
<cfquery 
/> 
func)on 
init(){ 
var 
helper 
= 
new 
Helper(); 
} 
private 
func)on 
getData(){ 
return 
data; 
}
The 
COLD 
hard 
truth 
– 
It 
can 
Hurt 
• Tes)ng 
some 
code 
is 
hard, 
or 
almost 
impossible. 
• Refactor 
it 
• Mock 
it 
• Test 
It 
• With 
CI, 
you 
can 
forget 
about 
it 
Un)l 
it 
breaks
Refactor 
to 
make 
it 
Mockable 
• Original: 
<cfdirectory 
ac)on=”list” 
directory=”/myapp/path” 
name=”qResults”> 
• Refactored 
<cffunc)on 
name=”getFiles” 
output=”false” 
returnType=”query”> 
<cfargument 
name=”path”> 
<cfset 
var 
qResults 
= 
“”> 
<cfdirectory 
ac)on=”list” 
directory=”#arguments.path#” 
name=”qResults”> 
... 
Process 
Here 
... 
<cfreturn 
qResults> 
</cffunc)on>
Normal 
View 
of 
your 
Service
Mock/Test 
View 
of 
your 
Service
What 
do 
we 
Mock? 
• Excep)ons 
• Data 
• CFC 
and 
Objects 
• Methods 
in 
our 
CFCs 
• Proper)es 
in 
our 
CFCs
Mocking 
Framework 
• Introducing
What 
can 
MockBox 
do? 
• Mock 
Objects 
with 
or 
without 
implementa)ons 
• Mock 
methods 
& 
proper)es 
in 
any 
scope 
• Create 
Stub 
Objects 
-­‐> 
Non-­‐existent 
objects 
• Mock 
excep)ons 
• Mock 
arguments 
to 
results 
• Logging 
& 
Debugging 
• Verifica)on 
methods 
• State 
Machine 
Results
Sepng 
up 
MockBox 
• Standalone 
Version 
(FW/1, 
Fusebox, 
Model 
Glue, 
Home 
Brewed) 
mockBox 
= 
createObject(“component”,”mockBox.system.tes)ng.MockBox”).init(); 
• Running 
from 
inside 
ColdBox 
(outside 
of 
TestBox) 
mockBox 
= 
createObject(“component”,”coldbox.system.tes)ng.MockBox”).init();
Using 
MockBox 
• MockBox 
does 
its 
magic 
dynamically, 
adding 
/ 
decora)ng 
CFCs 
with 
necessary 
methods. 
• CreateMock() 
user 
= 
mockBox.createMock(“model.User”); 
• CreateEmptyMock() 
dao 
= 
mockBox.createEmptyMock(“model.UserDAO”); 
• PrepareMock() 
mockBox.prepareMock( 
service 
);
Using 
MockBox 
-­‐ 
Stubs 
• CreateStub() 
– Create 
a 
simple 
empty 
Stub 
– Pass 
an 
Implements 
to 
get 
a 
Mock 
Interface 
– Pass 
an 
Extends 
to 
get 
a 
Mock 
with 
Inheritance 
nonExistentService 
= 
mockBox.createStub(); 
mockInterface 
= 
mockBox.createStub(implements=”model.ICache”); 
mockInheritance 
= 
mockbox.createStub(extends=”model.SecurityService”);
Injected 
Methods
$() 
• Argument 
– method 
– returns 
– preserveReturnType 
– throwExcep)on 
– throwType 
– throwDetail 
– throwMessage 
– callLogging 
// Cascaded mocks 
mockUser.$(“isFound”,true).$(“isDirty”,true); 
// Mock Exception 
mockUser. 
$(method=”save”, 
throwsException=true, 
throwType=”IllegalStateException”, 
throwMessage=”Invalid User Data”); 
// Mock Return Objects 
mockRole = mockBox.createMock(“Role”); 
service.$ 
(method=”getRole”,returns=mockRole);
Using 
$() 
mockUser 
= 
mockBox.createEmptyMock(“model.User”).init(); 
userService 
= 
mockBox.createMock(“model.UserService”).init(); 
user 
= 
userService.$(“get”, 
mockUser); 
//Technique 
1 
– 
Constant 
Result 
user.$(“getName”, 
“Rose 
Tyler”); 
//Technique 
2 
– 
Rota)ng 
Results 
user.$(“getName”).$results(“Rose 
Tyler”, 
“Amelia 
Pond”, 
“River 
Song”);
Using 
$args() 
• Results 
based 
on 
the 
Arguments 
Passed 
• Must 
be 
chained 
via 
Results. 
// 
Call 
to 
Mock 
if( 
dao.getSepng(“userAudit”) 
){ 
startAudit( 
dao.getSepng(“auditTables”) 
); 
}; 
// 
Mocking 
Calls 
dao.$(“getSepng”).$args(“userAudit”).$results(true); 
dao.$(“getSepng”).$args(“auditTables”).$results(“user,order,
Using 
$args() 
• Arguments 
are 
smart 
like 
normal 
func)ons 
– Posi)onal 
Arguments 
saveUser(”Rose”,”Tyler”); 
– Named 
Arguments 
saveUser(fname=”Rose”,lname=”Tyler”); 
– Argument 
Collec)ons 
data 
= 
{ 
fname 
= 
“Rose”, 
lname 
= 
“Tyler” 
}; 
saveUser(argumentCollec)on=data);
$results() 
• Your 
results 
can 
be 
– Constant 
– Or 
Sequenced 
• Your 
results 
will 
loop 
over 
and 
over. 
• Argument 
Based 
Results 
can 
also 
be 
repe))ve 
in 
a 
sequence.
$property() 
• Mock 
any 
property 
on 
any 
scope 
• Great 
for 
sepngs 
and 
dependency 
injec)on 
mocking 
// 
Mock 
a 
sepng 
on 
the 
variables 
scope 
service.$property(“cacheAc)ve”,”variables”,true); 
// 
Mock 
a 
file 
u)lity 
object 
mockU)l 
= 
mockbox.createEmptyMock(“u)l.FileU)ls”); 
service.$property(“fileU)l”,”variables”, 
mockU)l); 
// 
Mock 
in 
the 
variables.instance 
scope 
path 
service.$property(“isDirty”,”instance”,true);
Verifica)on 
Methods 
* Verification methods return boolean so they can be asserted
Verifica)on 
Methods 
func)on 
testVerifyCallCount(){ 
test.$("displayData",queryNew('')); 
assertTrue( 
test.$never() 
); 
assertTrue( 
test.$never(“displayData”) 
); 
test.displayData(); 
assertFalse( 
test.$)mes(1,”displayData”) 
); 
assertFalse( 
test.$once(”displayData”) 
); 
test.displayData(); 
assertEquals(true, 
test.$verifyCallCount(2)); 
}
Verifica)on 
Methods 
func)on 
testMockMethodCallCount(){ 
test.$("displayData",queryNew('')); 
test.$("getLuis",1); 
assertEquals(0, 
test.$count("displayData") 
); 
assertEquals(-­‐1, 
test.$count("displayData2") 
); 
}
Lets 
look 
at 
a 
Demo 
h6p://justmockit.local.com 
Code 
available 
at: 
h6ps://github.com/gpickin/justmockitdemo
The 
End 
– 
Thank 
you 
• Thanks 
everyone 
for 
making 
it 
this 
far 
• All 
of 
the 
materials 
will 
be 
on 
my 
ITB 
presenta)on 
Site: 
h6p://www.gpickin.com/itb2014/ 
• Hit 
me 
up 
on 
twi6er 
@gpickin 
• Read 
more 
on 
my 
blog: 
h6p://gpickin.com 
• Check 
out 
my 
CFO 
Session 
Thursday, 
15th 
11:30am 
– 
12:30am 
on 
Lakes 
Ballroom 
C

More Related Content

PDF
Unit Testing JavaScript Applications
PDF
Hotfixing iOS apps with Javascript
PPTX
Zero to Testing in JavaScript
PDF
Selenium bootcamp slides
PDF
Unit-testing and E2E testing in JS
PPTX
Java script unit testing
PPTX
MidwestJS Zero to Testing
PPT
Google mock for dummies
Unit Testing JavaScript Applications
Hotfixing iOS apps with Javascript
Zero to Testing in JavaScript
Selenium bootcamp slides
Unit-testing and E2E testing in JS
Java script unit testing
MidwestJS Zero to Testing
Google mock for dummies

What's hot (20)

PDF
Functions for nothing, and your tests for free
PDF
Testing swagger contracts without contract based testing
PDF
Das Frontend richtig Testen – mit Jest @Developer Week 2018
PDF
RSpec on Rails Tutorial
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
PPTX
Unit testing presentation
PDF
Javascript Test Automation Workshop (21.08.2014)
PPTX
Unit testing JavaScript: Jasmine & karma intro
ODP
Getting to Grips with SilverStripe Testing
PPTX
Maintainable JavaScript 2012
PDF
jQuery Proven Performance Tips & Tricks
PPTX
Extending burp with python
PDF
Introduction to Protractor
PPTX
Testing ASP.NET - Progressive.NET
PPTX
Cusomizing Burp Suite - Getting the Most out of Burp Extensions
PDF
AOP in Python API design
KEY
New techniques in sql obfuscation, from DEFCON 20
PPTX
Testing React Applications
PDF
How Testability Inspires AngularJS Design / Ran Mizrahi
PDF
SilverStripe CMS JavaScript Refactoring
Functions for nothing, and your tests for free
Testing swagger contracts without contract based testing
Das Frontend richtig Testen – mit Jest @Developer Week 2018
RSpec on Rails Tutorial
2011 NetUG HH: ASP.NET MVC & HTML 5
Unit testing presentation
Javascript Test Automation Workshop (21.08.2014)
Unit testing JavaScript: Jasmine & karma intro
Getting to Grips with SilverStripe Testing
Maintainable JavaScript 2012
jQuery Proven Performance Tips & Tricks
Extending burp with python
Introduction to Protractor
Testing ASP.NET - Progressive.NET
Cusomizing Burp Suite - Getting the Most out of Burp Extensions
AOP in Python API design
New techniques in sql obfuscation, from DEFCON 20
Testing React Applications
How Testability Inspires AngularJS Design / Ran Mizrahi
SilverStripe CMS JavaScript Refactoring
Ad

Viewers also liked (20)

PPTX
Q3 institutions
PDF
Intro to RESTFul API's with ColdBox MVC
PDF
ITB2016 Web Applications can control the world
PPT
Breaking wifi-faster
PDF
0 6 método de los desplazamientos
PPTX
Creating a Double Page Spread Document
DOCX
Planning booklet
PPTX
Gentech
PDF
ITB2016 - ContentBox Modular CMS
PDF
Into The Box 2015 Keynote
PPTX
PPTX
Star wars return of the jedi
PPTX
Tugas trigger
PPT
forces
PPT
forces
PDF
ITB2016 - ForgeBox 2 Package Management
PPTX
მუქარა
PPTX
PPTX
과제 3
PPT
Саші Хортів
Q3 institutions
Intro to RESTFul API's with ColdBox MVC
ITB2016 Web Applications can control the world
Breaking wifi-faster
0 6 método de los desplazamientos
Creating a Double Page Spread Document
Planning booklet
Gentech
ITB2016 - ContentBox Modular CMS
Into The Box 2015 Keynote
Star wars return of the jedi
Tugas trigger
forces
forces
ITB2016 - ForgeBox 2 Package Management
მუქარა
과제 3
Саші Хортів
Ad

Similar to CBDW2014 - MockBox, get ready to mock your socks off! (20)

PDF
Just Mock It - Mocks and Stubs
PPTX
Testing Ext JS and Sencha Touch
PDF
Building XWiki
PDF
Getting your mobile test automation process in place - using Cucumber and Cal...
PPT
Google mock for dummies
PPT
Google mock for dummies
PPT
Google mock for dummies
PPT
Google mock for dummies
PPT
Google mock for dummies
PPT
Google mock for dummies
PDF
Escaping Test Hell - ACCU 2014
PDF
Devday2016 real unittestingwithmockframework-phatvu
PDF
The Many Ways to Test Your React App
PDF
Breaking Dependencies to Allow Unit Testing
PDF
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
PPTX
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
PDF
Selenium Tips & Tricks - StarWest 2015
PDF
Jest: Frontend Testing richtig gemacht @WebworkerNRW
PDF
Awesome html with ujs, jQuery and coffeescript
PDF
The Cowardly Test-o-Phobe's Guide To Testing
Just Mock It - Mocks and Stubs
Testing Ext JS and Sencha Touch
Building XWiki
Getting your mobile test automation process in place - using Cucumber and Cal...
Google mock for dummies
Google mock for dummies
Google mock for dummies
Google mock for dummies
Google mock for dummies
Google mock for dummies
Escaping Test Hell - ACCU 2014
Devday2016 real unittestingwithmockframework-phatvu
The Many Ways to Test Your React App
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Selenium Tips & Tricks - StarWest 2015
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Awesome html with ujs, jQuery and coffeescript
The Cowardly Test-o-Phobe's Guide To Testing

More from Ortus Solutions, Corp (20)

PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
PDF
June Webinar: BoxLang-Dynamic-AWS-Lambda
PDF
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
PDF
What's-New-with-BoxLang-Brad Wood.pptx.pdf
PDF
Getting Started with BoxLang - CFCamp 2025.pdf
PDF
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
PDF
What's New with BoxLang Led by Brad Wood.pdf
PDF
Vector Databases and the BoxLangCFML Developer.pdf
PDF
Using cbSSO in a ColdBox App Led by Jacob Beers.pdf
PDF
Use JSON to Slash Your Database Performance.pdf
PDF
Portable CI wGitLab and Github led by Gavin Pickin.pdf
PDF
Tame the Mesh An intro to cross-platform tracing and troubleshooting.pdf
PDF
Supercharging CommandBox with Let's Encrypt.pdf
PDF
Spice up your site with cool animations using GSAP..pdf
PDF
Passkeys and cbSecurity Led by Eric Peterson.pdf
PDF
Legacy Code Nightmares , Hellscapes, and Lessons Learned.pdf
PDF
Integrating the OpenAI API in Your Coldfusion Apps.pdf
PDF
Hidden Gems in FusionReactor for BoxLang, ACF, and Lucee Users.pdf
PDF
Geting-started with BoxLang Led By Raymon Camden.pdf
PDF
From Zero to CRUD with ORM - Led by Annette Liskey.pdf
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
June Webinar: BoxLang-Dynamic-AWS-Lambda
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
What's-New-with-BoxLang-Brad Wood.pptx.pdf
Getting Started with BoxLang - CFCamp 2025.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
What's New with BoxLang Led by Brad Wood.pdf
Vector Databases and the BoxLangCFML Developer.pdf
Using cbSSO in a ColdBox App Led by Jacob Beers.pdf
Use JSON to Slash Your Database Performance.pdf
Portable CI wGitLab and Github led by Gavin Pickin.pdf
Tame the Mesh An intro to cross-platform tracing and troubleshooting.pdf
Supercharging CommandBox with Let's Encrypt.pdf
Spice up your site with cool animations using GSAP..pdf
Passkeys and cbSecurity Led by Eric Peterson.pdf
Legacy Code Nightmares , Hellscapes, and Lessons Learned.pdf
Integrating the OpenAI API in Your Coldfusion Apps.pdf
Hidden Gems in FusionReactor for BoxLang, ACF, and Lucee Users.pdf
Geting-started with BoxLang Led By Raymon Camden.pdf
From Zero to CRUD with ORM - Led by Annette Liskey.pdf

Recently uploaded (20)

PDF
Modernizing your data center with Dell and AMD
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPT
Teaching material agriculture food technology
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Modernizing your data center with Dell and AMD
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Teaching material agriculture food technology
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
A Presentation on Artificial Intelligence
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Understanding_Digital_Forensics_Presentation.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Dropbox Q2 2025 Financial Results & Investor Presentation
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?

CBDW2014 - MockBox, get ready to mock your socks off!

  • 1. Just Mock It Mocks and Stubs Presented by Gavin Pickin Slides: http://gpickin.com/itb2014/ Website: http://gpickin.com Twitter: @gpickin
  • 2. Introduc)on • Follow along with resources from h6p://gpickin.com/itb2014/ • If you want to find out more about me, my website has more than enough informa)on
  • 3. 20 Second Agenda • Unit Tes)ng -­‐ Recap • What is Mocking • What is a Mock / Stub • Why Mock • Let’s look at some Mocking
  • 4. Unit Tes)ng “unit tes)ng is a soOware verifica)on and valida)on method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an applica)on” -­‐ wikipedia
  • 5. Unit Tes)ng • Can improve code quality -­‐> quick error discovery • Code confidence via immediate verifica)on • Can expose high coupling • Will encourage refactoring to produce > testable code • Remember: Tes)ng is all about behavior and expecta)ons
  • 7. Bugs Hurt • Bugs hurt – the later in the process, the harder to fix. • Test Early and OOen – Find them before they rot your founda)on • Testable Code is Maintainable Code
  • 10. Important Tests • Unit Tes)ng – Test behavior of individual objects • Integra)on Tes)ng – Test En)re Applica)on from Top Down • UI verifica)on tes)ng – Verifica)on via HTML/Visual elements
  • 11. Important Tes)ng Tools • TestBox (Run BDD and MXUnit style) • IDE -­‐ CF Builder / Eclipse • Mocking Framework • ANT • Jenkins, Bamboo, Teamcity, other Cis • Selenium • Jmeter or Webstress Tool, Apache AB
  • 12. What is Mocking? According to Merriam Webster • to laugh at or make fun of (someone or something) especially by copying an ac)on or a way of behaving or speaking • to imitate (as a mannerism) closely
  • 13. What is Mocking? "A mock object is an object that takes the place of a ‘real’ object in such a way that makes tes)ng easier and more meaningful, or in some cases, possible at all" by Sco6 Bain -­‐ Emergent Design
  • 14. Mocks
  • 15. Mocks
  • 16. Mocks
  • 17. Mocks
  • 18. Stub Object • A stub is an empty container, that represents an Object. • This can be useful for represen)ng CFCs and Objects that haven’t been wri6en yet.
  • 19. Why use Mocking • Isolate your SUT -­‐> SoOware Under Test • To build against interfaces & contracts • Building against missing integra)on pieces • To control data and expecta)ons • Mock components whose behavior is undesirable or hard to control
  • 20. Why Mock? • How do you test when helper components that are not built yet? • How do you do controlled excep)ons? • How do you test & control external API calls? • How do you control results from ColdFusion tags or func)ons? • How do you control network connec)ons? Do you pull the network plug?
  • 21. Why Mock? How do you test code like this? <cfdirectory ac)on=”list” directory=”#arguments.path#” name=”qResults”> <ck6p url=”#arguments.urlPath#” results=”qResults”> <cfmail to=”#to#” from=”#from#” subject=”#subject#”>#content#</cfmail> <cfquery /> func)on init(){ var helper = new Helper(); } private func)on getData(){ return data; }
  • 22. The COLD hard truth – It can Hurt • Tes)ng some code is hard, or almost impossible. • Refactor it • Mock it • Test It • With CI, you can forget about it Un)l it breaks
  • 23. Refactor to make it Mockable • Original: <cfdirectory ac)on=”list” directory=”/myapp/path” name=”qResults”> • Refactored <cffunc)on name=”getFiles” output=”false” returnType=”query”> <cfargument name=”path”> <cfset var qResults = “”> <cfdirectory ac)on=”list” directory=”#arguments.path#” name=”qResults”> ... Process Here ... <cfreturn qResults> </cffunc)on>
  • 24. Normal View of your Service
  • 25. Mock/Test View of your Service
  • 26. What do we Mock? • Excep)ons • Data • CFC and Objects • Methods in our CFCs • Proper)es in our CFCs
  • 27. Mocking Framework • Introducing
  • 28. What can MockBox do? • Mock Objects with or without implementa)ons • Mock methods & proper)es in any scope • Create Stub Objects -­‐> Non-­‐existent objects • Mock excep)ons • Mock arguments to results • Logging & Debugging • Verifica)on methods • State Machine Results
  • 29. Sepng up MockBox • Standalone Version (FW/1, Fusebox, Model Glue, Home Brewed) mockBox = createObject(“component”,”mockBox.system.tes)ng.MockBox”).init(); • Running from inside ColdBox (outside of TestBox) mockBox = createObject(“component”,”coldbox.system.tes)ng.MockBox”).init();
  • 30. Using MockBox • MockBox does its magic dynamically, adding / decora)ng CFCs with necessary methods. • CreateMock() user = mockBox.createMock(“model.User”); • CreateEmptyMock() dao = mockBox.createEmptyMock(“model.UserDAO”); • PrepareMock() mockBox.prepareMock( service );
  • 31. Using MockBox -­‐ Stubs • CreateStub() – Create a simple empty Stub – Pass an Implements to get a Mock Interface – Pass an Extends to get a Mock with Inheritance nonExistentService = mockBox.createStub(); mockInterface = mockBox.createStub(implements=”model.ICache”); mockInheritance = mockbox.createStub(extends=”model.SecurityService”);
  • 33. $() • Argument – method – returns – preserveReturnType – throwExcep)on – throwType – throwDetail – throwMessage – callLogging // Cascaded mocks mockUser.$(“isFound”,true).$(“isDirty”,true); // Mock Exception mockUser. $(method=”save”, throwsException=true, throwType=”IllegalStateException”, throwMessage=”Invalid User Data”); // Mock Return Objects mockRole = mockBox.createMock(“Role”); service.$ (method=”getRole”,returns=mockRole);
  • 34. Using $() mockUser = mockBox.createEmptyMock(“model.User”).init(); userService = mockBox.createMock(“model.UserService”).init(); user = userService.$(“get”, mockUser); //Technique 1 – Constant Result user.$(“getName”, “Rose Tyler”); //Technique 2 – Rota)ng Results user.$(“getName”).$results(“Rose Tyler”, “Amelia Pond”, “River Song”);
  • 35. Using $args() • Results based on the Arguments Passed • Must be chained via Results. // Call to Mock if( dao.getSepng(“userAudit”) ){ startAudit( dao.getSepng(“auditTables”) ); }; // Mocking Calls dao.$(“getSepng”).$args(“userAudit”).$results(true); dao.$(“getSepng”).$args(“auditTables”).$results(“user,order,
  • 36. Using $args() • Arguments are smart like normal func)ons – Posi)onal Arguments saveUser(”Rose”,”Tyler”); – Named Arguments saveUser(fname=”Rose”,lname=”Tyler”); – Argument Collec)ons data = { fname = “Rose”, lname = “Tyler” }; saveUser(argumentCollec)on=data);
  • 37. $results() • Your results can be – Constant – Or Sequenced • Your results will loop over and over. • Argument Based Results can also be repe))ve in a sequence.
  • 38. $property() • Mock any property on any scope • Great for sepngs and dependency injec)on mocking // Mock a sepng on the variables scope service.$property(“cacheAc)ve”,”variables”,true); // Mock a file u)lity object mockU)l = mockbox.createEmptyMock(“u)l.FileU)ls”); service.$property(“fileU)l”,”variables”, mockU)l); // Mock in the variables.instance scope path service.$property(“isDirty”,”instance”,true);
  • 39. Verifica)on Methods * Verification methods return boolean so they can be asserted
  • 40. Verifica)on Methods func)on testVerifyCallCount(){ test.$("displayData",queryNew('')); assertTrue( test.$never() ); assertTrue( test.$never(“displayData”) ); test.displayData(); assertFalse( test.$)mes(1,”displayData”) ); assertFalse( test.$once(”displayData”) ); test.displayData(); assertEquals(true, test.$verifyCallCount(2)); }
  • 41. Verifica)on Methods func)on testMockMethodCallCount(){ test.$("displayData",queryNew('')); test.$("getLuis",1); assertEquals(0, test.$count("displayData") ); assertEquals(-­‐1, test.$count("displayData2") ); }
  • 42. Lets look at a Demo h6p://justmockit.local.com Code available at: h6ps://github.com/gpickin/justmockitdemo
  • 43. The End – Thank you • Thanks everyone for making it this far • All of the materials will be on my ITB presenta)on Site: h6p://www.gpickin.com/itb2014/ • Hit me up on twi6er @gpickin • Read more on my blog: h6p://gpickin.com • Check out my CFO Session Thursday, 15th 11:30am – 12:30am on Lakes Ballroom C