Getting started with Fake Objects – Part 3: Verify that a call has been made

If you haven’t read the other posts in this trilogy – you might what to have a look at them about now:

  1. Why fake is better then mock
  2. How to create a fake object

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.

The problem at hand

If you remember the code from the previous post we have UserService and we need to create a new user.

image

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

Verify that a call was made

Using Moq we can copy the test from the previous post and change it a bit:

  • UserExist will return false when called (line 5).
  • Verify that the method SaveUser was called (line 12).

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.

Beware of verify

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:

  • Don’t test that method A called method B because a simple refactor will break your test
  • Don’t test that internal (and private) method was called
  • Avoid exact arguments passed to the method unless that’s what you’re testing
  • Only one verify per test please!

As always these are only guidelines – if you write enough tests you’ll know when to follow them

Conclusion

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.