Testing the Untestable in .NET without a mocking framework

When trying to test code that uses the MVC framework and it’s libraries that do not have interfaces, the best way I’ve come across is something I was show during my time at Esendex by @aplea.

Put a wrapper round it!

If you create a new object, which has an interface, and passes in your object that you want to ensure you’ve called (in a nice, shy, OO kind of fashion) into the constructor. This class can’t really be tested, HOWEVER, all the things that were previously using your untestable object can now call this! You can use the nice self shunt pattern to ensure calls have been made.

Enjoy!

Example:

public class MvcHttpMessage : IHttpMessage
{
private readonly HttpApplication _httpApplication;

public MvcHttpMessage(HttpApplication httpApplication)
{
_httpApplication = httpApplication;
}

public string AbsoluteUri()
{
return _httpApplication.Request.Url.AbsoluteUri;
}

public void UpdateStatus(string status)
{
_httpApplication.Response.Status = status;
}

public void UpdateStatusCode(int statusCode)
{
_httpApplication.Response.StatusCode = statusCode;
}

public void AddHeader(Header header)
{
_httpApplication.Response.AddHeader(header.Name, header.Value);
}

public void EndResponse()
{
_httpApplication.Response.End();
}
}

What did you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s