Wednesday 21 April 2010

NUnit Part 5: Mocks, Fakes and Stubs

So we've finally reached the penultimate post in the NUnit series. So far I've discussed

1. The importance of TDD and unit testing,
2. Introduced a free C# testing framework (NUnit),
3. Shown how to simplify tests using set up/tear down code, and
4. Discussed the importance of interfaces and dependency injection.

This is actually the last post on coding tests, as the final post demonstrates how to add a shortcut to run our tests to Visual C# Express. So what's left? Well as the title and frequent references in the last post might have given away, the wonderful world of mocking.

We saw in the last post that we should always supply any objects a class might need via its constructor (or some other method), rather than have the class make them itself. But that means that in order to test a class, we might need to pass in multiple objects which in turn would require multiple objects and so on. So, to save writing a whole heap of extra code, we create alternate versions of the required objects.

If we want to test an object based on another objects response, we can create a stub/fake. This is a greatly simplified alternate version that returns preset responses rather than performing calculations. A good example would be if a class requires a random number generator. We can create a stub that returns the values we require for our tests.

Alternatively, if we want to test how objects interact, we can setup some expectations. Typically these take the form of:

1. Requiring that a method is called with certain arguments, or
2. Requiring a method is called a certain number of times (possibly zero).

At the end of our test, we can then verify (see Assert) that the expectations were met. In these cases, we should use a mock. These involve a lot more code than creating a simple stub. But isn't that a "whole heap of extra code". Well, that depends. Not if we use some automated mocking tools!

There are a number of such tools available for free. NUnit includes a dll for mocking, but you should also check out Rhino.Mocks and Moq. We'll be focusing on NUnit, but the others are both excellent. I personally prefer Rhino.Mocks as I find it slightly more powerful, but the choice is up to you.

So how do we create mock objects with NUnit?

Still a work in progress...

No comments:

Post a Comment