SlideShare a Scribd company logo
Mock driven development (with .NET)
Test Driven Development with Mocks for .NET Framework
By Punit Ganshani
Twitter -
                                                                   @ganshani
                                                                   @codetails

                                                                   LinkedIn -
                                                                   Connect


                                                                   Blog Sites –
                                                                   www.ganshani.com
                                                                   www.codetails.com
                                                                   Open Source –
                                                                   CodeInject, Workflow Extractor,
                                                                   dI.Hook


Punit Ganshani
Punit Ganshani is a Technology Evangelist practising application design & development on C#, WCF,
WP8, WinRT and Open Source. He is an open-source contributor on CodePlex, has several applications
on Windows Phone Store, author of a book, and 18+ whitepapers in international magazines.
Not in scope…

                AGILE MANIFESTO
                          SCRUM
                        KANBAN
                      TFD vs. TAD
Test Driven Development (in a nutshell)

A methodology that states that

test cases should be driving the design decisions
and development
advocates knowing the expected behaviour of our application (or a
part of it), before we write the code
enforces incremental design and allows us to write just enough code
to pass our test

      Test first Development vs Test after development   Doing TDD well
Mock driven development using .NET
Mock?

Simulated objects that mimic the behavior of real
objects in controlled ways
                                        -Wikipedia


Mock – to deceive, delude, or disappoint.
                                - English Definition
The terminology

Mocks, Stubs, …

▪ Mocks - Mock objects are used to define expectations i.e: In
  this scenario I expect method A() to be called with such and
  such parameters. Mocks record and verify such expectations..
▪ Stubs - Stubs, on the other hand have a different purpose: they
  do not record or verify expectations, but rather allow us to
  “replace” the behaviour, state of the “fake”object in order to
  utilize a test scenario.
▪ Dummy - objects are passed around but never actually used.
  Usually they are just used to fill parameter lists.


                                              Source: http://martinfowler.com/articles/mocksArentStubs.html
Why mock?

• Actual class does not exist - Multiple development streams focusing
  on different components
• Trips to external services, databases take a lot of time to execute
• Non-existent or un-available dependent environments
• A lot of UI input required in real-code
• Abnormal, Unexpected conditions – outages, natural calamities, etc
• Isolate code under test and narrow the scope
When to mock?

▪ Unit Tests
   ▪ Mock the availability of
       ▪ external components
       ▪ non-existent classes
       ▪ services
       ▪ database calls
   ▪ Isolate the code under test and make it less fragile
▪ Integration Tests
   ▪ Do not mock your dependencies, service calls, database calls, etc
   ▪ Focus on checking the integration of all components
   ▪ Should not have any business-specific code
Types of mocks?

▪ Strict
   ▪ Creates brittle tests
   ▪ Throws an exception if you try to use any method that has not explicitly been
     set up to be used.

▪ Normal, Loose
   ▪ Does not throw an exception if you try to use a method that is not set up, it will
     simply return a default value from the method and keep going.
How to mock – Existing Applications?

        Single Responsibility Principle (SRP) - an object should have only a
1   S   single responsibility

        Open/Closed Principle (OCP) - open for extension, but closed for
    O   modification

        Liskov Substitution Principle (LSP) - derived class should not break
    L   assumptions or behavior of base class

        Interface Segregation Principle (ISP) - many specific interfaces are
2   I   better than one general purpose interface (e.g. role interface)

        Dependency Inversion Principle (DIP) - depend upon abstractions, not
3   D   upon concretions


                                                                      Source: http://prasadhonrao.com/tag/solid/
The steps of mocking



 Arrange               Act      Assert

• Data setup
• Mock setup
                 Execute the   Verify the
                  unit test     output
Arrange : Object & Property Mocks



RhinoMocks                            Moq



              NSubstitute
Arrange : Method Mocks




RhinoMocks                            Moq



                        NSubstitute
Arrange: Event Mocks




RhinoMocks




                       NSubstitute
Beware!

  ▪ Remember what is mocked in which test – structure your unit tests
     appropriately
  ▪ Apply mocks only on Unit Tests, not integration tests
  ▪ Forces IoC container based design in and outside tests
  ▪ Dependencies (interfaces for mocks) should not have constructors
  ▪ GUI’s can’t be mocked, business logic should be


Hybrid approach can be followed – Mock some things that are time consuming,
external to your system, unreliable, not easily reachable and use real instances of
others
Mock driven development using .NET
Further Read

▪ Understanding Mock and frameworks – Part 1 of N – Understanding
  the need of TDD, Mock and getting your application Unit Test ready
▪ Understanding Mock and frameworks – Part 2 of N – Understanding
  Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq
▪ Understanding Mock and frameworks – Part 3 of N - Understanding
  how to Mock Methods calls and their Output – Rhino Mocks,
  NSubstitute and Moq
▪ Understanding Mock and frameworks – Part 4 of N - Understanding
  how to Mock Exceptions and Event Subscriptions – Rhino Mocks,
  NSubstitute and Moq

More Related Content

PPTX
Unit Testing And Mocking
PPTX
Understanding Unit Testing
PPTX
Unit Testing
PPTX
An Introduction to Unit Testing
PPTX
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
PPTX
Moq presentation
PDF
Unit Testing Fundamentals
PPT
Unit testing
Unit Testing And Mocking
Understanding Unit Testing
Unit Testing
An Introduction to Unit Testing
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Moq presentation
Unit Testing Fundamentals
Unit testing

What's hot (20)

PPTX
Unit testing
PPS
Unit Testing
PPTX
Unit tests & TDD
PPTX
Unit Testing (C#)
PPTX
Benefit From Unit Testing In The Real World
PDF
Unit testing (workshop)
PPTX
Unit testing - the hard parts
PPTX
Unit Testing Concepts and Best Practices
PDF
Clean Unit Test Patterns
PDF
Unit and integration Testing
PDF
Unit Test + Functional Programming = Love
PPT
Unit Testing
PPTX
Software Quality via Unit Testing
PPTX
Unit Tests And Automated Testing
PPTX
Unit test
ODP
Beginners - Get Started With Unit Testing in .NET
PDF
Unit Testing 101
PPTX
UNIT TESTING
PPTX
Good Unit Tests Ask For Quality Code
PPSX
Unit Test Presentation
Unit testing
Unit Testing
Unit tests & TDD
Unit Testing (C#)
Benefit From Unit Testing In The Real World
Unit testing (workshop)
Unit testing - the hard parts
Unit Testing Concepts and Best Practices
Clean Unit Test Patterns
Unit and integration Testing
Unit Test + Functional Programming = Love
Unit Testing
Software Quality via Unit Testing
Unit Tests And Automated Testing
Unit test
Beginners - Get Started With Unit Testing in .NET
Unit Testing 101
UNIT TESTING
Good Unit Tests Ask For Quality Code
Unit Test Presentation
Ad

Viewers also liked (17)

PPTX
Moq Presentation
PPTX
Principles and patterns for test driven development
PPT
PDF
Javascript TDD by example
PDF
Java script tutorial by example
PDF
All about unit testing using (power) mock
PDF
Sequential file programming patterns and performance with .net
PDF
Unit Testing and Test Driven Development in Unity3D
PDF
TDD, BDD and mocks
PPT
Tdd in unity
PDF
An Introduction to Unit Test Using NUnit
PPTX
TDD - Agile
PDF
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
PPTX
UNIT TESTING PPT
PDF
Unit testing best practices
PDF
Test Driven Development (TDD)
PPTX
F# Presentation
Moq Presentation
Principles and patterns for test driven development
Javascript TDD by example
Java script tutorial by example
All about unit testing using (power) mock
Sequential file programming patterns and performance with .net
Unit Testing and Test Driven Development in Unity3D
TDD, BDD and mocks
Tdd in unity
An Introduction to Unit Test Using NUnit
TDD - Agile
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
UNIT TESTING PPT
Unit testing best practices
Test Driven Development (TDD)
F# Presentation
Ad

Similar to Mock driven development using .NET (20)

PPTX
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
PPTX
Unit Testing Full@
PDF
TechEvent 2019: Artificial Intelligence in Dev & Ops; Martin Luckow - Trivadis
PDF
Architecting a Large Software Project - Lessons Learned
PDF
Django in the Real World
PDF
10 Ways To Improve Your Code
PPTX
Introduction to django
PDF
Boston Startup School - OO Design
PDF
DataEngConf SF16 - Methods for Content Relevance at LinkedIn
DOC
Mayur_Resume (2) (1)
PPTX
Open, Secure & Transparent AI Pipelines
PPTX
Dependency Injection in .NET applications
PPTX
Technologies for startup
PPTX
Agile Mumbai 2022 - Rohit Handa | Combining Human and Artificial Intelligence...
PDF
Devday2016 real unittestingwithmockframework-phatvu
PDF
Workshop - The Little Pattern That Could.pdf
PPTX
Type mock isolator
PPTX
Latest trends in information technology
PDF
10 Ways To Improve Your Code( Neal Ford)
PDF
Automation Abstractions: Page Objects and Beyond
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
Unit Testing Full@
TechEvent 2019: Artificial Intelligence in Dev & Ops; Martin Luckow - Trivadis
Architecting a Large Software Project - Lessons Learned
Django in the Real World
10 Ways To Improve Your Code
Introduction to django
Boston Startup School - OO Design
DataEngConf SF16 - Methods for Content Relevance at LinkedIn
Mayur_Resume (2) (1)
Open, Secure & Transparent AI Pipelines
Dependency Injection in .NET applications
Technologies for startup
Agile Mumbai 2022 - Rohit Handa | Combining Human and Artificial Intelligence...
Devday2016 real unittestingwithmockframework-phatvu
Workshop - The Little Pattern That Could.pdf
Type mock isolator
Latest trends in information technology
10 Ways To Improve Your Code( Neal Ford)
Automation Abstractions: Page Objects and Beyond

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Advanced methodologies resolving dimensionality complications for autism neur...
Chapter 2 Digital Image Fundamentals.pdf
Spectral efficient network and resource selection model in 5G networks
Per capita expenditure prediction using model stacking based on satellite ima...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Empathic Computing: Creating Shared Understanding
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Sensors and Actuators in IoT Systems using pdf
madgavkar20181017ppt McKinsey Presentation.pdf
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Weekly Chronicles - August'25 Week I
Transforming Manufacturing operations through Intelligent Integrations
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
MYSQL Presentation for SQL database connectivity
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....

Mock driven development using .NET

  • 1. Mock driven development (with .NET) Test Driven Development with Mocks for .NET Framework By Punit Ganshani
  • 2. Twitter - @ganshani @codetails LinkedIn - Connect Blog Sites – www.ganshani.com www.codetails.com Open Source – CodeInject, Workflow Extractor, dI.Hook Punit Ganshani Punit Ganshani is a Technology Evangelist practising application design & development on C#, WCF, WP8, WinRT and Open Source. He is an open-source contributor on CodePlex, has several applications on Windows Phone Store, author of a book, and 18+ whitepapers in international magazines.
  • 3. Not in scope… AGILE MANIFESTO SCRUM KANBAN TFD vs. TAD
  • 4. Test Driven Development (in a nutshell) A methodology that states that test cases should be driving the design decisions and development advocates knowing the expected behaviour of our application (or a part of it), before we write the code enforces incremental design and allows us to write just enough code to pass our test Test first Development vs Test after development Doing TDD well
  • 6. Mock? Simulated objects that mimic the behavior of real objects in controlled ways -Wikipedia Mock – to deceive, delude, or disappoint. - English Definition
  • 7. The terminology Mocks, Stubs, … ▪ Mocks - Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations.. ▪ Stubs - Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behaviour, state of the “fake”object in order to utilize a test scenario. ▪ Dummy - objects are passed around but never actually used. Usually they are just used to fill parameter lists. Source: http://martinfowler.com/articles/mocksArentStubs.html
  • 8. Why mock? • Actual class does not exist - Multiple development streams focusing on different components • Trips to external services, databases take a lot of time to execute • Non-existent or un-available dependent environments • A lot of UI input required in real-code • Abnormal, Unexpected conditions – outages, natural calamities, etc • Isolate code under test and narrow the scope
  • 9. When to mock? ▪ Unit Tests ▪ Mock the availability of ▪ external components ▪ non-existent classes ▪ services ▪ database calls ▪ Isolate the code under test and make it less fragile ▪ Integration Tests ▪ Do not mock your dependencies, service calls, database calls, etc ▪ Focus on checking the integration of all components ▪ Should not have any business-specific code
  • 10. Types of mocks? ▪ Strict ▪ Creates brittle tests ▪ Throws an exception if you try to use any method that has not explicitly been set up to be used. ▪ Normal, Loose ▪ Does not throw an exception if you try to use a method that is not set up, it will simply return a default value from the method and keep going.
  • 11. How to mock – Existing Applications? Single Responsibility Principle (SRP) - an object should have only a 1 S single responsibility Open/Closed Principle (OCP) - open for extension, but closed for O modification Liskov Substitution Principle (LSP) - derived class should not break L assumptions or behavior of base class Interface Segregation Principle (ISP) - many specific interfaces are 2 I better than one general purpose interface (e.g. role interface) Dependency Inversion Principle (DIP) - depend upon abstractions, not 3 D upon concretions Source: http://prasadhonrao.com/tag/solid/
  • 12. The steps of mocking Arrange Act Assert • Data setup • Mock setup Execute the Verify the unit test output
  • 13. Arrange : Object & Property Mocks RhinoMocks Moq NSubstitute
  • 14. Arrange : Method Mocks RhinoMocks Moq NSubstitute
  • 16. Beware! ▪ Remember what is mocked in which test – structure your unit tests appropriately ▪ Apply mocks only on Unit Tests, not integration tests ▪ Forces IoC container based design in and outside tests ▪ Dependencies (interfaces for mocks) should not have constructors ▪ GUI’s can’t be mocked, business logic should be Hybrid approach can be followed – Mock some things that are time consuming, external to your system, unreliable, not easily reachable and use real instances of others
  • 18. Further Read ▪ Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready ▪ Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq ▪ Understanding Mock and frameworks – Part 3 of N - Understanding how to Mock Methods calls and their Output – Rhino Mocks, NSubstitute and Moq ▪ Understanding Mock and frameworks – Part 4 of N - Understanding how to Mock Exceptions and Event Subscriptions – Rhino Mocks, NSubstitute and Moq