ivaylokenov / AspNet.Mvc.TypedRouting

A collection of extension methods providing strongly typed routing and link generation for ASP.NET Core MVC projects.
https://mytestedasp.net/
MIT License
485 stars 36 forks source link

Unit testing #30

Closed svickers closed 7 years ago

svickers commented 7 years ago

Love this library, makes life so much easier. When writing unit tests for any action that uses the extension methods I am running into an issue:

Object reference not set to an instance of an object. at Microsoft.AspNetCore.Mvc.ControllerExtensions.GetExpresionRouteHelper(Controller controller)\n at Microsoft.AspNetCore.Mvc.ControllerExtensions.RedirectToAction[TController](TController controller, Expression`1 action, Object routeValues)\n at insights.headset.io.Controllers.HomeController.d__24.MoveNext() in /Users/scottvickers/dev/insights.headset.io/Controllers/HomeController.cs:line 246

Here is a simple example:

public async Task<IActionResult> RedirectTest(){
    return this.RedirectToAction<HomeController>(c=>c.Index(""));
}

[Fact]
public async Task RedirectTest(){
    var result = await controller.RedirectTest() as RedirectToActionResult;
    Assert.NotNull(result);
}

Any ideas?

ivaylokenov commented 7 years ago

@svickers You can take a look at this issue for a possible solution: https://github.com/ivaylokenov/AspNet.Mvc.TypedRouting/issues/15 Let me know whether it fixes your problem. I am planning to enhance the unit testing experience when using the library.

svickers commented 7 years ago

I added the TestInit stuff but not having any luck still. When debugging I've verified that the testinit methods are called appropriately but still null reference exception on GetExpressionRouteHelper. Any ideas what I might be missing?

svickers commented 7 years ago

Scratch that, was missing the ControllerContext update when instantiating my controllers: https://github.com/ivaylokenov/AspNet.Mvc.TypedRouting/blob/master/test/AspNet.Mvc.TypedRouting.Test/LinkGeneration/ControllerExtensionsTest.cs#L447