Mocking indexed properties with Moq

A coworker of mine (who just got back from the Microsoft MVP events in Seattle, congrats, Matt!) has turned me on to using Moq, which I must say is an impressive mocking framework that has made unit testing notably easier.

Recently I had the need to mock the IRequest interface of the Castle MonoRail framework – specifically, two properties: the indexed property and the QueryString property, both of which expose a NameValueCollection.

I found some guidance on mocking the indexed property via Stack Overflow, which turned me on to the following solution.

var request = new Mock<IRequest>();
request.ExpectGet(r => r[It.Is<string>(x => x == "someName")]).Returns("someValue");

To mock the QueryString property took a different approach: create a NameValueCollection, add my test data to it, and wire the collection to the mocked object.

var request = new Mock<IRequest>();
var query = new NameValueCollection();
query.Add("someName", "someValue");
request.ExpectGet(r => r.QueryString).Returns(query);

With this, I can now pass my mocked IRequest to other classes, which will be able to access the following:

request["someName"] = "someValue";
request.QueryString["someName"] = "someValue";

In all, it makes unit testing web requests a lot easier!

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>