SlideShare a Scribd company logo
1 of 28
Download to read offline
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
Mocking - Visug session
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 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
 

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

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

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.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
 

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

SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.IPLOOK Networks
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Muhammad Tiham Siddiqui
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024Brian Pichman
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch TuesdayIvanti
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3DianaGray10
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 

Recently uploaded (20)

SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch Tuesday
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 

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
  • 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