title: Unable to mock Owin context in C# WEB API REST service unit test
body: <p>I am trying to mock the OWIN context in a C# WEB API REST service but the OWIN context always seems to be null. I am using moq and .NET framework 4.5.2.</p>
  
  <p>Here is the controller method I am trying to test:</p>
  
  <pre><code>public class CustomerController : ApiController
  {
      // GET: api/Customer/n
      [HttpGet]
      [ClaimsPrincipalPermission(SecurityAction.Demand, Operation = Actions.View, Resource = Resources.Self)]
      public IHttpActionResult Get(int id)
      {
          if (id &lt;= 0)
              return BadRequest();
  
          ClaimsPrincipalPermission.CheckAccess(id.ToString(),"UserId");
  
          string jsonResponse = string.Empty;
          HttpStatusCode returnCode = this.ForwardGetRequestToWallet(String.Format("customer/gethistory/{0}", id), out jsonResponse);
          if (returnCode== HttpStatusCode.OK)
              return Ok(jsonResponse);
          return StatusCode(returnCode);            
      } 
  </code></pre>
  
  <p>And in a helper class the code that goes wrong, on the controller.Request.GetOwinContext call:</p>
  
  <pre><code>public static HttpClient GetClient(this ApiController controller)
  {
      HttpClient client = new HttpClient();
      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
      client.DefaultRequestHeaders.Authorization = controller.Request.Headers.Authorization;
      var test = controller.Request.GetOwinContext().Request.RemoteIpAddress;
      return client;
  } 
  </code></pre>
  
  <p>My test initialize:</p>
  
  <pre><code>[TestInitialize()]
  public void MyTestInitialize() 
  {
      player_user_id = Convert.ToInt32(ConfigurationManager.AppSettings["PLAYER_USER_ID"]);
      player_user_name = ConfigurationManager.AppSettings["PLAYER_USER_NAME"];
      API_protocol = ConfigurationManager.AppSettings["WEB_API_PROTOCOL"];
      API_host = ConfigurationManager.AppSettings["WEB_API_HOST"];
      API_port = ConfigurationManager.AppSettings["WEB_API_PORT"];
  
      wrapper = new ClaimsPrincipalWrapper();
  
      server = new Mock&lt;HttpServerUtilityBase&gt;();
      response = new Mock&lt;HttpResponseBase&gt;();
  
      request = new Mock&lt;HttpRequestBase&gt;();
  
      session = new Mock&lt;HttpSessionStateBase&gt;();
      session.Setup(s =&gt; s.SessionID).Returns(Guid.NewGuid().ToString());
  
      config = new HttpConfiguration();
  
      owinContext = new Mock&lt;IOwinContext&gt;();
  
      identity = new GenericIdentity(player_user_name);
      identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", player_user_id.ToString()));
  
      principal = new GenericPrincipal(identity, new[] { "User" });
  
      context = new Mock&lt;HttpContextBase&gt;();
      context.SetupGet(c =&gt; c.Request).Returns(request.Object);
      context.SetupGet(c =&gt; c.Response).Returns(response.Object);
      context.SetupGet(c =&gt; c.Server).Returns(server.Object);
      context.SetupGet(c =&gt; c.Session).Returns(session.Object);
      context.SetupGet(p =&gt; p.User.Identity.Name).Returns(player_user_name);
      context.SetupGet(p =&gt; p.Request.IsAuthenticated).Returns(true);
      context.SetupGet(s =&gt; s.User).Returns(principal);
  
  }
  </code></pre>
  
  <p>My test:</p>
  
  <pre><code>[TestMethod]
  public void Get()
  {
      var queryMock = new Mock&lt;IReadableStringCollection&gt;();
  
      var requestMock = new Mock&lt;IOwinRequest&gt;();
  
      requestMock.Setup(m =&gt; m.Query).Returns(queryMock.Object);
  
      owinContext.Setup(m =&gt; m.Request).Returns(requestMock.Object);
  
      testURI = new Uri(String.Format("{0}://{1}:{2}/Get/{3}", API_protocol, API_host, API_port, player_user_id));
      request.Setup(r =&gt; r.Url).Returns(testURI);
  
      message = new HttpRequestMessage(HttpMethod.Get, testURI);
      var route = config.Routes.MapHttpRoute("Default", "api/{controller}/{id}");
      var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "customerController", "get" } });
  
      var testControllerContext = new HttpControllerContext(config, routeData, message);
  
      var controller = new SharedWalletAPI.Controllers.CustomerController()
      {
          ControllerContext = testControllerContext,
          Request = new HttpRequestMessage(HttpMethod.Get, testURI),
          User = new System.Security.Principal.GenericPrincipal(identity, new string[0])
      };
  
      // Act
      var _result = controller.Get(player_user_id);
  
      // get JSON
      //CustomerHistoryList jsonObj = JsonConvert.DeserializeObject&lt;CustomerHistoryList&gt;(_result);
  
      // Assert
      Assert.IsNotNull(_result);
  }
  </code></pre>
  
  <p>All seems fine until we actually do the get then the OWIN GetOwinContext call which always returns null and hence throws an error of the old chestnut type "Object Reference not set to an instance of an object".</p>
  
  <p>I am still pretty new to OWIN. Can anyone advise me here?</p>