6

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!

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.