Basic Introduction to writing unit tests with Moq - Part 3

This post is the third part of a series on Mocking with Moq. If you haven't already taken a look at the first two posts on the basics of Moq, please check it out.

Moq Same Class

Mocking a method within the same class

So, recently I came across a problem where I had a method on a class that I needed to mock its return value. It had no interface and I wasn't sure if there was a way to mock it. Fortunately there is a way - and it's pretty easy to do! Let's take a look.

In the previous articles that we have looked at, we wrote a few tests for a simple eCommerce Basket (Cart) system. In this example we are taking a look at a very simple method that calls another method to get the Geolocation details of an IP address. If you would like to know more about this Geolocation service - please check out the article on Scott Hanselman's blog.

We don't want to call the 3rd party service every time we run our tests, so we need to mock out the return value. In this instance our method doesn't have a matching interface.

Moq Same Class

In the above method we pass in the basket object and an IP Adress that we need to find out the details for. Previously, I would have done this using an Interface - but for the purpose of this example let's say there is no Interface. Where previously we would have mocked the Interface we now need to mock the class under test.

In our setup we now mock the Class instead of the Interface.

Moq Same Class Setup

There are still a few more things that need to be done in order to get this to work. The method that we are calling needs to made virtual and we need to use the CallBase property on the Mock. The Callbase property is a boolean and decides whether or not to call the base member virtual implementation.

Moq Same Class

And update the method signature to virtual.

Moq Same Class

Then we put it all together.

Moq Same Class

If you run through this test you will now see that the same class will return a mock value. I've put together this example on top of the code that came with the first two posts and can be downloaded here.