Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate UrlHelper for a Controller Unit Test in Asp.Net Core 2.0

I am writing unit tests for my Asp.Net Core 2.0 controllers. Each controller is injected with an IUrlHelper service to facilitate creating Hateoas links. This service is registered in the ConfigureServices method in the Startup class. Here a snapshot of my Startup class:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        services.AddScoped<IUrlHelper, UrlHelper>(implementationFactory =>
        {
            var actionContext = 
                implementationFactory.GetService<IActionContextAccessor>()
                .ActionContext;
            return new UrlHelper(actionContext);
        });
    }
}

Sample Controller:

using Microsoft.AspNetCore.Mvc;

public class MyApiController : Controller
{
    private readonly IUrlHelper _urlHelper;

    public MyApiController(IUrlHelper urlHelper)
    {
        _urlHelper = urlHelper;
    }

    // At least 5 actions and each requires _urlHelper to create Hateoas links
}

Where I am stuck is I don't know how to initialize the UrlHelper class inside an unit test class.

What I have tried so far:


Mocking UrlHelper

I found this article, but I prefer to not mock the UrlHelper service and instead initialize it for the real API under test, because mocking requires too much effort to write out all mocked paths. The effort to test my whole API would be number of controllers * number of actions * number of links per action.

Starting a TestServer

I found this MS article on creating a TestServer. However, this would already be an integration test and I would like to stick to unit testing as long as possible. If there is no way to avoid starting a test server, which I am currently playing around with, then I don't know how to get an instance of UrlHelper from the test server.


Is there any way to get an instance of UrlHelper for the API under test in my test classes, preferably without starting a test server, and if the test server is unavoidable, how do I get the UrlHelper instance from the test server?

like image 277
philipp-fx Avatar asked Jan 25 '26 12:01

philipp-fx


1 Answers

  1. You do not need to inject the UrlHelper in your constructor. ControllerBase.Url already contains the UrlHelper.
  2. Extract your hateoas builders into seperate classes that take a IUrlHelper, that will lower the complexity of your controller actions and make unit testing easier
  3. Create a stub IUrlHelper for unit testing your hatoas builders. It's rather easy to stub.
like image 117
Martin Avatar answered Jan 27 '26 02:01

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!