Hello,
I'm trying to mock a controller.ControllerContext and everything is working until the system tries to GetDisplayMode on the context. Since it is null, it blows up.
Here are two functions, the first creates the controller and the second uses the controller and blows up.
Any help would be appreciated!
Lee
And here I am trying to use it to generate the output of a view:
I'm trying to mock a controller.ControllerContext and everything is working until the system tries to GetDisplayMode on the context. Since it is null, it blows up.
Here are two functions, the first creates the controller and the second uses the controller and blows up.
Any help would be appreciated!
Lee
private
static
LogonController CreateLogonController()
{
var controller =
new
LogonController();
var response = Mock.Create<HttpResponseBase>();
var httpContext = Mock.Create<HttpContextBase>();
var routeData =
new
RouteData();
var request = Mock.Create<HttpRequestBase>();
var cookies =
new
HttpCookieCollection();
var context =
new
ControllerContext(httpContext, routeData, Mock.Create<ControllerBase>());
var browser = Mock.Create<HttpBrowserCapabilitiesBase>();
response.Output =
new
StringWriter();
Mock.Arrange(() => browser.IsMobileDevice).Returns(
false
);
Mock.Arrange(() => request.Cookies).Returns(cookies);
Mock.Arrange(() => request.ValidateInput());
Mock.Arrange(() => request.UserAgent).Returns(
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"
);
Mock.Arrange(() => request.Browser).Returns(browser);
Mock.Arrange(() => response.Cookies).Returns(cookies);
Mock.Arrange(() => httpContext.Request).Returns(request);
Mock.Arrange(() => httpContext.Response).Returns(response);
routeData.Values.Add(
"controller"
,
"LogonController"
);
routeData.Values.Add(
"action"
,
"Index"
);
controller.ControllerContext = context;
return
controller;
}
And here I am trying to use it to generate the output of a view:
public
static
class
ApiExtensionMethods
{
public
static
string
Render(
this
ViewResult result, Controller controller)
{
controller.ViewData.Model = result.Model;
try
{
using
(var sw =
new
StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, result.ViewName);
var context =
new
ViewContext(controller.ControllerContext, viewResult.View, result.ViewData, result.TempData, sw);
viewResult.View.Render(context, sw);
return
sw.GetStringBuilder().ToString();
}
}
catch
(Exception e)
{
return
e.ToString();
}
}
}