Home > database >  Mock IHttpContextAccessor in Integration Tests
Mock IHttpContextAccessor in Integration Tests

Time:10-07

I would like to test one method in controller which is retrieving value from IHttpContextAccessor.HttpContext.Connection.RemoteIpAddress.

Is it possible to customize WebApplicationFactory so one can set fixed ip address?

The workaround would be to wrap the expression above into service so it can be mocked.

Thanks

Test.cs

var ipAddress = IPAddress.Parse("192.168.1.123");
var factory = new WebApplicationFactory<Startup>();
// ?

using var client = factory.CreateClient();
var response = await client.GetAsync(new Uri("https://localhost/test"), UriKind.Relative));
var ipAddress = await response.Content.ReadAsStringAsync();

TestController.cs

  private readonly IHttpContextAccessor _httpContextAccessor;

  public TestController(IHttpContextAccessor httpContextAccessor)
        {

            _httpContextAccessor = httpContextAccessor;
        }

  [HttpGet("test")]
  public async Task<IActionResult> GetTest()
  {

      var ipAddressObj = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress;

      var ipAddress = ipAddressObj?.ToString();

      return Ok(ipAddress);
   }

CodePudding user response:

Try this:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System.Net;
using WebApplication.Api.Controllers;
using Xunit;

namespace WebApplication.Api.Tests
{
    public class TestControllerTests
    {
        [Fact]
        public async void IpAdressResult()
        {
            var ipAddress = "192.168.1.123";
            var accessorMcok = new Mock<IHttpContextAccessor>();
            accessorMcok.Setup(a => a.HttpContext.Connection.RemoteIpAddress).Returns(IPAddress.Parse(ipAddress));

            var controller = new TestController(accessorMcok.Object);

            var result = (OkObjectResult)(await controller.GetTest());
            Assert.Equal(ipAddress, result.Value);
        }
    }
}
  • Related