SlideShare a Scribd company logo
Mocking
Maarten Balliauw – RealDolmen Huizingen
     http://blog.maartenballiauw.be
                 www.visug.be
Who am I?
•   Maarten Balliauw
•   Antwerp, Belgium
•   www.realdolmen.com
•   Focus on web
    – ASP.NET, ASP.NET MVC, PHP, Azure, VSTS, …
• http://blog.maartenballiauw.be
• http://twitter.com/maartenballiauw

                        www.visug.be
Agenda
• Unit testing
• Dependencies
• Mocking frameworks




                  www.visug.be
Unit testing (“you-need testing”)
• Verification
  – Self validating
• Feedback speed
  – They should be fast!
• Focus
  – Testing the area we are working on
• Isolation
  – No dependencies!
                       www.visug.be
Unit testing
• Arrange
  – Get everything prepared for test
• Act
  – Execute the code under test
• Assert
  – Verify everything worked as expected




                       www.visug.be
Let’s create something…
• Order OrderBeer<T>(int count);
  – Create an order
  – Add count beers




                      www.visug.be
Our example, the TDD way

DEMO


                           www.visug.be
Extending our example…
• Order OrderBeer<T>(int count);
  – Create an order
  – Add count beers
  – Is the sun shining?
  – If yes
     • Order free cheese with it
     • Pass this to the KitchenService
  – If no
     • Order free nuts
     • Instruct the NutDistributor machine
                          www.visug.be
Do I really want to test these?
• Weather web service
• Kitchen ordering system
• Nut distributor machine




                    www.visug.be
Use a “Stunt Double” (Test Double)
• 4 types of test double
  – Dummy
     • Null, empty List<T>, …
  – Fake
     • Working implementations
  – Stubs
     • Implementation using canned answers
  – Mocks
     • Implementation returning expected answers for a
       specific test

                          www.visug.be
Creating some fake implementations

DEMO


                             www.visug.be
Retrospection…
• Look at the test class…
  –   Lots of helper classes
  –   Maintainability?
  –   Verification?
  –   Not really linked to specific test

• Wouldn’t it be better…
  – … to have these “helpers” defined per test?
  – … to have a dynamic implementation of these
    “helpers”?

                            www.visug.be
Mocking frameworks
• Convenient interface for setting up
  fakes/stubs/mocks
• Do the job with less code
• Test logic can stay within test
• Write your tests AAA style
• Develop the fake/stub/mock as you test and
  get immediate results (TDD)

                    www.visug.be
Rhino.Mocks
• One of the most mature and feature complete mocking
  frameworks
• Uses Castle remoting to mock calls
    – Not able to mock static or sealed calls
•   Fast
•   Record/Replay syntax and AAA syntax
•   Lots of help and code examples available
•   Open source

• http://ayende.com/projects/rhino-
  mocks/downloads.aspx

                             www.visug.be
Typemock Isolator
• Mature and fully featured (really, LOTS)
• Uses IL Generation
  – Can mock static classes and calls
  – Can chain events
• Commercial licence available for full feature
  set and support

• http://www.typemock.com
                       www.visug.be
Moq (“Mock you!”)
• “The new kid on the block”, increasing popularity
• Uses Castle remoting to mock calls
    – Not able to mock static or sealed calls
•   AAA syntax
•   Vague line between fake/stub/mock
•   Less code clutter in tests
•   Not feature complete, but in active development
•   Open source

• http://code.google.com/p/moq/
                           www.visug.be
Using Moq

DEMO


            www.visug.be
Moq – In the box (1)
• Setup expectations
  // Arrange
  var weatherServiceMock = new Mock<IWeatherService>();
  weatherServiceMock.Setup(s => s.WhatsTheWeather())
                    .Returns(quot;sunnyquot;);




• Even when parameters are not known!
  // Arrange
  var kitchenServiceMock = new Mock<IKitchenService>();
  kitchenServiceMock.Setup(
          k => k.Order(It.IsAny<IConsumable>()))
                    .Returns(true);


                           www.visug.be
Moq – In the box (2)
• Expect Exceptions are thrown
  // Arrange
  var pureAlcohol = new Mock<IBeer>();
  pureAlcohol.Setup(a => a.Drink())
             .Throws(new OverflowException());


• Work with callbacks
  // Arrange
  int beerCount;
  var rochefort10 = new Mock<IBeer>();
  rochefort10.Setup(b => b.Drink())
             .Callback(() => beerCount++)
             .Returns(quot;Beer nr. quot; + beerCount);


                           www.visug.be
Moq – In the box (3)
• Want to mock protected members?
  // Arrange
  var mock = new Mock<CommandBase>();
  mock.Protected()
      .Expect<int>(quot;Executequot;)
      .Returns(5);




                           www.visug.be
Moq – In the box (4)
• Want automatic mocking? Recursive mocks!
   // Arrange
   var context = new Mock<HttpContextBase>();
   context.Expect(c => c.Response.ContentType)
          .Returns(quot;application/xmlquot;);




• (this would be a giant stub if we had to write it ourselves…)



                                  www.visug.be
Moq – In the box (5)
• Verify calls to expectations
  // Assert
  weatherServiceMock.VerifyAll(); // checks all Setup() calls




• Verify certains calls are made X times
  // Assert
  kitchenServiceMock.Verify(
          k => k.Order(It.IsAny<IConsumable>()),
          Times.Exactly(1),
          quot;Only one piece of cheesequot;
  );



                           www.visug.be
When should I…
• Unit test?
   – All the time!

• Mock?
   – Dependency on code that is not under test
      •   “external” object (service, database, web server context, …)
      •   non-deterministic object (temperature, time, …)
      •   hard to reproduce (network error, out of disk space)
      •   slow execution (calculation)
      •   object not yet implemented

   – Don’t mock everything!

                                 www.visug.be
Takeaways
• Use loosely-coupled code!
   – Easier to do when working test-driven (TDD)
   – Tie everything together with an IoC container

• Use a mocking framework when testing
   –   Define “helpers” per test
   –   Define expectations on them
   –   Use these mocked instances in your actual test
   –   Verify stuff

• Don’t mock everything!

                             www.visug.be
Further reading…
• Ayende Rahien
  – http://ayende.com/projects/rhino-mocks.aspx
• TypeMock
  – http://www.typemock.com
• Roy Osherove
  – http://www.iserializable.com
• Daniel Cazzulino
  – http://www.clariusconsulting.net/blogs/kzu/archi
    ve/category/1062.aspx
                      www.visug.be
Questions and Answers




        www.visug.be
Make sure to check http://blog.maartenballiauw.be

THANK YOU!


                              www.visug.be

More Related Content

What's hot

Automate testing with behat, selenium, phantom js and nightwatch.js (5)
Automate testing with behat, selenium, phantom js and nightwatch.js (5)Automate testing with behat, selenium, phantom js and nightwatch.js (5)
Automate testing with behat, selenium, phantom js and nightwatch.js (5)
Faichi Solutions
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
Michał Pierzchała
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
dreamwidth
 
GAEO
GAEOGAEO
(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven Development(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven Development
Filippo Liverani
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Nicholas Zakas
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
Peter Gfader
 
Javascript testing should be awesome
Javascript testing should be awesomeJavascript testing should be awesome
Javascript testing should be awesome
Abderrazak BOUADMA
 
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018
Thijs Feryn
 
Web Cache Deception Attack
Web Cache Deception AttackWeb Cache Deception Attack
Web Cache Deception Attack
Omer Gil
 
Autotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP BasicsAutotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP Basics
Artur Babyuk
 
State of the resource timing api
State of the resource timing apiState of the resource timing api
State of the resource timing api
Aaron Peters
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
Vaidas Pilkauskas
 
Firefox OS something 201411
Firefox OS something 201411Firefox OS something 201411
Firefox OS something 201411
dynamis
 
Your Script Just Killed My Site
Your Script Just Killed My SiteYour Script Just Killed My Site
Your Script Just Killed My Site
Steve Souders
 
Wso2 esb-rest-integration
Wso2 esb-rest-integrationWso2 esb-rest-integration
Wso2 esb-rest-integration
Chanaka Fernando
 
Fav
FavFav
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
Steve Souders
 
Debugging PHP With Xdebug
Debugging PHP With XdebugDebugging PHP With Xdebug
Debugging PHP With Xdebug
Mark Niebergall
 

What's hot (19)

Automate testing with behat, selenium, phantom js and nightwatch.js (5)
Automate testing with behat, selenium, phantom js and nightwatch.js (5)Automate testing with behat, selenium, phantom js and nightwatch.js (5)
Automate testing with behat, selenium, phantom js and nightwatch.js (5)
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
 
GAEO
GAEOGAEO
GAEO
 
(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven Development(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven Development
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Javascript testing should be awesome
Javascript testing should be awesomeJavascript testing should be awesome
Javascript testing should be awesome
 
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018
 
Web Cache Deception Attack
Web Cache Deception AttackWeb Cache Deception Attack
Web Cache Deception Attack
 
Autotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP BasicsAutotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP Basics
 
State of the resource timing api
State of the resource timing apiState of the resource timing api
State of the resource timing api
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
Firefox OS something 201411
Firefox OS something 201411Firefox OS something 201411
Firefox OS something 201411
 
Your Script Just Killed My Site
Your Script Just Killed My SiteYour Script Just Killed My Site
Your Script Just Killed My Site
 
Wso2 esb-rest-integration
Wso2 esb-rest-integrationWso2 esb-rest-integration
Wso2 esb-rest-integration
 
Fav
FavFav
Fav
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
 
Debugging PHP With Xdebug
Debugging PHP With XdebugDebugging PHP With Xdebug
Debugging PHP With Xdebug
 

Viewers also liked

PHP And Silverlight - DevDays session
PHP And Silverlight - DevDays sessionPHP And Silverlight - DevDays session
PHP And Silverlight - DevDays session
Maarten Balliauw
 
PHPExcel
PHPExcelPHPExcel
Just another Wordpress weblog, but more cloudy
Just another Wordpress weblog, but more cloudyJust another Wordpress weblog, but more cloudy
Just another Wordpress weblog, but more cloudy
Maarten Balliauw
 
AZUG.BE - Azure User Group Belgium - First public meeting
AZUG.BE - Azure User Group Belgium - First public meetingAZUG.BE - Azure User Group Belgium - First public meeting
AZUG.BE - Azure User Group Belgium - First public meeting
Maarten Balliauw
 
ASP.NET MVC Wisdom
ASP.NET MVC WisdomASP.NET MVC Wisdom
ASP.NET MVC Wisdom
Maarten Balliauw
 
MSDN - Converting an existing ASP.NET application to Windows Azure
MSDN - Converting an existing ASP.NET application to Windows AzureMSDN - Converting an existing ASP.NET application to Windows Azure
MSDN - Converting an existing ASP.NET application to Windows Azure
Maarten Balliauw
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Maarten Balliauw
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
Maarten Balliauw
 

Viewers also liked (8)

PHP And Silverlight - DevDays session
PHP And Silverlight - DevDays sessionPHP And Silverlight - DevDays session
PHP And Silverlight - DevDays session
 
PHPExcel
PHPExcelPHPExcel
PHPExcel
 
Just another Wordpress weblog, but more cloudy
Just another Wordpress weblog, but more cloudyJust another Wordpress weblog, but more cloudy
Just another Wordpress weblog, but more cloudy
 
AZUG.BE - Azure User Group Belgium - First public meeting
AZUG.BE - Azure User Group Belgium - First public meetingAZUG.BE - Azure User Group Belgium - First public meeting
AZUG.BE - Azure User Group Belgium - First public meeting
 
ASP.NET MVC Wisdom
ASP.NET MVC WisdomASP.NET MVC Wisdom
ASP.NET MVC Wisdom
 
MSDN - Converting an existing ASP.NET application to Windows Azure
MSDN - Converting an existing ASP.NET application to Windows AzureMSDN - Converting an existing ASP.NET application to Windows Azure
MSDN - Converting an existing ASP.NET application to Windows Azure
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
MSDN - ASP.NET MVC
MSDN - ASP.NET MVCMSDN - ASP.NET MVC
MSDN - ASP.NET MVC
 

Similar to Mocking - Visug session

Performance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScriptPerformance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScript
jeresig
 
How the JDeveloper team test JDeveloper at UKOUG'08
How the JDeveloper team test JDeveloper at UKOUG'08How the JDeveloper team test JDeveloper at UKOUG'08
How the JDeveloper team test JDeveloper at UKOUG'08
kingsfleet
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
Ortus Solutions, Corp
 
Progressive Enhancement with JavaScript and Ajax
Progressive Enhancement with JavaScript and AjaxProgressive Enhancement with JavaScript and Ajax
Progressive Enhancement with JavaScript and Ajax
Christian Heilmann
 
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
Atlassian
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
wolframkriesing
 
Tellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.TestingTellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.Testing
John.Jian.Fang
 
High-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
High-Octane Dev Teams: Three Things You Can Do To Improve Code QualityHigh-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
High-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
Atlassian
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
RubyOnRails_dude
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
oscon2007
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
John.Jian.Fang
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
iPhone Development For Experienced Web Developers
iPhone Development For Experienced Web DevelopersiPhone Development For Experienced Web Developers
iPhone Development For Experienced Web Developers
lisab517
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
Gavin Pickin
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript Debugging
Rami Sayar
 
Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript Debugging
FITC
 
Test
TestTest
Test
Eddie Kao
 
Agile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source FrameworksAgile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source Frameworks
Viraf Karai
 
The Tantric Team: Getting Your Automated Build Groove On
The Tantric Team: Getting Your Automated Build Groove OnThe Tantric Team: Getting Your Automated Build Groove On
The Tantric Team: Getting Your Automated Build Groove On
Atlassian
 

Similar to Mocking - Visug session (20)

Performance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScriptPerformance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScript
 
How the JDeveloper team test JDeveloper at UKOUG'08
How the JDeveloper team test JDeveloper at UKOUG'08How the JDeveloper team test JDeveloper at UKOUG'08
How the JDeveloper team test JDeveloper at UKOUG'08
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Progressive Enhancement with JavaScript and Ajax
Progressive Enhancement with JavaScript and AjaxProgressive Enhancement with JavaScript and Ajax
Progressive Enhancement with JavaScript and Ajax
 
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
Peer Code Review: In a Nutshell and The Tantric Team: Getting Your Automated ...
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
Tellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.TestingTellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.Testing
 
High-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
High-Octane Dev Teams: Three Things You Can Do To Improve Code QualityHigh-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
High-Octane Dev Teams: Three Things You Can Do To Improve Code Quality
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorial
 
Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5Tellurium.A.New.Approach.For.Web.Testing.V5
Tellurium.A.New.Approach.For.Web.Testing.V5
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
iPhone Development For Experienced Web Developers
iPhone Development For Experienced Web DevelopersiPhone Development For Experienced Web Developers
iPhone Development For Experienced Web Developers
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript Debugging
 
Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript Debugging
 
Test
TestTest
Test
 
Agile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source FrameworksAgile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source Frameworks
 
The Tantric Team: Getting Your Automated Build Groove On
The Tantric Team: Getting Your Automated Build Groove OnThe Tantric Team: Getting Your Automated Build Groove On
The Tantric Team: Getting Your Automated Build Groove On
 

More from Maarten Balliauw

Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptx
Maarten Balliauw
 
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Maarten Balliauw
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
Maarten Balliauw
 
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Maarten Balliauw
 
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Maarten Balliauw
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
Maarten Balliauw
 
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
Maarten Balliauw
 
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se....NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
Maarten Balliauw
 
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw
 
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and SearchNDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
Maarten Balliauw
 
Approaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days PolandApproaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days Poland
Maarten Balliauw
 
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Maarten Balliauw
 
Approaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologneApproaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologne
Maarten Balliauw
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
Maarten Balliauw
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
Maarten Balliauw
 
ConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttlingConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttling
Maarten Balliauw
 
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Maarten Balliauw
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
Maarten Balliauw
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
Maarten Balliauw
 
VISUG - Approaches for application request throttling
VISUG - Approaches for application request throttlingVISUG - Approaches for application request throttling
VISUG - Approaches for application request throttling
Maarten Balliauw
 

More from Maarten Balliauw (20)

Bringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptxBringing nullability into existing code - dammit is not the answer.pptx
Bringing nullability into existing code - dammit is not the answer.pptx
 
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
 
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
 
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
 
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se....NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
 
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
 
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and SearchNDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
 
Approaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days PolandApproaches for application request throttling - Cloud Developer Days Poland
Approaches for application request throttling - Cloud Developer Days Poland
 
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
 
Approaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologneApproaches for application request throttling - dotNetCologne
Approaches for application request throttling - dotNetCologne
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
ConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttlingConFoo Montreal - Approaches for application request throttling
ConFoo Montreal - Approaches for application request throttling
 
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
VISUG - Approaches for application request throttling
VISUG - Approaches for application request throttlingVISUG - Approaches for application request throttling
VISUG - Approaches for application request throttling
 

Recently uploaded

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 

Recently uploaded (20)

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 

Mocking - Visug session

  • 1. Mocking Maarten Balliauw – RealDolmen Huizingen http://blog.maartenballiauw.be www.visug.be
  • 2. Who am I? • Maarten Balliauw • Antwerp, Belgium • www.realdolmen.com • Focus on web – ASP.NET, ASP.NET MVC, PHP, Azure, VSTS, … • http://blog.maartenballiauw.be • http://twitter.com/maartenballiauw www.visug.be
  • 3.
  • 4. Agenda • Unit testing • Dependencies • Mocking frameworks www.visug.be
  • 5. Unit testing (“you-need testing”) • Verification – Self validating • Feedback speed – They should be fast! • Focus – Testing the area we are working on • Isolation – No dependencies! www.visug.be
  • 6. Unit testing • Arrange – Get everything prepared for test • Act – Execute the code under test • Assert – Verify everything worked as expected www.visug.be
  • 7. Let’s create something… • Order OrderBeer<T>(int count); – Create an order – Add count beers www.visug.be
  • 8. Our example, the TDD way DEMO www.visug.be
  • 9. Extending our example… • Order OrderBeer<T>(int count); – Create an order – Add count beers – Is the sun shining? – If yes • Order free cheese with it • Pass this to the KitchenService – If no • Order free nuts • Instruct the NutDistributor machine www.visug.be
  • 10. Do I really want to test these? • Weather web service • Kitchen ordering system • Nut distributor machine www.visug.be
  • 11. Use a “Stunt Double” (Test Double) • 4 types of test double – Dummy • Null, empty List<T>, … – Fake • Working implementations – Stubs • Implementation using canned answers – Mocks • Implementation returning expected answers for a specific test www.visug.be
  • 12. Creating some fake implementations DEMO www.visug.be
  • 13. Retrospection… • Look at the test class… – Lots of helper classes – Maintainability? – Verification? – Not really linked to specific test • Wouldn’t it be better… – … to have these “helpers” defined per test? – … to have a dynamic implementation of these “helpers”? www.visug.be
  • 14. Mocking frameworks • Convenient interface for setting up fakes/stubs/mocks • Do the job with less code • Test logic can stay within test • Write your tests AAA style • Develop the fake/stub/mock as you test and get immediate results (TDD) www.visug.be
  • 15. Rhino.Mocks • One of the most mature and feature complete mocking frameworks • Uses Castle remoting to mock calls – Not able to mock static or sealed calls • Fast • Record/Replay syntax and AAA syntax • Lots of help and code examples available • Open source • http://ayende.com/projects/rhino- mocks/downloads.aspx www.visug.be
  • 16. Typemock Isolator • Mature and fully featured (really, LOTS) • Uses IL Generation – Can mock static classes and calls – Can chain events • Commercial licence available for full feature set and support • http://www.typemock.com www.visug.be
  • 17. Moq (“Mock you!”) • “The new kid on the block”, increasing popularity • Uses Castle remoting to mock calls – Not able to mock static or sealed calls • AAA syntax • Vague line between fake/stub/mock • Less code clutter in tests • Not feature complete, but in active development • Open source • http://code.google.com/p/moq/ www.visug.be
  • 18. Using Moq DEMO www.visug.be
  • 19. Moq – In the box (1) • Setup expectations // Arrange var weatherServiceMock = new Mock<IWeatherService>(); weatherServiceMock.Setup(s => s.WhatsTheWeather()) .Returns(quot;sunnyquot;); • Even when parameters are not known! // Arrange var kitchenServiceMock = new Mock<IKitchenService>(); kitchenServiceMock.Setup( k => k.Order(It.IsAny<IConsumable>())) .Returns(true); www.visug.be
  • 20. Moq – In the box (2) • Expect Exceptions are thrown // Arrange var pureAlcohol = new Mock<IBeer>(); pureAlcohol.Setup(a => a.Drink()) .Throws(new OverflowException()); • Work with callbacks // Arrange int beerCount; var rochefort10 = new Mock<IBeer>(); rochefort10.Setup(b => b.Drink()) .Callback(() => beerCount++) .Returns(quot;Beer nr. quot; + beerCount); www.visug.be
  • 21. Moq – In the box (3) • Want to mock protected members? // Arrange var mock = new Mock<CommandBase>(); mock.Protected() .Expect<int>(quot;Executequot;) .Returns(5); www.visug.be
  • 22. Moq – In the box (4) • Want automatic mocking? Recursive mocks! // Arrange var context = new Mock<HttpContextBase>(); context.Expect(c => c.Response.ContentType) .Returns(quot;application/xmlquot;); • (this would be a giant stub if we had to write it ourselves…) www.visug.be
  • 23. Moq – In the box (5) • Verify calls to expectations // Assert weatherServiceMock.VerifyAll(); // checks all Setup() calls • Verify certains calls are made X times // Assert kitchenServiceMock.Verify( k => k.Order(It.IsAny<IConsumable>()), Times.Exactly(1), quot;Only one piece of cheesequot; ); www.visug.be
  • 24. When should I… • Unit test? – All the time! • Mock? – Dependency on code that is not under test • “external” object (service, database, web server context, …) • non-deterministic object (temperature, time, …) • hard to reproduce (network error, out of disk space) • slow execution (calculation) • object not yet implemented – Don’t mock everything! www.visug.be
  • 25. Takeaways • Use loosely-coupled code! – Easier to do when working test-driven (TDD) – Tie everything together with an IoC container • Use a mocking framework when testing – Define “helpers” per test – Define expectations on them – Use these mocked instances in your actual test – Verify stuff • Don’t mock everything! www.visug.be
  • 26. Further reading… • Ayende Rahien – http://ayende.com/projects/rhino-mocks.aspx • TypeMock – http://www.typemock.com • Roy Osherove – http://www.iserializable.com • Daniel Cazzulino – http://www.clariusconsulting.net/blogs/kzu/archi ve/category/1062.aspx www.visug.be
  • 27. Questions and Answers www.visug.be
  • 28. Make sure to check http://blog.maartenballiauw.be THANK YOU! www.visug.be