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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With