I need some help here, how do I easily test my controller?
If you have ever tried to test any of the framework aspects of a controller, such as making sure the response code is a 404, you probably know that it's not as easy as you had hoped. The following is a base class that I have created that I use in my testing to set up all of the dependencies using Rhino Mocks. In addition to this it is necessary to create a "Testable" version of your controller, of which I have an example bellow.
Test Base Class
public class ControllerBaseTester
{
protected readonly IBlogConfiguration Configuration = MockRepository.GenerateStub<IBlogConfiguration>();
protected readonly HttpContextBase HttpContext = MockRepository.GenerateStub<HttpContextBase>();
protected readonly RouteData RouteData = new RouteData();
protected readonly RequestContext Context;
protected readonly StringBuilder ResponseString = new StringBuilder();
protected readonly TextWriter ResponseWriter;
protected readonly HttpResponseBase Response;
public ControllerBaseTester()
{
ResponseWriter = new StringWriter(ResponseString);
Response = new HttpResponseWrapper(new HttpResponse(ResponseWriter));
HttpContext.User = Test.AuthorizedUser;
HttpContext.Expect(x => x.Response).Return(Response);
Context = new RequestContext(HttpContext, RouteData);
Configuration.Stub(x => x.Configuration).Return(Test.Configuration);
}
}
Creating a Testable Controller
class TestableController : BlogController
{
TestableController(IBlogService blogService, IBlogConfiguration configuration)
: base(blogService, configuration)
{
}
private void Init(RequestContext context)
{
Initialize(context);
}
public static BlogController Create(RequestContext context, IBlogService blogService, IBlogConfiguration configuration)
{
var result = new TestableController(blogService, configuration);
result.Init(context);
return result;
}
}
Tuesday, February 02, 2010
Comments
blog comments powered by Disqus