Quantcast
Channel: Platform – C# City
Viewing all articles
Browse latest Browse all 16

Mocking Base Class Methods with Moq

$
0
0

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<Cat>().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<Cat>();
    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.


Viewing all articles
Browse latest Browse all 16

Trending Articles