Mocking Base Class Methods with Moq

Moq does allow you to mock base class methods, via the use of the Moq.Protected namespace. You can read about it here.

Imagine you have the following scenario:


class Animal {
private int timesTalked = 0;
public void Talk() {
timesTalked++;
}
}

class Cat {
public void Talk() {
base.Talk();
Console.WriteLine("meow!");
}
}

class CatTest {
public void TalkDoesntThrow() {
var c = new Moq().Setup(c => c.Talk()) ... // Cat.Talk

In this case, you want to test the Cat.Talk method by mocking out the base class method. How can you do this?

At first glance, you can’t, because the signatures match. But, if you can make your base class method protected instead, that gives you breathing room:


class Animal {
protected void Talk() { .. }
}

class CatTest {
public void TalkDoesntThrow() {
var c = new Mock();
c.Protected().Setup("Talk") ... // Animal.Talk
}

If this doesn’t work, you need to change one of the method signatures, like so:


class Cat {
public void Talk(string message) { ... }

The final caveat I noticed is that the mocking is sensitive to the use of the base keyword. It seems like the CLR knows the actual base type and calls that, instead of the one derived from Moq.

That is, in our Cat class, we call base.Talk. Instead of that, we should just invoke Talk.

This affects the runtime binding, since Moq dynamically subclasses our mocked classes.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Web, Wndows Forms, WPF and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *