SlideShare ist ein Scribd-Unternehmen logo
1 von 21
eleks.comeleks.com
Fakes, Stubs and Mocks
Mocking frameworks
In previous lessons…
Dummy
objects are passed around but never actually used. Usually they are just used to fill parameter lists.
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. Stubs may also record information about calls, such as an email
gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
Spies
mock only part of methods (is recommended to test legacy code).
Fake
objects actually have working implementations, but usually take some shortcut which makes them not
suitable for production (an in memory database is a good example).
Mocks
objects pre-programmed with expectations which form a specification of the calls they are expected to
receive.
Mocking is
Mock objects are simulated objects that mimic the behavior
of real objects in controlled ways.
A programmer typically creates a mock object to test the
behavior of some other object, in much the same way that a
car designer uses a crash test dummy to simulate the
dynamic behavior of a human in vehicle impacts.
Let’s remind common unit test scenario
Steps:
1. Arrange – setup test context, initialize an
object being tested and its dependent
modules/services, connect them together
2. Act – test triggers behaviour that should
be tested in the object under test
3. Interact – object under test
communicates with collborators
4. Assert – verify that the SUT(object under
test and its dependent modules/services)
behaves as it has to; checks for expected
results
What’s new it has?
- Has dependencies and requires setup all of them
- May have side effects
- Hard to maintain as a result [Ignore] comes to help
- If there is a bug in the dependent object - how can you make your test passed?
What is mocking?
Mocking is a process used in unit testing
when the unit being tested has external
dependencies.
In mocking, the dependencies are
replaced by closely controlled
replacements objects that simulate the
behavior of the real ones.
Mocking features
- Eliminates dependencies between class under test and modules/services/classes it
uses
- Isolate class under test
- Simplify maintenance and support of such tests
- Allow to write test when dependent modules are not implemented
Example of object with dependencies
- What should be verified if method
under test returns void?
- What if we don’t have implementation
of dependent object?
- External resources usage
problem(e.g. not enough disk space,
transport level connection problem,
etc.)
Mocks Aren’t Stubs
State verification
vs
Behavior verification
Fakes
Fake objects actually have working implementations, but usually take
some shortcut which makes them not suitable for production.
Fakes Con’s and Pro’s
Con’s
• Hard to maintain
• Code duplication
• Requires independent implementation
Pro’s
• Great for simple test scenarios
• Easy to implement
Fakes: unit test scenario
• Setup requires implementation of
dependent object functionality
• Interact with fake object
• Asserts on object under test and
their dependencies that now
represented as fakes
eleks.com
Let's go through the first example!
[nUnit + Fake]
Mocking frameworks
Mocking frameworks simplify the process of isolating object under test and eliminates it
dependencies.
Most popular mocking frameworks:
• NSubstitute
• Rhino Mocks
• Moq
• FakeItEasy
• NMock3
Mocking framework features
• Dynamically creates and setup mock objects within test
• Allows to setup and simulate methods calls, including input parameters, return values,
throws exception on mock object
• Built-in method calls verifications – verify method parameters, number of expected
method calls etc.
Stubs
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.
Stubs may also record information about calls, such as an email gateway
stub that remembers the messages it 'sent', or maybe only how many
messages it 'sent'.
Stubs: unit test scenario
• Stubs should be created on the
arrange step – setup methods
calls inputs and outputs
• Stubs don’t take place in the
verification step
Mocks
Mocks are what we are talking about here: objects pre-programmed
with expectations which form a specification of the calls they are
expected to receive.
Mocks – typical test scenario
• Arrange step now is more complex
- setup test context, initialize an
object being tested, configure the
mock object – setup up return
values, excepted method calls and
their arguments
• Assert step moves to the mock
object itself
• Can still assert on the object being
tested or its other collaborators
eleks.com
Unit test with Mocks and Stubs
example
[nUnit + Moq]
eleks.com
Inspired by Technology.
Driven by Value.

Weitere ähnliche Inhalte

Was ist angesagt?

Moq presentation
Moq presentationMoq presentation
Moq presentation
LynxStar
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
Maveryx
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 

Was ist angesagt? (20)

Unit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and MoqUnit Testing in Action - C#, NUnit, and Moq
Unit Testing in Action - C#, NUnit, and Moq
 
The Fitnesse Fix
The Fitnesse FixThe Fitnesse Fix
The Fitnesse Fix
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Moq presentation
Moq presentationMoq presentation
Moq presentation
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Test Driven Development using QUnit
Test Driven Development using QUnitTest Driven Development using QUnit
Test Driven Development using QUnit
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
 
Unit & integration testing
Unit & integration testingUnit & integration testing
Unit & integration testing
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testing
 
Nunit
NunitNunit
Nunit
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking Frameworks
 
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
 
Presentation
PresentationPresentation
Presentation
 
Software Testing - Tool support for testing (CAST) - Mazenet Solution
Software Testing - Tool support for testing (CAST) - Mazenet SolutionSoftware Testing - Tool support for testing (CAST) - Mazenet Solution
Software Testing - Tool support for testing (CAST) - Mazenet Solution
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
ГАННА КАПЛУН «Automatic test data generation» QADay 2019
ГАННА КАПЛУН «Automatic test data generation» QADay 2019ГАННА КАПЛУН «Automatic test data generation» QADay 2019
ГАННА КАПЛУН «Automatic test data generation» QADay 2019
 
Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010Tdd Ugialtnet Jan2010
Tdd Ugialtnet Jan2010
 

Andere mochten auch (20)

Improving rpc bkp
Improving rpc bkpImproving rpc bkp
Improving rpc bkp
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Unit1 summary
Unit1 summaryUnit1 summary
Unit1 summary
 
DAL
DALDAL
DAL
 
Web service lecture
Web service lectureWeb service lecture
Web service lecture
 
tsql
tsqltsql
tsql
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
 
Windows service
Windows serviceWindows service
Windows service
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
 
#2 integration + ui tests
#2 integration + ui tests#2 integration + ui tests
#2 integration + ui tests
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
 
If unit2 summary
If unit2 summaryIf unit2 summary
If unit2 summary
 
SQL Grouping, Joins
SQL Grouping, JoinsSQL Grouping, Joins
SQL Grouping, Joins
 
Code Practices
Code PracticesCode Practices
Code Practices
 
#4 code quality
#4 code quality#4 code quality
#4 code quality
 
Mvvw patterns
Mvvw patternsMvvw patterns
Mvvw patterns
 
Rpc
RpcRpc
Rpc
 
SQL: Indexes, Select operator
SQL: Indexes, Select operatorSQL: Indexes, Select operator
SQL: Indexes, Select operator
 
SDLC. QA Role
SDLC. QA RoleSDLC. QA Role
SDLC. QA Role
 
Sql 04n edited
Sql 04n editedSql 04n edited
Sql 04n edited
 

Ähnlich wie Mocking

Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 

Ähnlich wie Mocking (20)

Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
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
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tips
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Flex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative AnalysisFlex Mock Testing Frameworks: Comparative Analysis
Flex Mock Testing Frameworks: Comparative Analysis
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
 
Testing 101
Testing 101Testing 101
Testing 101
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 

Mehr von eleksdev (16)

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
 
Communication in android
Communication in androidCommunication in android
Communication in android
 
Hello android world
Hello android worldHello android world
Hello android world
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
 
Android location and sensors API
Android location and sensors APIAndroid location and sensors API
Android location and sensors API
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
 
Version control
Version controlVersion control
Version control
 
NoSQL basics
NoSQL basicsNoSQL basics
NoSQL basics
 
sql introduction
sql introductionsql introduction
sql introduction
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Mocking

  • 1. eleks.comeleks.com Fakes, Stubs and Mocks Mocking frameworks
  • 2. In previous lessons… Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. 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. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'. Spies mock only part of methods (is recommended to test legacy code). Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example). Mocks objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
  • 3. Mocking is Mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.
  • 4. Let’s remind common unit test scenario Steps: 1. Arrange – setup test context, initialize an object being tested and its dependent modules/services, connect them together 2. Act – test triggers behaviour that should be tested in the object under test 3. Interact – object under test communicates with collborators 4. Assert – verify that the SUT(object under test and its dependent modules/services) behaves as it has to; checks for expected results
  • 5. What’s new it has? - Has dependencies and requires setup all of them - May have side effects - Hard to maintain as a result [Ignore] comes to help - If there is a bug in the dependent object - how can you make your test passed?
  • 6. What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the behavior of the real ones.
  • 7. Mocking features - Eliminates dependencies between class under test and modules/services/classes it uses - Isolate class under test - Simplify maintenance and support of such tests - Allow to write test when dependent modules are not implemented
  • 8. Example of object with dependencies - What should be verified if method under test returns void? - What if we don’t have implementation of dependent object? - External resources usage problem(e.g. not enough disk space, transport level connection problem, etc.)
  • 9. Mocks Aren’t Stubs State verification vs Behavior verification
  • 10. Fakes Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production.
  • 11. Fakes Con’s and Pro’s Con’s • Hard to maintain • Code duplication • Requires independent implementation Pro’s • Great for simple test scenarios • Easy to implement
  • 12. Fakes: unit test scenario • Setup requires implementation of dependent object functionality • Interact with fake object • Asserts on object under test and their dependencies that now represented as fakes
  • 13. eleks.com Let's go through the first example! [nUnit + Fake]
  • 14. Mocking frameworks Mocking frameworks simplify the process of isolating object under test and eliminates it dependencies. Most popular mocking frameworks: • NSubstitute • Rhino Mocks • Moq • FakeItEasy • NMock3
  • 15. Mocking framework features • Dynamically creates and setup mock objects within test • Allows to setup and simulate methods calls, including input parameters, return values, throws exception on mock object • Built-in method calls verifications – verify method parameters, number of expected method calls etc.
  • 16. Stubs 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. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
  • 17. Stubs: unit test scenario • Stubs should be created on the arrange step – setup methods calls inputs and outputs • Stubs don’t take place in the verification step
  • 18. Mocks Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
  • 19. Mocks – typical test scenario • Arrange step now is more complex - setup test context, initialize an object being tested, configure the mock object – setup up return values, excepted method calls and their arguments • Assert step moves to the mock object itself • Can still assert on the object being tested or its other collaborators
  • 20. eleks.com Unit test with Mocks and Stubs example [nUnit + Moq]