title: .NET Core unit test how to Mock HttpContext RemoteIpAddress?
body: <p>I have a .NET Core 3.1 project using Identity. For the <code>Login</code> page handler I have added a line of code that after a user logs in, it updates a users location based on their IP address: </p>
  
  <pre><code>_locationRepository.UpdateUserLocationAsync(HttpContext.Connection.RemoteIpAddress);
  </code></pre>
  
  <p><strong>Full Code</strong></p>
  
  <pre><code>public async Task&lt;IActionResult&gt; OnPostAsync(string returnUrl = null)
  {
      returnUrl = returnUrl ?? Url.Content("~/");
  
      if (ModelState.IsValid)
      {
          // This doesn't count login failures towards account lockout
          // To enable password failures to trigger account lockout, set lockoutOnFailure: true
          var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
          if (result.Succeeded)
          {
              _locationRepo.UpdateUserLocation(HttpContext.Connection.RemoteIpAddress);
              _logger.LogInformation("User logged in.");
              return LocalRedirect(returnUrl);
          }
          if (result.RequiresTwoFactor)
          {
              return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
          }
          if (result.IsLockedOut)
          {
              _logger.LogWarning("User account locked out.");
              return RedirectToPage("./Lockout");
          }
          else
          {
              ModelState.AddModelError(string.Empty, "Invalid login attempt.");
              return Page();
          }
      }
  
      // If we got this far, something failed, redisplay form
      return Page();
  }
  </code></pre>
  
  <p>My problem is when writing the unit test, I don't know how to properly mock the <code>HttpContext</code>. I keep getting a null reference exception regardless of what I have tried.</p>
  
  <pre><code>var httpContext = new Mock&lt;HttpContext&gt;();
  httpContext.Setup(x =&gt; x.Connection.RemoteIpAddress).Returns(new IPAddress(16885952));
  </code></pre>
  
  <p>How do I mock the <code>RemoteIpAddress</code>?</p>