NoWar
NoWar

Reputation: 37633

HttpContextBaseExtensions.GetOwinContext throws NullReferenceException when trying to run Unit tests

I get a NullReferenceException when trying to run Unit tests for a program written in the ASP.NET MVC framework.

Test(s) failed. System.NullReferenceException : Object reference not set to an instance of an object. at System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase context)

This error happens when I try to execute the Logoff method.

public ActionResult LogOff()
{
     SessionWrapper.SetInSession("_Settings", null);  
     AuthenticationManager.SignOut();
     return RedirectToAction("Index", "Home");
}

public class HttpContextSessionWrapper : ISessionWrapper
{
        public T GetFromSession<T>(string key)
        {
            if (!string.IsNullOrEmpty(key))
                return (T)HttpContext.Current.Session[key];
            else    
                return default(T);
        }

        public void SetInSession(string key, object value)
        {
            if (!string.IsNullOrEmpty(key))
                HttpContext.Current.Session[key] = value;
        }
}

How do I fix this NullReferenceException when writing unit tests in ASP.NET MVC?

Upvotes: 1

Views: 1670

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190943

You should not be using HttpContext.Context. Use this.Session, this being your controller. You could either inject that with IoC or pass it to your methods.

With IoC, you could mock this dependency much easier as well.

Upvotes: 1

Related Questions