SlideShare a Scribd company logo
MOCKING WITH MOQ
A look at mocking objects
with the Moq framework
By: Mohamed Elkhodary
YOUR EXPECTATIONS
TEST DRIVEN DEVELOPMENT
If it's worth building, it's worth testing.
If it's not worth testing, why are you wasting your time working
on it?
TEST DRIVEN DEVELOPMENT
THE PROBLEM
SOLUTION
INTRODUCTION What is mocking?
TERMINOLOGIES
o Mocks used to define expectations. Like expecting that method A()
to be called with defined parameters. Mocks record and verify such
expectations.
o Stubs do not record or verify expectations, but rather allow us to
“replace” the behavior and state of the “fake” object in order to utilize
a test scenario.
o Dummy objects are passed around but never actually used. Usually
they are just used to fill parameter lists.
MOCKING AN OBJECT
o Mock objects are simulated
objects that mimic the behavior
of real objects in controlled
ways.
o A programmer typically creates
a mock object to test the
behavior of some other object.
REASONS FOR USE
o The object supplies non-deterministic results (e.g., the current time
or the current temperature).
o It has states that are difficult to create or reproduce (e.g., a network
error).
o It is slow (e.g., a complete database, which would have to be
initialized before the test).
o It does not yet exist or may change behavior.
o Testing it is out of current scope (External component).
o Focus on SUT without worrying about its dependencies.
WHAT DOES A MOCKING
FRAMEWORK DO?
1. Create fake objects.
2. Set behavior of fake objects.
3. Verify method was called.
4. And much more .
STEPS OF MOCKING
Arrange Act Assert
RULE OF THUMB
Apply mocks only on Unit Tests, not
Integration Tests
TECHNICAL DETAILS
o Mock objects have the same interface as the real objects they mimic,
allowing a client object to remain unaware of whether it is using a
real object or a mock object.
o Many available mock object frameworks allow the programmer to
specify which, and in what order, methods will be invoked on a mock
object and what parameters will be passed to them, as well as what
values will be returned.
o Behavior of a complex object such as a network socket can be
mimicked by a mock object, allowing the programmer to discover
whether the object being tested responds appropriately to the wide
variety of states such mock objects may be in.
HAND ROLLED MOCK Example
TRY IT | CUSTOMER SERVICE
o This service dependent on:
o CustomerAdressBuilder.
o Has a method ‘From’ whose input parameter is a customer command and return an address as a string.
o CustomerRepository.
o Can save a customer object on the persistence storage.
o Get mailing address to customer from CustomerAddressBuilder.
o Throws InvalidCustomerMailingAddressException if mailing address
is null.
o Assign mailing address to customer.
o Persist customer in CustomerRepository.
MOQ Code samples
2) SIMPLE MOCK – WATCH USING
MOQ
o Create Single Customer
o Input : CustomerCreateCommand.
o It has to:
oCreate a customer object.
o Persist it on the respository.
2) SIMPLE MOCK– TRY IT
oCreate Bulk of Customers
o Input : List of CustomerCreateCommand.
o It has to:
oCreate a customer object.
o Persist it on the respository.
3) RETURN VALUES – TRY IT
oNotes:
oApply Moq on example of hand rolled mock.
oICustomerAddressBuilder Interface.
o string From(CustomerCreateCommand customercommand);
o Actions:
o Mock address builder to return an Email.
o Write a test method for testing exception if mailing address is
null.
o Verify that CustomerRepository Save method is called.
4) OUTPUT PARAMETERS – TRY IT
oNotes:
oIMailingAddressFactory Interface.
o bool TryParse(string mailingAddress, out MailingAddress result);
o Actions:
o Mock IMailingAddressFactory to return an output parameter.
o Set customer DetailedMailingAddress by the result.
o Verify that CustomerRepository Save method is called.
5) MULTIPLE RETURN VALUES –
TRY IT
o Notes:
oCheck IIdFactory Interface.
oint Create();
o Create method of Customer Service has a list of Customer Create
Commands.
o Set a unique Id for each customer using IIdFactory Interface.
o Persist it on the repository.
o Actions:
o Verify that CustomerRepository Save method is called.
o Verify that Create method is called per command to set
customer Id.
6) ARGUMENT TRACKING – TRY IT
o Notes:
o IFullNameFactory Interface.
ostring From(string firstName, string lastName);
o Set Customer Fullname by result of From method in
IFullNameFactory.
o Persist it on the repository.
o Actions:
o Setup From in IFullNameFactory to get any string values in
both input parameters.
o Verify that both input parameters equals the command
corresponding values.
7) EXECUTION FLOW – TRY IT
Notes:
o IStatusFactory Interface.
o CustomerStatusEnum From(CustomerCreateCommand
createCommand);
o CustomerStatusEnum (Normal, Platinum).
o Set customer status by result from From method in IStatusFactory.
o If Customer status is Platinum, use SaveSpecial in
ICustomerRepository.
o else, use Save in ICustomerRepository.
Actions:
o Setup From in IStatusFactory to return different results.
o Verify that appropriate methods called.
8) PROPERTIES – TRY IT
Notes:
o Check ICustomerRepository Interface.
o Check IApplicationSettings Interface.
o Set Customer Repository Time Zone by Standard name of
current time zone.
Actions:
o Verify ICustomerRepository TimeZone setter.
8) PROPERTIES – TRY IT
Notes:
o Check ICustomerRepository Interface.
o Check IApplicationSettings Interface.
o Set WorkStationId of Customer by WorkStationId of
IApplicationSettings.
Actions:
o Verify IApplicationSettings WorkStationId getter.
8) PROPERTIES – TRY IT
Notes:
o Check ICustomerRepository Interface.
o Check IApplicationSettings Interface.
o Make it harder by using complex property object.
Actions:
o Verify getter of
_applicationSettings.SystemConfiguration.AuditingInformation.WorkStationI
d.
8) PROPERTIES – TRY IT
1. Try using SetupProperty instead of Setup
2. Try setup the property from the exposed object of
mock
3. SetupAllProperties
9) EVENTS – TRY IT
Notes:
o Check IMailingRepository Interface.
o CustomerRepository should subscribe to an Event
NotifySalesTeam.
o Once event is raised, it has to call NewCustomerMessage in
IMailingRepository and pass the event argument.
Actions:
o Verify that NewCustomerMessage is called if event raised.
MOQ | ADVANCED TOPICS Samples
1) RECURSIVE MOCKING
Notes:
o Check IMailingAddressFactory Interface.
o Get ICustomerAddressBuilder from
IMailingAddressFactory .
o Set Customer Mailing Address using From method in
ICustomerAddressBuilder.
Actions:
o Verify that From method in ICustomerAddressBuilder is
called.
2) PROTECTED MEMBERS
Notes:
o Check CustomerNameFormatter class.
Actions:
o Verify that RemoveUnderScoreFrom is called.
3) INTERFACES
Notes:
o Check StringSequenceReader class.
Actions:
o Verify that Dispose method is called.
EDUWORX Real Example
BEST PRACTICES Hints on using TDD
THE BAD
o The use of mock objects can closely couple the unit tests to the
actual implementation.
o Test fails even though all mocked object methods still obey the
contract of the previous implementation.
o Over-use of mock objects as part of a suite of unit tests can result
in a dramatic increase in the amount of maintenance.
THANK YOU!

More Related Content

What's hot

Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
ICS
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
Luciano Queiroz
 
React Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive servicesReact Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive services
Fabio Biondi
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
JIGAR MAKHIJA
 
Functions in php
Functions in phpFunctions in php
Functions in php
Kamal Acharya
 
Clean backends with NestJs
Clean backends with NestJsClean backends with NestJs
Clean backends with NestJs
Aymene Bennour
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Joe Tremblay
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Luis Goldster
 
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
All Things Open
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Lilia Sfaxi
 
Php cookies
Php cookiesPhp cookies
Php cookies
JIGAR MAKHIJA
 

What's hot (20)

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
React Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive servicesReact Typescript for beginners: Translator app with Microsoft cognitive services
React Typescript for beginners: Translator app with Microsoft cognitive services
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Clean backends with NestJs
Clean backends with NestJsClean backends with NestJs
Clean backends with NestJs
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
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
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Php cookies
Php cookiesPhp cookies
Php cookies
 

Viewers also liked

Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQUnit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Bruce Johnson
 
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas FendTrivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis
 
Ibs s&op overview
Ibs s&op   overviewIbs s&op   overview
Ibs s&op overviewAlex Doyle
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
Pranalee Rokde
 
Sales & Operations Planning (S&OP): An Introduction
Sales & Operations Planning (S&OP): An IntroductionSales & Operations Planning (S&OP): An Introduction
Sales & Operations Planning (S&OP): An Introduction
Steelwedge
 
Inventory Control Final Ppt
Inventory Control Final PptInventory Control Final Ppt
Inventory Control Final Ppt
rajnikant
 
Inventory control & management
Inventory control & managementInventory control & management
Inventory control & management
Goa App
 

Viewers also liked (7)

Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQUnit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
 
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas FendTrivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
 
Ibs s&op overview
Ibs s&op   overviewIbs s&op   overview
Ibs s&op overview
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Sales & Operations Planning (S&OP): An Introduction
Sales & Operations Planning (S&OP): An IntroductionSales & Operations Planning (S&OP): An Introduction
Sales & Operations Planning (S&OP): An Introduction
 
Inventory Control Final Ppt
Inventory Control Final PptInventory Control Final Ppt
Inventory Control Final Ppt
 
Inventory control & management
Inventory control & managementInventory control & management
Inventory control & management
 

Similar to Mocking with Moq

Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
Paul Churchward
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
Stefan Oprea
 
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
Harry Potter
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
James Wong
 
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
Hoang Nguyen
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Young Alista
 
Qtp 11 notes
Qtp 11 notesQtp 11 notes
Qtp 11 notes
Pragya Rastogi
 
Micro Object Testing
Micro Object TestingMicro Object Testing
Micro Object Testing
ESUG
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Test api
Test apiTest api
Test api
Ivo Manolov
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET Journal
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
Deepak Singhvi
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 

Similar to Mocking with Moq (20)

Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
 
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
 
Qtp 11 notes
Qtp 11 notesQtp 11 notes
Qtp 11 notes
 
Micro Object Testing
Micro Object TestingMicro Object Testing
Micro Object Testing
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Test api
Test apiTest api
Test api
 
Ex
ExEx
Ex
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 

Recently uploaded

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 

Recently uploaded (20)

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 

Mocking with Moq

  • 1. MOCKING WITH MOQ A look at mocking objects with the Moq framework By: Mohamed Elkhodary
  • 3. TEST DRIVEN DEVELOPMENT If it's worth building, it's worth testing. If it's not worth testing, why are you wasting your time working on it?
  • 8. TERMINOLOGIES o Mocks used to define expectations. Like expecting that method A() to be called with defined parameters. Mocks record and verify such expectations. o Stubs do not record or verify expectations, but rather allow us to “replace” the behavior and state of the “fake” object in order to utilize a test scenario. o Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • 9. MOCKING AN OBJECT o Mock objects are simulated objects that mimic the behavior of real objects in controlled ways. o A programmer typically creates a mock object to test the behavior of some other object.
  • 10. REASONS FOR USE o The object supplies non-deterministic results (e.g., the current time or the current temperature). o It has states that are difficult to create or reproduce (e.g., a network error). o It is slow (e.g., a complete database, which would have to be initialized before the test). o It does not yet exist or may change behavior. o Testing it is out of current scope (External component). o Focus on SUT without worrying about its dependencies.
  • 11. WHAT DOES A MOCKING FRAMEWORK DO? 1. Create fake objects. 2. Set behavior of fake objects. 3. Verify method was called. 4. And much more .
  • 13. RULE OF THUMB Apply mocks only on Unit Tests, not Integration Tests
  • 14. TECHNICAL DETAILS o Mock objects have the same interface as the real objects they mimic, allowing a client object to remain unaware of whether it is using a real object or a mock object. o Many available mock object frameworks allow the programmer to specify which, and in what order, methods will be invoked on a mock object and what parameters will be passed to them, as well as what values will be returned. o Behavior of a complex object such as a network socket can be mimicked by a mock object, allowing the programmer to discover whether the object being tested responds appropriately to the wide variety of states such mock objects may be in.
  • 15. HAND ROLLED MOCK Example
  • 16. TRY IT | CUSTOMER SERVICE o This service dependent on: o CustomerAdressBuilder. o Has a method ‘From’ whose input parameter is a customer command and return an address as a string. o CustomerRepository. o Can save a customer object on the persistence storage. o Get mailing address to customer from CustomerAddressBuilder. o Throws InvalidCustomerMailingAddressException if mailing address is null. o Assign mailing address to customer. o Persist customer in CustomerRepository.
  • 18. 2) SIMPLE MOCK – WATCH USING MOQ o Create Single Customer o Input : CustomerCreateCommand. o It has to: oCreate a customer object. o Persist it on the respository.
  • 19. 2) SIMPLE MOCK– TRY IT oCreate Bulk of Customers o Input : List of CustomerCreateCommand. o It has to: oCreate a customer object. o Persist it on the respository.
  • 20. 3) RETURN VALUES – TRY IT oNotes: oApply Moq on example of hand rolled mock. oICustomerAddressBuilder Interface. o string From(CustomerCreateCommand customercommand); o Actions: o Mock address builder to return an Email. o Write a test method for testing exception if mailing address is null. o Verify that CustomerRepository Save method is called.
  • 21. 4) OUTPUT PARAMETERS – TRY IT oNotes: oIMailingAddressFactory Interface. o bool TryParse(string mailingAddress, out MailingAddress result); o Actions: o Mock IMailingAddressFactory to return an output parameter. o Set customer DetailedMailingAddress by the result. o Verify that CustomerRepository Save method is called.
  • 22. 5) MULTIPLE RETURN VALUES – TRY IT o Notes: oCheck IIdFactory Interface. oint Create(); o Create method of Customer Service has a list of Customer Create Commands. o Set a unique Id for each customer using IIdFactory Interface. o Persist it on the repository. o Actions: o Verify that CustomerRepository Save method is called. o Verify that Create method is called per command to set customer Id.
  • 23. 6) ARGUMENT TRACKING – TRY IT o Notes: o IFullNameFactory Interface. ostring From(string firstName, string lastName); o Set Customer Fullname by result of From method in IFullNameFactory. o Persist it on the repository. o Actions: o Setup From in IFullNameFactory to get any string values in both input parameters. o Verify that both input parameters equals the command corresponding values.
  • 24. 7) EXECUTION FLOW – TRY IT Notes: o IStatusFactory Interface. o CustomerStatusEnum From(CustomerCreateCommand createCommand); o CustomerStatusEnum (Normal, Platinum). o Set customer status by result from From method in IStatusFactory. o If Customer status is Platinum, use SaveSpecial in ICustomerRepository. o else, use Save in ICustomerRepository. Actions: o Setup From in IStatusFactory to return different results. o Verify that appropriate methods called.
  • 25. 8) PROPERTIES – TRY IT Notes: o Check ICustomerRepository Interface. o Check IApplicationSettings Interface. o Set Customer Repository Time Zone by Standard name of current time zone. Actions: o Verify ICustomerRepository TimeZone setter.
  • 26. 8) PROPERTIES – TRY IT Notes: o Check ICustomerRepository Interface. o Check IApplicationSettings Interface. o Set WorkStationId of Customer by WorkStationId of IApplicationSettings. Actions: o Verify IApplicationSettings WorkStationId getter.
  • 27. 8) PROPERTIES – TRY IT Notes: o Check ICustomerRepository Interface. o Check IApplicationSettings Interface. o Make it harder by using complex property object. Actions: o Verify getter of _applicationSettings.SystemConfiguration.AuditingInformation.WorkStationI d.
  • 28. 8) PROPERTIES – TRY IT 1. Try using SetupProperty instead of Setup 2. Try setup the property from the exposed object of mock 3. SetupAllProperties
  • 29. 9) EVENTS – TRY IT Notes: o Check IMailingRepository Interface. o CustomerRepository should subscribe to an Event NotifySalesTeam. o Once event is raised, it has to call NewCustomerMessage in IMailingRepository and pass the event argument. Actions: o Verify that NewCustomerMessage is called if event raised.
  • 30. MOQ | ADVANCED TOPICS Samples
  • 31. 1) RECURSIVE MOCKING Notes: o Check IMailingAddressFactory Interface. o Get ICustomerAddressBuilder from IMailingAddressFactory . o Set Customer Mailing Address using From method in ICustomerAddressBuilder. Actions: o Verify that From method in ICustomerAddressBuilder is called.
  • 32. 2) PROTECTED MEMBERS Notes: o Check CustomerNameFormatter class. Actions: o Verify that RemoveUnderScoreFrom is called.
  • 33. 3) INTERFACES Notes: o Check StringSequenceReader class. Actions: o Verify that Dispose method is called.
  • 35. BEST PRACTICES Hints on using TDD
  • 36. THE BAD o The use of mock objects can closely couple the unit tests to the actual implementation. o Test fails even though all mocked object methods still obey the contract of the previous implementation. o Over-use of mock objects as part of a suite of unit tests can result in a dramatic increase in the amount of maintenance.