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

Contenu connexe

Tendances

Tendances (20)

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

En vedette

Q3 institutions
Q3 institutionsQ3 institutions
Q3 institutions
LucyAnne97
 
Creating a Double Page Spread Document
Creating a Double Page Spread DocumentCreating a Double Page Spread Document
Creating a Double Page Spread Document
laurenjewell
 
Star wars return of the jedi
Star wars   return of the jediStar wars   return of the jedi
Star wars return of the jedi
LucyAnne97
 

En vedette (20)

Q3 institutions
Q3 institutionsQ3 institutions
Q3 institutions
 
Intro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVCIntro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVC
 
ITB2016 Web Applications can control the world
ITB2016 Web Applications can control the worldITB2016 Web Applications can control the world
ITB2016 Web Applications can control the world
 
Breaking wifi-faster
Breaking wifi-fasterBreaking wifi-faster
Breaking wifi-faster
 
0 6 método de los desplazamientos
0 6 método de los desplazamientos0 6 método de los desplazamientos
0 6 método de los desplazamientos
 
Creating a Double Page Spread Document
Creating a Double Page Spread DocumentCreating a Double Page Spread Document
Creating a Double Page Spread Document
 
Planning booklet
Planning bookletPlanning booklet
Planning booklet
 
Gentech
GentechGentech
Gentech
 
ITB2016 - ContentBox Modular CMS
ITB2016 - ContentBox Modular CMSITB2016 - ContentBox Modular CMS
ITB2016 - ContentBox Modular CMS
 
Into The Box 2015 Keynote
Into The Box 2015 KeynoteInto The Box 2015 Keynote
Into The Box 2015 Keynote
 
Welcome
WelcomeWelcome
Welcome
 
Star wars return of the jedi
Star wars   return of the jediStar wars   return of the jedi
Star wars return of the jedi
 
Tugas trigger
Tugas triggerTugas trigger
Tugas trigger
 
forces
forcesforces
forces
 
forces
forcesforces
forces
 
ITB2016 - ForgeBox 2 Package Management
ITB2016 - ForgeBox 2 Package ManagementITB2016 - ForgeBox 2 Package Management
ITB2016 - ForgeBox 2 Package Management
 
მუქარა
მუქარამუქარა
მუქარა
 
Pro forma
Pro formaPro forma
Pro forma
 
과제 3
과제 3과제 3
과제 3
 
Саші Хортів
Саші ХортівСаші Хортів
Саші Хортів
 

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

Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Tony Nguyen
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Young Alista
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Luis Goldster
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Fraboni Ec
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
James Wong
 

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

Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 
Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...Getting your mobile test automation process in place - using Cucumber and Cal...
Getting your mobile test automation process in place - using Cucumber and Cal...
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Escaping Test Hell - ACCU 2014
Escaping Test Hell - ACCU 2014Escaping Test Hell - ACCU 2014
Escaping Test Hell - ACCU 2014
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
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
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 
Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 

Plus de Ortus Solutions, Corp

Plus de Ortus Solutions, Corp (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Ortus Government.pdf
Ortus Government.pdfOrtus Government.pdf
Ortus Government.pdf
 
Luis Majano The Battlefield ORM
Luis Majano The Battlefield ORMLuis Majano The Battlefield ORM
Luis Majano The Battlefield ORM
 
Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI
 
Secure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusionSecure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusion
 
Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023
 
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdfITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
 
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdfITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
 
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdfITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
 
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdfITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
 
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdfITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
 
ITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdfITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdf
 
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdfITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
 
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdfITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
 
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdfITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
 
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdfITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
 
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdfITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
 
ITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdfITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdf
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
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
vu2urc
 

Dernier (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave 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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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