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!
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.
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