mocking - visug session

28
www.visug.be Mocking Maarten Balliauw – RealDolmen Huizingen http://blog.maartenballiauw.be

Upload: maarten-balliauw

Post on 27-Jan-2015

113 views

Category:

Technology


2 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Mocking - Visug session

www.visug.be

MockingMaarten Balliauw – RealDolmen Huizingen

http://blog.maartenballiauw.be

Page 2: Mocking - Visug session

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

Page 3: Mocking - Visug session

http://blog.maartenballiauw.be

Page 4: Mocking - Visug session

www.visug.be

Agenda

• Unit testing• Dependencies• Mocking frameworks

Page 5: Mocking - Visug session

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!

Page 6: Mocking - Visug session

www.visug.be

Unit testing

• Arrange– Get everything prepared for test

• Act– Execute the code under test

• Assert– Verify everything worked as expected

Page 7: Mocking - Visug session

www.visug.be

Let’s create something…

• Order OrderBeer<T>(int count);– Create an order– Add count beers

Page 8: Mocking - Visug session

www.visug.be

DEMOOur example, the TDD way

Page 9: Mocking - Visug session

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

Page 10: Mocking - Visug session

www.visug.be

Do I really want to test these?

• Weather web service• Kitchen ordering system• Nut distributor machine

Page 11: Mocking - Visug session

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

Page 12: Mocking - Visug session

www.visug.be

DEMOCreating some fake implementations

Page 13: Mocking - Visug session

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

Page 14: Mocking - Visug session

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)

Page 15: Mocking - Visug session

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

Page 16: Mocking - Visug session

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

Page 17: Mocking - Visug session

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/

Page 18: Mocking - Visug session

www.visug.be

DEMOUsing Moq

Page 19: Mocking - Visug session

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

Page 20: Mocking - Visug session

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

Page 21: Mocking - Visug session

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

Page 22: Mocking - Visug session

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");

Page 23: Mocking - Visug session

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

Page 24: Mocking - Visug session

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!

Page 25: Mocking - Visug session

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!

Page 26: Mocking - Visug session

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

Page 27: Mocking - Visug session

www.visug.be

Questions and Answers

Page 28: Mocking - Visug session

www.visug.be

THANK YOU!Make sure to check http://blog.maartenballiauw.be