What a Moqery…

Every new technology that comes into a developer’s hand goes through a so called “honeymoon period”. I’ve been hooked onto Moq these days. I am quite sure down the line, few years pass by and I shall be using something more "usable” than Moq and would consider that as my best mocking tool. But that is just another page in a developer’.

Back to the meat of this blog, the other day I was mocking certain classes for writing some behavioural tests. There was a reason to mock certain properties of a class. For Moq to mock the property it has to be marked as virtual. Ideally, I would have it part of an interface that can be mocked with Moq. But that is a different topic all together. To put forward my point, look at the below code snippet of a pretty dumb method “DeReplace”. All it does is for the string stored in BarProperty, it replaces ‘a’ with ‘@’.

private string bar;
public virtual string BarProperty { get { return bar; }set { bar = value; } }

public string DoReplace()
{
if(String.IsNullOrEmpty(bar))
{
throw new InvalidOperationException("The bar string cannot be null or empty.");
}
return bar.Replace('a', '@');
}


One heck of a useful method eh! This is a test for the above method using Moq,



[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
mockBar.SetupGet(x => x.BarProperty).Returns("skadoosh!!!");
var result = mockBar.Object.DoReplace();
Assert.AreEqual("sk@doosh!!!", result);
}


Did it work. Of course not. It resulted in the InvalidOperationException and the assertion failed. Why? We did setup the BarProperty correctly with Moq, but what are we using in our original method? We are using bar string. This does bring back the discussion whether to use properties for local usages or just use local member variables. I shall leave that discussion for StackOverflow, but one thing is pretty clear. If you intend to mock properties for a class, you better use them in your methods. Below is the changed class to make the test work,



private string bar;
public virtual string BarProperty { get { return bar; }private set { bar = value; } }

public string DoReplace()
{
if(String.IsNullOrEmpty(BarProperty))
{
throw new InvalidOperationException("The bar string cannot be null or empty.");
}
return BarProperty.Replace('a', '@');
}

Ahh that green color, sweet.

Happy “Moq”ing.

Abhang Rane


No comments :

Post a Comment

Leave a Comment...