Some “Moq”ing

I have become a big fan of Moq since I started using it. The reason I like it so much is its ease of use. I have not bothered to learn Rhino Mocks or NMock for that matter coz since I have started using it, its the 3rd team I have joined for a project where they have choosen Moq over all others.

Right, back to work. Did you ever have a requirement where you had to mock some methods of a class and leave out certain methods as is? Consider that following utterly useless classes,

public class Foo
{
public string CallMe()
{
var result = DoSomethingImportant();
return result.ToString();
}
public virtual int DoSomethingImportant()
{
return 10000;
}
}

public class Bar : Foo
{
}

Ya they are pretty dumb I know. The point is this, say you would like to mock the Bar class and test out its CallMe method. This is how it might look,

[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
var result = mockBar.Object.CallMe();
Assert.AreEqual("10000", result);
}

You run this test and you meet this error,

image


The problem here is, you sure have a virtual method in Foo, but there is no overridden implementation provided in Bar. Moq underneath derives from the target class (in this case Bar) and injects its setup implementations for the virtual members as provided. Although, if you intend to leave a method in the base class (Foo) as is, you need to tell Moq to do so. Common it can’t be that smart! To do this, use the “CallBase” property on the mock object. This does exactly what it says and calls the base virtual implementation in case a setup is not matched. Below is the working test for the same,

[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
mockBar.CallBase = true;
var result = mockBar.Object.CallMe();
Assert.AreEqual("10000", result);
}

Now run the test again. I just love when I see that green color, dont you!

Happy Moqing!

Abhang Rane


No comments :

Post a Comment

Leave a Comment...