SlideShare uma empresa Scribd logo
1 de 38
Integration testing vs Unit testing
Using Mocks and stubs
Reading:
The Art of Unit Testing,
Ch. 1, 3, 4-5 (Osherove)
Code Complete,
Ch. 29 (McConnell)
slides based on material by Marty Stepp
http://www.cs.washington.edu/403/
Agenda
• LogAnalyzer: a “test” case
• Unit vs Integration testing
• Design Principles for Testable Code
• Stubs vs Mocks
• Demo LogAnalyzer in Java
LogAnalyzer
Unit Tests vs. Other Kinds of Tests
• Performed on the class (“unit”) level
• Each unit is tested in isolation
• Automatic
• Create class object, call methods, check results
Unit Testing Context
Class Under Test May Call Many Others
ClassUnderTest
ClassA
Dependency3Dependency1 Dependency2
ClassB ClassC ClassD ClassE
F G H I J K L M N
Database Network File System Printer Nuclear Rocket
Launcher
Design Principles for Testable Code
Beware hard coded dependencies
double GetPrice(int productId)
{
using (SqlConnection conn = new SqlConnection(
Config.ProductsDbConnectionString))
{
conn.Open();
double price = ReadPriceFromDb(conn, productId);
if (DateTime.Now.DayOfWeek==DayOfWeek.Wednesday)
{
// apply Wednesday discount
price *= 0.95;
}
return price;
}
}
Replaceable dependencies
• All dependencies are explicitly passed in constructor/method
parameters or properties
• If it is not passed, it should not be used
• Must avoid hidden dependencies
• Static methods (like DateTime.Now)
• Singletons
• “new”
• The only place where things are “new’ed” is a factory class or
a factory method, which is not unit tested
Dependency Inversion vs Dependency Injection
• A principle, one of the SOLID principles
• High-level modules should not depend
upon low-level modules. Both should
depend upon abstractions.
• Abstractions should not depend upon
details. Details should depend upon
abstractions.
• A technique offered by frameworks that
use an IoC-container but can also be
applied manually. Push mechanism (Tell,
Don’t Ask or the Hollywood Principe:
Don’t Call us, We call You), you can also
use a pull mechanism (Ask, Don’t Tell),
e.g. a ServiceLocator or Plug-In.
LogAnalyzer: Where do we put the
interfaces?
Not compliant to DIP
Compliant with DIP. Any other options?
Multiple client depend on a component’s interface
Unit vs Integration Tests
Unit vs Integration Tests
• Tests that involve many classes are integration tests
• In other words: test reading from a database is not a unit test
• Integration tests verify the wiring between classes
• Unit tests verify classes in isolation
• We need both: neither is a replacement of the other
Integration
integration: Combining 2 or more software units
– often a subset of the overall project (!= system testing)
Why do software engineers care about integration?
– new problems will inevitably surface
• many systems now together that have never been before
– if done poorly, all problems present themselves at once
• hard to diagnose, debug, fix
– cascade of interdependencies
• cannot find and solve problems one-at-a-time
Phased integration
phased ("big-bang") integration:
– design, code, test, debug each class/unit/subsystem separately
– combine them all
– pray
Incremental integration
incremental integration:
– develop a functional "skeleton" system
– design, code, test, debug a small new piece
– integrate this piece with the skeleton
• test/debug it before adding any other pieces
Benefits of incremental
Benefits:
– Errors easier to isolate, find, fix
• reduces developer bug-fixing load
– System is always in a (relatively) working state
• good for customer relations, developer morale
Drawbacks:
– May need to create "stub" versions of some features that have
not yet been integrated
Top-down integration
top-down integration:
Start with outer UI layers and work inward
– must write (lots of) stub lower layers for UI to interact with
– allows postponing tough design/debugging decisions (bad?)
Bottom-up integration
bottom-up integration:
Start with low-level data/logic layers and work outward
– must write test drivers to run these layers
– won't discover high-level / UI design flaws until late
Daily builds
daily build: Compile working executable on a daily basis
– allows you to test the quality of your integration so far
– helps morale; product "works every day"; visible progress
– best done automated or through an easy script
– quickly catches/exposes any bug that breaks the build
smoke test: A quick set of tests run on the daily build.
– NOT exhaustive; just sees whether code "smokes" (breaks)
– used (along with compilation) to make sure daily build runs
continuous integration:
Adding new units immediately as they are written.
Integration testing
integration testing: Verifying software quality by testing two or more
dependent software modules as a group.
challenges:
– Combined units can fail
in more places and in more
complicated ways.
– How to test a partial system
where not all parts exist?
– How to "rig" the behavior of
unit A so as to produce a
given behavior from unit B?
Test Doubles
Test Doubles (Gerard, Fowler)
https://martinfowler.com/bliki/TestDouble.html
• Dummy objects are passed around but never actually used. Usually
they are just used to fill parameter lists.
• Fake objects actually have working implementations, but usually take
some shortcut which makes them not suitable for production
(an InMemoryTestDatabase is a good example).
• Stubs provide canned answers to calls made during the test, usually
not responding at all to anything outside what's programmed in for the
test.
• Spies are stubs that also record some information based on how they
were called. One form of this might be an email service that records
how many messages it was sent.
• Mocks are pre-programmed with expectations which form a
specification of the calls they are expected to receive. They can throw
an exception if they receive a call they don't expect and are checked
during verification to ensure they got all the calls they were expecting.
Stubs
stub: A controllable replacement for an existing software unit to
which your code under test has a dependency.
– useful for simulating difficult-to-control elements:
• network / internet
• database
• time/date-sensitive code
• files
• threads
• memory
– also useful when dealing with brittle legacy code/systems
Create a stub, step 1
Identify the external dependency.
– This is either a resource or a class/object.
– If it isn't an object, wrap it up into one.
• (Suppose that Class A depends on troublesome Class B.)
Create a stub, step 2
Extract the core functionality of the object into an interface.
– Create an InterfaceB based on B
– Change all of A's code to work with type InterfaceB, not B
Create a stub, step 3
Write a second "stub" class that also implements the interface,
but returns pre-determined fake data.
– Now A's dependency on B is dodged and can be tested easily.
– Can focus on how well A integrates with B's external behavior.
Injecting a stub
seams: Places to inject the stub so Class A will talk to it.
– at construction (not ideal)
A aardvark = new A(new StubB());
– through a getter/setter method (better)
A apple = new A(...);
aardvark.setResource(new StubB());
– just before usage, as a parameter (also better)
aardvark.methodThatUsesB(new StubB());
• You should not have to change A's code everywhere (beyond using your interface) in
order to use your Stub B. (a "testable design")
"Mock" objects
mock object: A fake object that decides whether a unit test has
passed or failed by watching interactions between objects.
– useful for interaction testing (as opposed to state testing)
Stubs vs. mocks
– A stub gives out data that goes to
the object/class under test.
– The unit test directly asserts against
class under test, to make sure it gives
the right result when fed this data.
– A mock waits to be called by
the class under test (A).
• Maybe it has several methods
it expects that A should call.
– It makes sure that it was contacted
in exactly the right way.
• If A interacts with B the way it should, the test passes.
Mock object frameworks
Stubs are often best created by hand/IDE.
Mocks are tedious to create manually.
Mock object frameworks help with the process.
– android-mock, EasyMock, jMock, Mockito (Java)
– FlexMock / Mocha (Ruby)
– SimpleTest / PHPUnit (PHP)
– ...
Frameworks provide the following:
– auto-generation of mock objects that implement a given interface
– logging of what calls are performed on the mock objects
– methods/primitives for declaring and asserting your expectations
Using stubs/mocks together
Suppose a log analyzer reads from a web service.
If the web fails to log an error, the analyzer must send email.
– How to test to ensure that this behavior is occurring?
Set up a stub for the web service that intentionally fails.
Set up a mock for the email service that checks to see whether
the analyzer contacts it to send an email message.
Initial Design - Sequence Diagram
Initial Design - Package/Class Diagram

Mais conteúdo relacionado

Mais procurados

Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminardunglinh111
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NETPuneet Ghanshani
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonSeb Rose
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven DevelopmentFerdous Mahmud Shaon
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesTriTAUG
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat VU
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentShawn Jones
 
Unit testing using Mock objects and dependency injection
Unit testing using Mock objects and dependency injectionUnit testing using Mock objects and dependency injection
Unit testing using Mock objects and dependency injectionYn Reddy
 
Automated Unit Testing and TDD
Automated Unit Testing and TDDAutomated Unit Testing and TDD
Automated Unit Testing and TDDGreg Sohl
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingSahar Nofal
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsJess Chadwick
 
Common Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSCommon Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSDerek Lee Boire
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentDhaval Dalal
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Grig Gheorghiu
 

Mais procurados (20)

Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Testing 101
Testing 101Testing 101
Testing 101
 
Unit tests benefits
Unit tests benefitsUnit tests benefits
Unit tests benefits
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking Skeleton
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and Challenges
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 
Unit testing using Mock objects and dependency injection
Unit testing using Mock objects and dependency injectionUnit testing using Mock objects and dependency injection
Unit testing using Mock objects and dependency injection
 
Automated Unit Testing and TDD
Automated Unit Testing and TDDAutomated Unit Testing and TDD
Automated Unit Testing and TDD
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere Mortals
 
Common Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSCommon Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOS
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Mocking
MockingMocking
Mocking
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009
 

Semelhante a Integration and Unit Testing in Java using Test Doubles like mocks and stubs

Testing & should i do it
Testing & should i do itTesting & should i do it
Testing & should i do itMartin Sykora
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testingmarkstory
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeIsaac Murchie
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaErick M'bwana
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 
unittesting-190620114546 (1).pptx document
unittesting-190620114546 (1).pptx documentunittesting-190620114546 (1).pptx document
unittesting-190620114546 (1).pptx documentAkshayaM79
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGegoodwintx
 
Software testing: an introduction - 2017
Software testing: an introduction - 2017Software testing: an introduction - 2017
Software testing: an introduction - 2017XavierDevroey
 

Semelhante a Integration and Unit Testing in Java using Test Doubles like mocks and stubs (20)

Integration testing
Integration testingIntegration testing
Integration testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Testing & should i do it
Testing & should i do itTesting & should i do it
Testing & should i do it
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Gallio Crafting A Toolchain
Gallio Crafting A ToolchainGallio Crafting A Toolchain
Gallio Crafting A Toolchain
 
Presentation
PresentationPresentation
Presentation
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testing
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your Code
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Unit testing
Unit testingUnit testing
Unit testing
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
unittesting-190620114546 (1).pptx document
unittesting-190620114546 (1).pptx documentunittesting-190620114546 (1).pptx document
unittesting-190620114546 (1).pptx document
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
 
Software testing: an introduction - 2017
Software testing: an introduction - 2017Software testing: an introduction - 2017
Software testing: an introduction - 2017
 

Mais de Rody Middelkoop

An agile mindset in education
An agile mindset in education An agile mindset in education
An agile mindset in education Rody Middelkoop
 
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpak
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpakEduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpak
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpakRody Middelkoop
 
Pecha Kucha eduScrum Agile Education
Pecha Kucha eduScrum Agile EducationPecha Kucha eduScrum Agile Education
Pecha Kucha eduScrum Agile EducationRody Middelkoop
 
Softwarekwaliteit in een ontwikkelstraat
Softwarekwaliteit in een ontwikkelstraatSoftwarekwaliteit in een ontwikkelstraat
Softwarekwaliteit in een ontwikkelstraatRody Middelkoop
 
JavaScript on the server - Node.js
JavaScript on the server - Node.jsJavaScript on the server - Node.js
JavaScript on the server - Node.jsRody Middelkoop
 
DDOA = Software Craftmanship
DDOA = Software CraftmanshipDDOA = Software Craftmanship
DDOA = Software CraftmanshipRody Middelkoop
 
Back to the Future: Onderwijs van 1991 tot 2031
Back to the Future: Onderwijs van 1991 tot 2031Back to the Future: Onderwijs van 1991 tot 2031
Back to the Future: Onderwijs van 1991 tot 2031Rody Middelkoop
 
Scrum implemented in an educational context
Scrum implemented in an educational contextScrum implemented in an educational context
Scrum implemented in an educational contextRody Middelkoop
 
Pragmatic Model Driven Development In Java Using Smart Use Cases
Pragmatic Model Driven Development In Java Using Smart Use CasesPragmatic Model Driven Development In Java Using Smart Use Cases
Pragmatic Model Driven Development In Java Using Smart Use CasesRody Middelkoop
 
Scrum in informaticaonderwijs
Scrum in informaticaonderwijsScrum in informaticaonderwijs
Scrum in informaticaonderwijsRody Middelkoop
 
Saas: Software AND Service
Saas: Software AND ServiceSaas: Software AND Service
Saas: Software AND ServiceRody Middelkoop
 
Service Analysis And Design
Service Analysis And DesignService Analysis And Design
Service Analysis And DesignRody Middelkoop
 
Contract First Modeling Services Using Uml
Contract First Modeling Services Using UmlContract First Modeling Services Using Uml
Contract First Modeling Services Using UmlRody Middelkoop
 

Mais de Rody Middelkoop (18)

An agile mindset in education
An agile mindset in education An agile mindset in education
An agile mindset in education
 
Themalunch scrum
Themalunch scrumThemalunch scrum
Themalunch scrum
 
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpak
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpakEduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpak
Eduscrum presentatie Scrum event 2016: Scrum als onderwijsaanpak
 
Pecha Kucha eduScrum Agile Education
Pecha Kucha eduScrum Agile EducationPecha Kucha eduScrum Agile Education
Pecha Kucha eduScrum Agile Education
 
Software Process Models
Software Process ModelsSoftware Process Models
Software Process Models
 
Softwarekwaliteit in een ontwikkelstraat
Softwarekwaliteit in een ontwikkelstraatSoftwarekwaliteit in een ontwikkelstraat
Softwarekwaliteit in een ontwikkelstraat
 
JavaScript on the server - Node.js
JavaScript on the server - Node.jsJavaScript on the server - Node.js
JavaScript on the server - Node.js
 
DDOA = Software Craftmanship
DDOA = Software CraftmanshipDDOA = Software Craftmanship
DDOA = Software Craftmanship
 
Back to the Future: Onderwijs van 1991 tot 2031
Back to the Future: Onderwijs van 1991 tot 2031Back to the Future: Onderwijs van 1991 tot 2031
Back to the Future: Onderwijs van 1991 tot 2031
 
Scrum implemented in an educational context
Scrum implemented in an educational contextScrum implemented in an educational context
Scrum implemented in an educational context
 
Ajax And JSON
Ajax And JSONAjax And JSON
Ajax And JSON
 
OO JavaScript
OO JavaScriptOO JavaScript
OO JavaScript
 
Pragmatic Model Driven Development In Java Using Smart Use Cases
Pragmatic Model Driven Development In Java Using Smart Use CasesPragmatic Model Driven Development In Java Using Smart Use Cases
Pragmatic Model Driven Development In Java Using Smart Use Cases
 
Scrum in informaticaonderwijs
Scrum in informaticaonderwijsScrum in informaticaonderwijs
Scrum in informaticaonderwijs
 
Saas: Software AND Service
Saas: Software AND ServiceSaas: Software AND Service
Saas: Software AND Service
 
Service Analysis And Design
Service Analysis And DesignService Analysis And Design
Service Analysis And Design
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Contract First Modeling Services Using Uml
Contract First Modeling Services Using UmlContract First Modeling Services Using Uml
Contract First Modeling Services Using Uml
 

Último

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Último (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

Integration and Unit Testing in Java using Test Doubles like mocks and stubs

  • 1. Integration testing vs Unit testing Using Mocks and stubs Reading: The Art of Unit Testing, Ch. 1, 3, 4-5 (Osherove) Code Complete, Ch. 29 (McConnell) slides based on material by Marty Stepp http://www.cs.washington.edu/403/
  • 2. Agenda • LogAnalyzer: a “test” case • Unit vs Integration testing • Design Principles for Testable Code • Stubs vs Mocks • Demo LogAnalyzer in Java
  • 4. Unit Tests vs. Other Kinds of Tests • Performed on the class (“unit”) level • Each unit is tested in isolation • Automatic • Create class object, call methods, check results
  • 6. Class Under Test May Call Many Others ClassUnderTest ClassA Dependency3Dependency1 Dependency2 ClassB ClassC ClassD ClassE F G H I J K L M N Database Network File System Printer Nuclear Rocket Launcher
  • 7. Design Principles for Testable Code
  • 8. Beware hard coded dependencies double GetPrice(int productId) { using (SqlConnection conn = new SqlConnection( Config.ProductsDbConnectionString)) { conn.Open(); double price = ReadPriceFromDb(conn, productId); if (DateTime.Now.DayOfWeek==DayOfWeek.Wednesday) { // apply Wednesday discount price *= 0.95; } return price; } }
  • 9. Replaceable dependencies • All dependencies are explicitly passed in constructor/method parameters or properties • If it is not passed, it should not be used • Must avoid hidden dependencies • Static methods (like DateTime.Now) • Singletons • “new” • The only place where things are “new’ed” is a factory class or a factory method, which is not unit tested
  • 10.
  • 11. Dependency Inversion vs Dependency Injection • A principle, one of the SOLID principles • High-level modules should not depend upon low-level modules. Both should depend upon abstractions. • Abstractions should not depend upon details. Details should depend upon abstractions. • A technique offered by frameworks that use an IoC-container but can also be applied manually. Push mechanism (Tell, Don’t Ask or the Hollywood Principe: Don’t Call us, We call You), you can also use a pull mechanism (Ask, Don’t Tell), e.g. a ServiceLocator or Plug-In.
  • 12. LogAnalyzer: Where do we put the interfaces?
  • 14. Compliant with DIP. Any other options?
  • 15. Multiple client depend on a component’s interface
  • 17. Unit vs Integration Tests • Tests that involve many classes are integration tests • In other words: test reading from a database is not a unit test • Integration tests verify the wiring between classes • Unit tests verify classes in isolation • We need both: neither is a replacement of the other
  • 18. Integration integration: Combining 2 or more software units – often a subset of the overall project (!= system testing) Why do software engineers care about integration? – new problems will inevitably surface • many systems now together that have never been before – if done poorly, all problems present themselves at once • hard to diagnose, debug, fix – cascade of interdependencies • cannot find and solve problems one-at-a-time
  • 19. Phased integration phased ("big-bang") integration: – design, code, test, debug each class/unit/subsystem separately – combine them all – pray
  • 20. Incremental integration incremental integration: – develop a functional "skeleton" system – design, code, test, debug a small new piece – integrate this piece with the skeleton • test/debug it before adding any other pieces
  • 21. Benefits of incremental Benefits: – Errors easier to isolate, find, fix • reduces developer bug-fixing load – System is always in a (relatively) working state • good for customer relations, developer morale Drawbacks: – May need to create "stub" versions of some features that have not yet been integrated
  • 22. Top-down integration top-down integration: Start with outer UI layers and work inward – must write (lots of) stub lower layers for UI to interact with – allows postponing tough design/debugging decisions (bad?)
  • 23. Bottom-up integration bottom-up integration: Start with low-level data/logic layers and work outward – must write test drivers to run these layers – won't discover high-level / UI design flaws until late
  • 24. Daily builds daily build: Compile working executable on a daily basis – allows you to test the quality of your integration so far – helps morale; product "works every day"; visible progress – best done automated or through an easy script – quickly catches/exposes any bug that breaks the build smoke test: A quick set of tests run on the daily build. – NOT exhaustive; just sees whether code "smokes" (breaks) – used (along with compilation) to make sure daily build runs continuous integration: Adding new units immediately as they are written.
  • 25. Integration testing integration testing: Verifying software quality by testing two or more dependent software modules as a group. challenges: – Combined units can fail in more places and in more complicated ways. – How to test a partial system where not all parts exist? – How to "rig" the behavior of unit A so as to produce a given behavior from unit B?
  • 27. Test Doubles (Gerard, Fowler) https://martinfowler.com/bliki/TestDouble.html • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example). • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. • Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent. • Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
  • 28. Stubs stub: A controllable replacement for an existing software unit to which your code under test has a dependency. – useful for simulating difficult-to-control elements: • network / internet • database • time/date-sensitive code • files • threads • memory – also useful when dealing with brittle legacy code/systems
  • 29. Create a stub, step 1 Identify the external dependency. – This is either a resource or a class/object. – If it isn't an object, wrap it up into one. • (Suppose that Class A depends on troublesome Class B.)
  • 30. Create a stub, step 2 Extract the core functionality of the object into an interface. – Create an InterfaceB based on B – Change all of A's code to work with type InterfaceB, not B
  • 31. Create a stub, step 3 Write a second "stub" class that also implements the interface, but returns pre-determined fake data. – Now A's dependency on B is dodged and can be tested easily. – Can focus on how well A integrates with B's external behavior.
  • 32. Injecting a stub seams: Places to inject the stub so Class A will talk to it. – at construction (not ideal) A aardvark = new A(new StubB()); – through a getter/setter method (better) A apple = new A(...); aardvark.setResource(new StubB()); – just before usage, as a parameter (also better) aardvark.methodThatUsesB(new StubB()); • You should not have to change A's code everywhere (beyond using your interface) in order to use your Stub B. (a "testable design")
  • 33. "Mock" objects mock object: A fake object that decides whether a unit test has passed or failed by watching interactions between objects. – useful for interaction testing (as opposed to state testing)
  • 34. Stubs vs. mocks – A stub gives out data that goes to the object/class under test. – The unit test directly asserts against class under test, to make sure it gives the right result when fed this data. – A mock waits to be called by the class under test (A). • Maybe it has several methods it expects that A should call. – It makes sure that it was contacted in exactly the right way. • If A interacts with B the way it should, the test passes.
  • 35. Mock object frameworks Stubs are often best created by hand/IDE. Mocks are tedious to create manually. Mock object frameworks help with the process. – android-mock, EasyMock, jMock, Mockito (Java) – FlexMock / Mocha (Ruby) – SimpleTest / PHPUnit (PHP) – ... Frameworks provide the following: – auto-generation of mock objects that implement a given interface – logging of what calls are performed on the mock objects – methods/primitives for declaring and asserting your expectations
  • 36. Using stubs/mocks together Suppose a log analyzer reads from a web service. If the web fails to log an error, the analyzer must send email. – How to test to ensure that this behavior is occurring? Set up a stub for the web service that intentionally fails. Set up a mock for the email service that checks to see whether the analyzer contacts it to send an email message.
  • 37. Initial Design - Sequence Diagram
  • 38. Initial Design - Package/Class Diagram

Notas do Editor

  1. Don't put assertion statements directly in the mock object, because we may want to re-use it.