Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test MVC controller that uses HttpContext in ASP.NET Core 1.1

I have this small method written in ASP.Net Core on .Net Core 1.1 framework:

public class AccountController : Controller
{
    public IActionResult Logout()
    {
        HttpContext.Authentication.SignOutAsync("SchemaName");
        HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        return RedirectToAction("Index", "Home");
    }
}

I am struggling a lot with how to write a unit test that verifies that this method returns a RedirectToActionResult and tried many different approaches based on both old and relative new information found here and there. The problem is that HttpContext is null and I have been unsuccessful in mocking it.

Any help in writing this test would be greatly appreciated!

like image 543
MariWing Avatar asked Nov 18 '16 08:11

MariWing


1 Answers

You can setup a controller with an instance of the DefaultHttpContext like in this helper function.

    public MyController CreateController()
    {            
        var actionContext = new ActionContext
        {
            HttpContext = new DefaultHttpContext(),
            RouteData = new RouteData(),
            ActionDescriptor = new ControllerActionDescriptor()
        };

        var controller = new MyController
        {
            ControllerContext = new ControllerContext(actionContext)
        };

        return controller;
    }

Then the HttpContext property of the MyController instance is not null anymore and it provides a default AuthenticationManager in the HttpContext.Authentication property.

like image 122
Ralf Bönning Avatar answered Sep 21 '22 10:09

Ralf Bönning