Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 891311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T13:52:11+00:00 2026-05-15T13:52:11+00:00

I’m trying to write a test for an UrlHelper extensionmethod that is used like

  • 0

I’m trying to write a test for an UrlHelper extensionmethod that is used like this:

Url.Action<TestController>(x => x.TestAction());

However, I can’t seem set it up correctly so that I can create a new UrlHelper and then assert that the returned url was the expected one. This is what I’ve got but I’m open to anything that does not involve mocking as well. ;O)

        [Test]
    public void Should_return_Test_slash_TestAction()
    {
        // Arrange
        RouteTable.Routes.Add("TestRoute", new Route("{controller}/{action}", new MvcRouteHandler()));
        var mocks = new MockRepository();
        var context = mocks.FakeHttpContext(); // the extension from hanselman
        var helper = new UrlHelper(new RequestContext(context, new RouteData()), RouteTable.Routes);

        // Act
        var result = helper.Action<TestController>(x => x.TestAction());

        // Assert
        Assert.That(result, Is.EqualTo("Test/TestAction"));
    }

I tried changing it to urlHelper.Action(“Test”, “TestAction”) but it will fail anyway so I know it is not my extensionmethod that is not working. NUnit returns:

NUnit.Framework.AssertionException: Expected string length 15 but was 0. Strings differ at index 0.
Expected: "Test/TestAction"
But was:  <string.Empty>

I have verified that the route is registered and working and I am using Hanselmans extension for creating a fake HttpContext. Here’s what my UrlHelper extentionmethod look like:

        public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> actionExpression) where TController : Controller
    {
        var controllerName = typeof(TController).GetControllerName();
        var actionName = actionExpression.GetActionName();

        return urlHelper.Action(actionName, controllerName);
    }

    public static string GetControllerName(this Type controllerType)
    {
        return controllerType.Name.Replace("Controller", string.Empty);
    }

    public static string GetActionName(this LambdaExpression actionExpression)
    {
        return ((MethodCallExpression)actionExpression.Body).Method.Name;
    }

Any ideas on what I am missing to get it working???
/ Kristoffer

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T13:52:12+00:00Added an answer on May 15, 2026 at 1:52 pm

    The reason it isn’t working is that internally the RouteCollection object calls the ApplyAppPathModifier method on HttpResponseBase. It looks like Hanselman’s mock code does not set any expectations on that method so it returns null, which is why all of your calls to the Action method on UrlHelper are returning an empty string. The fix would be to setup an expectation on the ApplyAppPathModifier method of the HttpResponseBase mock to just return the value that is passed into it. I’m not a Rhino Mocks expert so I’m not completely sure on the syntax. If you are using Moq, then it would look like this:

    httpResponse.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>()))
        .Returns((string s) => s);
    

    Or, if you just use a hand-rolled mock, something like this would work:

    internal class FakeHttpContext : HttpContextBase
    {
        private HttpRequestBase _request;
        private HttpResponseBase _response;
    
        public FakeHttpContext()
        {
            _request = new FakeHttpRequest();
            _response = new FakeHttpResponse();
        }
    
        public override HttpRequestBase Request
        {
            get { return _request; }
        }
    
        public override HttpResponseBase Response
        {
            get { return _response; }
        }
    }
    
    internal class FakeHttpResponse : HttpResponseBase
    {
        public override string ApplyAppPathModifier(string virtualPath)
        {
            return virtualPath;
        }
    }
    
    internal class FakeHttpRequest : HttpRequestBase
    {
        private NameValueCollection _serverVariables = new NameValueCollection();
    
        public override string ApplicationPath
        {
            get { return "/"; }
        }
    
        public override NameValueCollection ServerVariables
        {
            get { return _serverVariables; }
        }
    }
    

    The above code should be the minimum necessary implementation of HttpContextBase in order to make a unit test pass for the UrlHelper. I tried it out and it worked. Hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I know there's a lot of other questions out there that deal with this
I'm trying to create an if statement in PHP that prevents a single post
I have some data like this: 1 2 3 4 5 9 2 6
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.