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