title: Mocking Request.UserHostAddress for Unit Testing for WEB API
body: <p>I am writing Unit Test for my WEB API Service. I want to mock request from ip address. I am using Microsoft Unit Test. </p>
  
  <pre><code>[TestClass]
  public class UnitTest1
  {
      private Mock&lt;HttpContextBase&gt; moqContext;
      private Mock&lt;HttpRequestBase&gt; moqRequest;
  
      [TestMethod()]
      public void TestMethod1()
      {
         var controller = new TestController();
          controller.ControllerContext = new ControllerContext(moqContext.Object, new System.Web.Routing.RouteData(), controller);
  
      }
      [TestInitialize]
      public void SetupTests()
      {
          // Setup Moq
          moqContext = new Mock&lt;HttpContextBase&gt;();
          moqRequest = new Mock&lt;HttpRequestBase&gt;();
          moqContext.Setup(x =&gt; x.Request).Returns(moqRequest.Object);
          moqContext.Setup(x =&gt; x.Request.UserHostAddress).Returns("192.111.1.1");
      }
  
  }
  </code></pre>
  
  <p>I don't know how to proceed further, I am getting below error.</p>
  
  <pre><code>&gt; Severity  Code    Description Project File    Line    Suppression State
  &gt; Error CS1503  Argument 3: cannot convert from
  &gt; 'WebApplication1.Controllers.TestController' to
  &gt; 'System.Web.Mvc.ControllerBase'   UnitTestProject1
  </code></pre>
  
  <p>Any help appreciated.
  Is MOQ better than Rino, also, alternate ways for avoiding virtual methods for MOQ testing.</p>
  
  <p>Updates 
  Ok so the Controller is an API Controller as follows</p>
  
  <pre><code>// GET: api/Test
          public IEnumerable&lt;string&gt; Get()
          {
              string s =HttpContext.Current.Request.UserHostAddress;
               ...Authentication/Authorization based on IP address
              return new string[] { s };
          }
  </code></pre>
  
  <p>I want to mock HttpContext.Current.Request.UserHostAddress in my Unit test so as to test different IP address. My question is how to set the mock IP address. I have found a link <a href="https://blog.slatner.com/geeky/mocking-request-userhostaddress-in-asp-net-mvc.html" rel="nofollow noreferrer">https://blog.slatner.com/geeky/mocking-request-userhostaddress-in-asp-net-mvc.html</a>. but I couldn't figure out how to use. Any help much appreciated.</p>