Aspnetcore: Creating a UrlHelper with ActionContext() results in a NullReferenceException

Created on 15 Jan 2019  路  3Comments  路  Source: dotnet/aspnetcore

Describe the bug

Trying to create a URLHelper for testing purposes with the help of ActionContext() throws a NullReferenceException.

To Reproduce

Steps to reproduce the behavior:

  1. Create a empty MVC core 2.2 solution
  2. Create a xunit test Project
  3. Install the NuGet Microsoft.AspNetCore.Mvc.Core 2.2.0
  4. Write in the test: var Url = new UrlHelper(new ActionContext());
  5. Run test

Expected behavior

Throws Message: System.NullReferenceException : Object reference not set to an instance of an object.

Additional context

Bug report can also be found on StackOverflow:
https://stackoverflow.com/questions/54199103/trying-to-test-a-controller-with-a-urlhelper

bug

By Design area-mvc

All 3 comments

What happens here is that the UrlHelper tries to access the RouteData property of the ActionContext to check if it has values on it thus causing the exception. To fix this you can do:

var url = new UrlHelper( new ActionContext{ RouteData = new RouteData() } );

That specific constructor is documented to be used for unit testing, more specifically when the ActionContext simply needs to be passed in, but not used by the consuming code. Setting it up the way @navelDirt suggested would be the way to go.

Going further, if you're intent is to unit test if a piece of code produces a specific url, you're going to have better success using a stub \ mock IUrlHelper. If you need to verify the actual outcome, I'd strongly recommend writing an integration test

Thank you very much @navelDirt and @pranavkm.
I was confused since in core 1.1 it worked without setting the RouteData, but switching to 2.2 it crashed. That's why I thought it was a bug... sorry for the inconvenience.

Was this page helpful?
0 / 5 - 0 ratings