ASP.NET MVC Controller Unit Testing - Problem with

2020-08-09 10:23发布

Trying to do some controller unit-testing in my ASP.NET MVC 3 web application.

My test goes like this:

[TestMethod]
public void Ensure_CreateReviewHttpPostAction_RedirectsAppropriately()
{
   // Arrange.
   var newReview = CreateMockReview();

   // Act.
   var result = _controller.Create(newReview) as RedirectResult;

   // Assert.
   Assert.IsNotNull(result, "RedirectResult was not returned");
}

Pretty simple. Basically testing a [HttpPost] action to ensure it returns a RedirectResult (PRG pattern). I'm not using RedirectToRouteResult because none of the overloads support anchor links. Moving on.

Now, i'm using Moq to mock the Http Context, including server variables, controller context, session, etc. All going well so far.

Until i've hit this line in my action method:

return Redirect(Url.LandingPageWithAnchor(someObject.Uri, review.Uri);

LandingPageWithAnchor is a custom HTML helper:

public static string LandingPageWithAnchor(this UrlHelper helper, string uri1, string uri2)
{
   const string urlFormat = "{0}#{1}";

   return string.Format(urlFormat,
                helper.RouteUrl("Landing_Page", new { uri = uri1}),
                uri2);
}

Basically, i redirect to another page which is a "landing page" for new content, with an anchor on the new review. Cool.

Now, this method was failing before because UrlHelper was null.

So i did this in my mocking:

controller.Url = new UrlHelper(fakeRequestContext);

Which got it further, but now it's failing because the route tables don't contain a definition for "Landing_Page".

So i know i need to mock "something", but im not sure if it's:

a) The route tables
b) The UrlHelper.RouteUrl method
c) The UrlHelper.LandingPageWithAnchor extension method i wrote

Can anyone provide some guidance?

EDIT

This particular route is in an Area, so i tried calling the area registration in my unit test:

AreaRegistration.RegisterAllAreas();

But i get an InvalidOperationException:

This method cannot be called during the application's pre-start initialization stage.

3条回答
对你真心纯属浪费
2楼-- · 2020-08-09 10:28

There is a constructor for UrlHelper that takes a RouteCollection as a second argument. If you have the default setup that MVC creates for you, then I think this should work for you:

var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);

controller.Url = new UrlHelper(fakeRequestContext, routes);

An alternative is to modify how your application starts up to make things a little easier to test and work with. If you define and interface like this:

public interface IMvcApplication
{
    void RegisterRoutes(RouteCollection routes);
    // Other startup operations    
}

With an implementation:

public class MyCustomApplication : IMvcApplication
{
    public void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        // Your route registrations here
    }

    // Other startup operations
}

Then you can modify your Global.asax like this:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        var app = new MyCustomApplication();
        app.RegisterRoutes(RouteTable.Routes);
        // Other startup calls
    }
}

And still have the flexibility to register your routes for testing. Something like this:

private IMvcApplication _app;
private RouteCollection _routes;

[TestInitialize]
public void InitializeTests()
{
    _app = new MyCustomApplication();

    _routes = new RouteCollection();
    _app.RegisterRoutes(_routes);
}

This can be similarly leveraged to work with area registrations as well.

private RouteCollection _routes;
private MyCustomAreaRegistration _area;

[TestInitialize]
public void InitTests()
{
    _routes = new RouteCollection();
    var context = new AreaRegistrationContext("MyCustomArea", _routes);

    _area.RegisterArea(context);
}
查看更多
看我几分像从前
3楼-- · 2020-08-09 10:37

Because this is a test, your test suite is most likely not reading the Global.asax like you may be expecting.

To get around this, do what @ataddeini suggested and create a route collection. To this collection, add in a new route, which will look like...

var routes = new RouteCollection();
routes.Add(new Route("Landing_Page", new { /*pass route params*/}, null));
var helper = new UrlHelper(fakeRequestContext, routes);
查看更多
Deceive 欺骗
4楼-- · 2020-08-09 10:47

Got it working by mocking the HttpContext, RequestContext and ControllerContext, registering the routes then creating a UrlHelper with those routes.

Goes a little like this:

public static void SetFakeControllerContext(this Controller controller, HttpContextBase httpContextBase)
{
    var httpContext = httpContextBase ?? FakeHttpContext().Object;
    var requestContext = new RequestContext(httpContext, new RouteData());
    var controllerContext = new ControllerContext(requestContext, controller);
    MvcApplication.RegisterRoutes();
    controller.ControllerContext = controllerContext;
    controller.Url = new UrlHelper(requestContext, RouteTable.Routes);
}

FakeHttpContext() is a Moq helper which creates all the mock stuff, server variables, session, etc.

查看更多
登录 后发表回答