
Hi everyone, my name is Andrew and this talk will be about unit testing in general, and mocking in particular.
Traditionally, unit testing means verifying a piece of code in isolation – and in real life it’s kind of a hard thing to do, because, you know, components communicate with each other, your methods call other methods, create objects, fire events... So testing something in isolation becomes a difficult task.
And that’s where mocking comes to rescue. And I have a question for you: how many people in this room actually use any kind of mocking in their tests? [Some 60% raised hands.] Ok, cool, quite a few.
And how many write unit tests? [About 90% raised hands.] Wow, that's great!

But before digging into details of how to use mocking, I’d like to talk a little bit about why you might want to do that.

And the root of all problems is dependencies. Everything depends on something else, the method you test most likely calls other methods, and if you don't isolate your dependencies, then a test failure could actually be a bug in some other place.
So there may be false negatives in the tests: a test fails, it’s not a bug in your code, but you still need to spend time investigating this.
On the other hand, if you mock out other components, bugs in those components don’t affect your tests. You simply tell – hey, if this method is called asking for a list of customers from the database, then return this hardcoded list, or, say, if that method is called to send out emails then don’t send anything, just skip it, and so on.
By isolating dependencies you don’t test, you make sure that a failure in a test would certainly mean a bug in your code.

...and tests become faster. If you verify the code that eventually writes to a database or reads from a file, or if you need to verify some UI code but it gets its data from a service tier, anything like that – such tests are usually slow.
Get a few hundreds of them, and they can easily make you not running unit tests before every checkin, just because it takes so much time.
But if you use mocking, you isolate everything you don’t test. You hoodwink your System Under Test into thinking it's still writing to a file or retrieving data from another layer, while in fact it would communicate with fake objects. And they would either skip calls or return some predefined things. And it would give you fast tests.

Then, you can test scenarios that are hard to reproduce. Perhaps you want to make sure the application will not crash in case of OutOfMemoryException. Or maybe you need to test how your code behaves if network is not available. All stuff like that. With mocking, it's easy – you set up a mock which throws SomethingBadHappenedException and then make sure the code handles it gratefully.
You no longer need to unplug your computer to test how your program would work if there’s no internet. Such a relief! Instead, you set up a mock that throws TimeoutException or something and use it in your test. So, without much effort, mock objects allow you to test scenarios that, well, rarely happen in real life.

And, finally, you can test incomplete solutions.
That's a common scenario: you are crafting a piece of code that needs to interact with someone elses code, everything is being developed in parallel. Or, one team is writing a component, another team is writing another one, and proper testing can be done only when both are finished.
With mocking you can test just your own part, and you don’t need to wait for another team. You just say: if my code calls this guy then return this hardcoded data, or do nothing, or throw an exception... And then you can test your code as like that another component had already been written.

So, mocking is about decoupling the System Under Test from its dependencies, to get all those benefits you see on the slide.
You have fast tests because the code you test doesn't really talks to a database or calls other tier. Instead, such calls are either ignored or predefined data gets returned.
You don't have dependencies, and so you don't spend time chasing test failures that happen because of bugs in other components. Your tests find bugs in your code, not elsewhere.
You no longer depend on other teams or other people even if your code will finally use their components - everybody can fully test their own code without waiting for others.
And you can test scenarios that rarely happen in real life.

As I said, in order to isolate your code from some dependency, you create a special object that would imitate that dependency. Such object, surprisingly, is called mock object and there’s a great article on Wikipedia, if you’re new to mocking this is probably the place where you should start.
There's a nice example on that page: imagine an alarm clock app which causes a bell to ring at 7am, and imagine it gets the current time from some DateTimeProvider. To test such program, the test must wait until 7 in the morning and then verify if the bell had actually rung. But you use a mock instead of the real time provider, such mock can be set up to always tell, "Now it’s 7 am" and in this case the alarm clock program can be tested in isolation. The test no longer depends on the time.

So, as now we know where to find all theory, let’s look at mocking on .NET.
There are several mocking frameworks available and I picked up five of them that look most promising. Here on the slide, the sizes of the logos kind of correlate with the amount of users each framework has. Rhino Mocks is the most popular one, almost 50% of all people that use any kind of mocking, use Rhino. Then goes Moq with about 30%, and then go other frameworks.
They’re all different, some are open source and some are not, most are free but one is quite not free, some are more powerful than others, they use different approaches for calls interception, they have different syntaxes – and what we’re going to do now is to look and compare all of them. Compare the APIs, look at how they work internally, look at things that some frameworks can do while others cannot.

So we’re going to start with a simple, real life example that is touching a hot cooker.
Here on the slide you see the code and a use case scenario. So you touch a cooker and if it appears to be hot, BurnException gets thrown by your hand, and then you scream. Sounds kind of simple, eh?
But in fact it’s a really complicated scenario with a lot of dependencies.

Just imagine how complicated it is. If there’s someone in the room who knows anatomy well, feel free to correct me, but basically it works like that.
Your body is crammed with special receptors called nociceptors for stuff like pain. So, you’ve touched the hot cooker and high temperature gets detected by thermal nociceptors, they emit electrical signals that go from the hand up to the spinal cord and then divide. One part retraces to jerk back the hand. Another part goes further up to a
special zone of the brain where the signal gets analyzed, you identify the problem, another signal goes to your mouth and you scream.
But, in fact, what we need to test is that when BurnException gets thrown, mouth.Scream really gets called. So let's open up Visual Studio and write this test with all those mocking frameworks.
NMock2.
We'll be using the Arrange-Act-Assert approach in writing unit tests. "Arrange" block is for setting up expectations, "act" block would contain the code to test, and the last one, "assert" block, is to validate our assumptions.
[Test]
public void ShouldScreamIfBurned()
{ //arrange
//act
//assert
}
Normally I don't put comments like that, they're here just to make the presentation more clear. So, first off we need to create Mockery which is the factory for our mocks of hand and mouth, and then set up expectations.
[Test]
public void ShouldScreamIfBurned()
{ //arrange
var mockery = new Mockery();
var hand = mockery.NewMock<Hand>();
var mouth = mockery.NewMock<Mouth>();
Expect.On(hand).Method("Touch").Will(Throw.Exception(new BurnException())); Expect.On(mouth).Method("Scream");
//act
//assert
}
[After the talk I got a question, what had I used for fast typing – not surprisingly it was R# and its Live Templates. There will be an example at the very bottom of the page.]
The API has one single root, Expect. As soon as you remember this call you become a master of NMock2. (Of course, it's open source so you can look at the code anytime, or even change it.)
Another neat thing is that our C# reads like prose now: "expect on hand (that) method Touch will throw exception". If you're an architect, an API designer, you'd certainly appreciate this approach. Anyone can easily read such code over the phone.
Such APIs heavily employ the idea of Fluent Interfaces. Methods aren't usually void there, they return either this or some new types, to allow call chaining where one method may call another one which in turn may call something else and so on.
Again, while designing normal APIs we tend to name methods as descriptive as possible: "GetCustomer" or "UpdateProfile". With fluent APIs, however, this changes: method name no longer needs to be descriptive in itself. It should be descriptive within the whole "sentence", and you're better off naming it as brief as possible, to keep the chains visually short. That's why methods in fluent interfaces are prepositions or short verbs: "On", "For", "Get" and so on.
But let's get back to NMock2 and our test, here's the final version:
[Test]
public void ShouldScreamIfBurned()
{ //arrange
var mockery = new Mockery();
var hand = mockery.NewMock<Hand>();
var mouth = mockery.NewMock<Mouth>();
Expect.On(hand).Method("Touch").Will(Throw.Exception(new BurnException())); Expect.On(mouth).Method("Scream");
//act
var person = new Person(hand, mouth);
person.TouchCooker(new Cooker());
//assert
mockery.VerifyAllExpectationsHaveBeenMet();
}
Bad news about NMock2 is that its expectations are string based. So they're neither type safe, nor refactoring friendly, and you don't have intellisense (unless you use their R# plugin).
However, being string based is a deliberate choice of NMock2 team, and one implication of which is that it makes the framework really fast.
Moq.
Let's look now at Moq now, which is open source as well. [The final version of the test is below.]
[Test]
public void ShouldScreamIfBurned()
{ //arrange
var hand = new Mock<Hand>();
var mouth = new Mock<Mouth>();
hand.Setup(x => x.Touch(It.IsAny<Cooker>())).Throws(new BurnException());
//act
var person = new Person(hand.Object, mouth.Object);
person.TouchCooker(new Cooker());
//assert
mouth.Verify(x => x.Scream());
}
We can easily see the differences.
First off, Moq is type safe: instead of passing method names, we pass lambdas! Under the hood, they get converted to strings anyway, but for us, end users, they're lambdas and compiler will warn you if you're trying to mock a non-existing method or something.
Kind of a drawback of Moq is that you need to append this clumsy .Object if you need to use your mocked objects in the test, as we do here passing them in the constructor. It's because of the C# compiler restriction that doesn't allow you to define conversions to/from interfaces.
Good thing is that tests with Moq are very brief. Compare this one to the one from NMock2: here we don't need to create a mockery, and verification part is placed at the end, which is good since it's a genuine assertion.
Next, as far as you we lambdas, we need to specify parameters, and Moq has an API for parameter matching. (In our test It.IsAny<Cooker> will match the call for any cooker.) This approach has a drawback, as expectations can get really long: think of long type names, esspecially if the method takes several parameters of that sort. Good news is that with Moq you can create a separate method or property and put your matching logic therein. Such methods can be called from more than one test, giving you less verbose and potentially more robust tests:
[Test]
public void ShouldScreamIfBurned()
{ ...
hand.Setup(x => x.Touch(AnyCooker)).Throws(new BurnException());
...
}
private Cooker AnyCooker
{ get { return It.IsAny<Cooker>(); }}
Let's look now at the next option.
Rhino Mocks.
Among the frameworks we review today, Rhino Mocks is the oldest one and therefore has a lot of different (some people even dare call them "legacy") syntaxes. You can solve one problem in many ways which I personally consider a bad thing, because then it's difficult to get a common coding approach across the whole team, esspecially if it's distributed and knowledge sharing gets slower.
But of course as it's open source anyone can look inside to clear up any questions on how it works, or even fix bugs.
[Below is the final version of the test]
[Test]
public void ShouldScreamIfBurned()
{ //arrange
var hand = MockRepository.GenerateStub<Hand>();
var mouth = MockRepository.GenerateMock<Mouth>();
hand.Stub(x => x.Touch(null)).IgnoreArguments().Throw(new BurnException());
//act
var person = new Person(hand, mouth);
person.TouchCooker(new Cooker());
//assert
mouth.AssertWasCalled(x => x.Scream());
}
As you can see, the test looks pretty much the same as the one with Moq - there's a difference in parameter matching API and in method names... So yeah, the only bad thing I can tell about Rhino Mocks is that it's somewhat difficult for a newbie to start using it, because of many APIs, and unfortunately intellisense is polluted because of the way Rhino Mocks defines its extensions.
But once you get over this initial confusion, you'll find that it's a powerful and beautiful framework. Keep in mind though, that there are plans to break backwards compatibility in Rhino Mocks 4.0 and create something completely different (and probably something easier to start working with).
Isolator.
Okay, so let's look at Typemock Isolator which is the only framework that is not free. And surely it's not open source. Obviously it's the most powerful one as well, otherwise nobody would want to pay €800 for it.
Isolator can mock static and non-virtual methods, it can mock DateTime.Now and it can do other cool things that other frameworks cannot. Since they cannot, they invented a "unit testable code" paradigm and some purists are known for eating people alive for using a static class or not marking a method virtual.
I'm kidding. Sort of. Don't get me wrong, I truly believe that writing unit testable code is important. However, it's also important not to become a slave of your tests – and that's where Isolator can be of help.
Let's make a task more difficult. So far, we were passing our mocks in the constructor. Let's imagine now, that it takes no parameters and instead creates the hand and the mouth inside with new operator.
[Test, Isolated]
public void ShouldScreamIfBurned()
{ //arrange
var hand = Isolate.Fake.Instance<Hand>();
var mouth = Isolate.Fake.Instance<Mouth>();
Isolate.WhenCalled(() => hand.Touch(null)).WillThrow(new BurnException());
Isolate.Swap.NextInstance<Hand>().With(hand);
Isolate.Swap.NextInstance<Mouth>().With(mouth);
//act
var person = new Person();
person.TouchCooker(new Cooker());
//assert
Isolate.Verify.WasCalledWithAnyArguments(() => mouth.Scream());
}
In the test above, we say that the next instances of Hand and Mouth, regardless of where they get created, will get swapped with the mocks we provide.
Let's look at mocking of DateTime.Now. The test below will fail with "End Of Time" exception (note that it wouldn't work from R# TestRunner, I think Typemock guys are fixing this now. Try command line with "%ISOLATOR_PATH%\tmockrunner.exe %NUNIT_PATH%\nunit.exe") and point it to the dll with the test:
public class Timer
{ private int _ticks;
public void Tick()
{ if (DateTime.Now == DateTime.MaxValue)
throw new Exception("End of time!");
_ticks++;
}
}
[TestFixture]
public class MockDateTimeTests
{ [Test, Isolated]
public void TestTimer()
{ Isolate.WhenCalled(() => DateTime.Now).WillReturn(DateTime.MaxValue);
var timer = new Timer();
timer.Tick();
}
}
Stubs.
And the last mocking framework for today is called Stubs and it's really amazing. Stubs comes with Pex, which purports to generate tests for you by looking at the code. I woudn't talk about Pex today.. yeah, but Stubs is truly brilliant and I'm saying that not because it comes from Microsoft.
I'm saying that because it takes a completely different approach to mocking. It doesn't provide you with an API. Instead, it generates classes that you can reuse later. [Then I was talking about using Stubs and how it works internally - pretty much the same you can read on my blog. Below goes the final version of the test.]
[Test]
public void MouthShouldScreamIfBurned()
{ //arrange
var hand = new SHand {TouchCooker = (anyCooker) => {throw new BurnException();}}; bool screamed = false;
var mouth = new SMouth {MouthScream = () => { screamed = true; }};
//act
var person = new Person(hand, mouth);
person.TouchCooker(new Cooker());
//assert
Assert.That(screamed, Is.True, "If hand burned, mouth should scream.");
}
And there's another interesting initiative within Pex, which is called Moles. Basically, it's Stubs on steroids, and allows you to mock non-virtual and static methods. Pretty much the same functionality as Isolator has. But free. (Although it's still a very deep Beta, currently 0.19 version is available for download.)
Unfortunately Pex (and thus Stubs/Moles) is not open source, so there's no chance to play with the code.

So we did this small review and now, if you don't use any mocking framework or plan to change the one you're using now, there's a question: which one to choose?
You'd have to decide yourself. If you can afford paying for Isolator, you may want to employ it because of its power. Well, they even provide personal licenses, so if you're a solo developer you can buy it for €90, about 10 times cheaper. Moreover, if you develop open source, you can request a free license.
If you cannot afford or don't want to use Isolator, try Moq. It's extremely easy to catch up with, mainly because it's very young (and thus doesn't have that burden of legacy syntaxes, imposed on others) and also because a lot of work is being done to support and enhance its clear API. Yeah, those guys really care.
Or you can employ NMock2 if you like its API and don't really care about type safety.
Or you can try Rhino Mocks if you aren't afraid of "many ways to do one task".. well, perhaps it's still better to not go for it right now, since they promised to break backwards compatibility soon. But you can wait until 4.0 is out, and I'm pretty sure it will be worth looking at.
Or you can spend some time playing with Pex and mastering Stubs and Moles. Because by the time Pex becomes a real product, it's mocking framework would make a splash. Stay tuned.

I also recommend you to have a look at my pet project, Mocking Frameworks Compare, that contains this very test that we went through today, and also a lot of other tests that outline the differences in syntaxes and compare things like performance and internal error messages. Source code of NMock2, Moq and Rhino Mocks is provided there as a part of the project. No source code for Isolator (which is a paid one, but you can download a 21 day trial) and Pex/Stubs (free but not open source).

So, thank you for your attention, and now - questions!
[There were a bunch of questions but I don't really remember them well... If you think your question and my answer are worth putting here, please drop me a line at andreister | AT |gmail | DOT | com and I'll be glad to add them.
As for the question about fast typing - I was using R# Live Templates, here's an example for NMock2:

The ppt itself is available here.]