Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to fake HttpContextBase and pass this to an UrlHelper which you can use in a thread without an HttpContext. Here is the rough idea, although you will need to create a class around it etc, this is a quick proof of concept as unit tests don't have an HttpContext either.</p> <pre><code>[TestFixture] public class RouteTestClass { private UrlHelper helper; public RouteTestClass() { MvcApplication.RegisterRoutes(RouteTable.Routes); //You dont need to do this if its done in global.asax! var c = new RequestContext(new FakeContext(), new RouteData()); helper = new UrlHelper(c, RouteTable.Routes); } [Test] public void TestGetHomeIndex() { var url = helper.Action("Index", "Home"); Assert.AreEqual("/",url); } } public class FakeContext : HttpContextBase { public override HttpRequestBase Request { get { return new FakeRequest(); } } public override HttpResponseBase Response { get { return new FakeResponse(); } } } public class FakeRequest : HttpRequestBase { public override string ApplicationPath { get { return "/"; } } public override NameValueCollection ServerVariables { get { return new NameValueCollection(); } } } public class FakeResponse : HttpResponseBase { public override string ApplyAppPathModifier(string virtualPath) { return virtualPath; } } </code></pre> <p><strong>Edit</strong></p> <p>Looking at <a href="https://stackoverflow.com/questions/2031995/call-urlhelper-in-models-in-asp-net-mvc/2032257#2032257">this</a> answer, I tidied the code up a little as I don't need to create fakes for HttpRequestBase and HttpResponseBase myself.</p> <pre><code>[TestFixture] public class RouteTestClass { private UrlHelper helper; public RouteTestClass() { MvcApplication.RegisterRoutes(RouteTable.Routes); var req = new HttpRequest("/", "http://www.yoururl.com", ""); var resp = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(req, resp); var c = new RequestContext(new HttpContextWrapper(httpContext), new RouteData()); helper = new UrlHelper(c, RouteTable.Routes); } [Test] public void TestGetHomeIndex() { var url = helper.Action("Index", "Home"); Assert.AreEqual("/",url); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload