Successfully reported this slideshow.

Mocking - Visug session

3,821 views

Published on

Session on mocking delivered at VISUG - Visual Studio user Group Belgium - www.visug.be

Published in: Technology
  • Be the first to comment

Mocking - Visug session

  1. 1. Mocking Maarten Balliauw – RealDolmen Huizingen http://blog.maartenballiauw.be www.visug.be
  2. 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. 3. Agenda • Unit testing • Dependencies • Mocking frameworks www.visug.be
  4. 4. 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
  5. 5. Unit testing • Arrange – Get everything prepared for test • Act – Execute the code under test • Assert – Verify everything worked as expected www.visug.be
  6. 6. Let’s create something… • Order OrderBeer<T>(int count); – Create an order – Add count beers www.visug.be
  7. 7. Our example, the TDD way DEMO www.visug.be
  8. 8. 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
  9. 9. Do I really want to test these? • Weather web service • Kitchen ordering system • Nut distributor machine www.visug.be
  10. 10. 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
  11. 11. Creating some fake implementations DEMO www.visug.be
  12. 12. 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
  13. 13. 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
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. Using Moq DEMO www.visug.be
  18. 18. 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
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. Questions and Answers www.visug.be
  27. 27. Make sure to check http://blog.maartenballiauw.be THANK YOU! www.visug.be

×