www.visug.be
MockingMaarten 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
http://blog.maartenballiauw.be
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
DEMOOur example, the TDD way
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
What I want to test
Dependency
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
DEMOCreating some fake implementations
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
DEMOUsing Moq
www.visug.be
Moq – In the box (1)
• Setup expectations
• Even when parameters are not known!
// Arrange var weatherServiceMock = new Mock<IWeatherService>();weatherServiceMock.Setup(s => s.WhatsTheWeather()) .Returns("sunny");
// 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
• Work with callbacks
// Arrange var pureAlcohol = new Mock<IBeer>();pureAlcohol.Setup(a => a.Drink()) .Throws(new OverflowException());
// Arrange int beerCount;var rochefort10 = new Mock<IBeer>();rochefort10.Setup(b => b.Drink()) .Callback(() => beerCount++) .Returns("Beer nr. " + beerCount);
www.visug.be
Moq – In the box (3)
• Want to mock protected members?// Arrange var mock = new Mock<CommandBase>();mock.Protected() .Expect<int>("Execute") .Returns(5);
www.visug.be
Moq – In the box (4)
• Want automatic mocking? Recursive mocks!
• (this would be a giant stub if we had to write it ourselves…)
// Arrangevar context = new Mock<HttpContextBase>();context.Expect(c => c.Response.ContentType) .Returns("application/xml");
www.visug.be
Moq – In the box (5)
• Verify calls to expectations
• Verify certains calls are made X times// Assert kitchenServiceMock.Verify( k => k.Order(It.IsAny<IConsumable>()), Times.Exactly(1), "Only one piece of cheese");
// Assert weatherServiceMock.VerifyAll(); // checks all Setup() calls
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/archiv
e/category/1062.aspx
www.visug.be
Questions and Answers
www.visug.be
THANK YOU!Make sure to check http://blog.maartenballiauw.be