If you haven’t read the other posts in this trilogy - you might what to have a look at them about now:
Let’s begin the third part of this tutorial where I’ll explain what to do when we need to test that a method has been called.
If you remember the code from the previous post we have UserService and we need to create a new user.
In the last post I’ve explained how to fake the UserRepository so it will return the value we want – this time we want to test that if the user is valid SaveUser is called.
Luckily for us that is a what Isolation (mocking) framework does well. I’ll explain how this can be done using Moq and Typemock Isolator
Using Moq we can copy the test from the previous post and change it a bit:
And that’s it. Using Isolator the test will look something like this:
You might have noticed that I don’t really care what arguments are passed to the SaveUser method – for a good reason which I’ll explain about now.
Now that you know how to verify that a method was called you should be aware of the issues that could happen when you misuse it.
Other then the fact that verify is very similar to Assert – it helps us check that a condition was met. And as such the same rules that effect assertions when writing tests apply to verify as well. Other then that you need to be careful of what you check in your test:
As always these are only guidelines – if you write enough tests you’ll know when to follow them
This post is the last in my three part tutorial on how to start using fake objects when writing unit testing (at least until I find more topics to write about). Of course there is more to learn about Isolation frameworks and fake objects but I hope that this tutorial is just enough to get you started.
Good luck and happy coding
Labels: Mock objects, Unit tests