Trying to create a URLHelper for testing purposes with the help of ActionContext() throws a NullReferenceException.
Steps to reproduce the behavior:
Throws Message: System.NullReferenceException : Object reference not set to an instance of an object.
Bug report can also be found on StackOverflow:
https://stackoverflow.com/questions/54199103/trying-to-test-a-controller-with-a-urlhelper
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.