SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 JestMichał Pierzchała
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Godreamwidth
 
(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven Development(Browser) Acceptance Test Driven Development
(Browser) Acceptance Test Driven DevelopmentFilippo Liverani
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
Javascript testing should be awesome
Javascript testing should be awesomeJavascript testing should be awesome
Javascript testing should be awesomeAbderrazak BOUADMA
 
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Thijs Feryn
 
Web Cache Deception Attack
Web Cache Deception AttackWeb Cache Deception Attack
Web Cache Deception AttackOmer Gil
 
Autotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP BasicsAutotests introduction - Codeception + PHP Basics
Autotests introduction - Codeception + PHP BasicsArtur Babyuk
 
State of the resource timing api
State of the resource timing apiState of the resource timing api
State of the resource timing apiAaron Peters
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
Firefox OS something 201411
Firefox OS something 201411Firefox OS something 201411
Firefox OS something 201411dynamis
 
Your Script Just Killed My Site
Your Script Just Killed My SiteYour Script Just Killed My Site
Your Script Just Killed My SiteSteve Souders
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance SnippetsSteve Souders
 
Debugging PHP With Xdebug
Debugging PHP With XdebugDebugging PHP With Xdebug
Debugging PHP With XdebugMark Niebergall
 

Was ist angesagt? (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
 

Andere mochten auch

PHP And Silverlight - DevDays session
PHP And Silverlight - DevDays sessionPHP And Silverlight - DevDays session
PHP And Silverlight - DevDays sessionMaarten Balliauw
 
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 cloudyMaarten 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 meetingMaarten 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 AzureMaarten Balliauw
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCMaarten Balliauw
 

Andere mochten auch (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
 

Ähnlich wie 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 JavaScriptjeresig
 
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'08kingsfleet
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend TestingNeil 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 AjaxChristian 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 Developmentwolframkriesing
 
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.TestingJohn.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 QualityAtlassian
 
Ajax Tutorial
Ajax TutorialAjax Tutorial
Ajax Tutorialoscon2007
 
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.V5John.Jian.Fang
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
iPhone Development For Experienced Web Developers
iPhone Development For Experienced Web DevelopersiPhone Development For Experienced Web Developers
iPhone Development For Experienced Web Developerslisab517
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsGavin Pickin
 
Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingFITC
 
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 DebuggingRami Sayar
 
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 FrameworksViraf 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 OnAtlassian
 

Ähnlich wie 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
 
Here Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript DebuggingHere Be Dragons – Advanced JavaScript Debugging
Here Be Dragons – Advanced JavaScript Debugging
 
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
 
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
 

Mehr von 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.pptxMaarten 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 SpaceMaarten 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 SearchMaarten 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 PolandMaarten 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 - dotNetCologneMaarten 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 laneMaarten 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 throttlingMaarten 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 .NETMaarten Balliauw
 
VISUG - Approaches for application request throttling
VISUG - Approaches for application request throttlingVISUG - Approaches for application request throttling
VISUG - Approaches for application request throttlingMaarten Balliauw
 

Mehr von 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
 

Kürzlich hochgeladen

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 

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