I'm attempting to unit test some code using NUnit. I have a method:
public static string RenderRoute(HttpContextBase context, RouteValueDictionary values)
{
var routeData = new RouteData();
foreach (var kvp in values)
{
routeData.Values.Add(kvp.Key, kvp.Value);
}
string controllerName = routeData.GetRequiredString("controller");
var requestContext = new RequestContext(context, routeData);
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
var ActionInvoker = new ControllerActionInvoker();
var controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
((ControllerBase)controller).ControllerContext = controllerContext;
string actionName = routeData.GetRequiredString("action");
Action action = delegate { ActionInvoker.InvokeAction(controllerContext, actionName); };
return new BlockRenderer(context).Capture(action);
}
My default controllerfactory is a StructureMap controller factory from MvcContrib. I'm also using the MvcMockHelpers from MvcContrib to help me mock the HttpContextBase.
The controller I am attempting to test calls the above RenderRoute method and blows up at:
IController controller = factory.CreateController(requestContext, controllerName);
With the error:
Controllers.WidgetControllerTests.CanCreateWidgetOnPage: System.Web.HttpException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception. ----> System.TypeInitializationException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception. ----> System.NullReferenceException : Object reference not set to an instance of an object.
I'm fairly new to unit testing/mocking and it's a possibility I'm not seeing something simple.
Here is the test I'm currently running:
[Test]
public void Test()
{
HttpContextBase context = MvcMockHelpers.DynamicHttpContextBase();
string s = RenderExtensions.RenderAction<HomeController>(context, a => a.About());
Console.WriteLine(s);
Assert.IsNotNullOrEmpty(s);
}
Any help would be appreciated.
I have simplified the problem down to this simple unit test:
[Test]
public void Test2()
{
HttpContextBase context = MvcMockHelpers.DynamicHttpContextBase();
var routeData = new RouteData();
routeData.Values.Add("Controller", "Home");
routeData.Values.Add("Action", "About");
string controllerName = routeData.GetRequiredString("controller");
var requestContext = new RequestContext(context, routeData);
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
Assert.IsNotNull(controller);
}