I'm trying to test below method with NUnit and Moq in .NET Core environment:
[HttpGet]
public async Task<IActionResult> DeviceType()
{
string deviceIp = HttpContext.GetServerVariable("REMOTE_ADDR");
var result = await DeviceService.GetTypeForAsync(deviceIp);
return Ok(result);
}
The problem is mock a HttpContext.GetServerVariable
. I've tried to mock context and insert it by ControllerContext
:
var actionContext = new Mock<ActionContext>();
var httpContext = new Mock<HttpContext>();
httpContext.Setup(x => x.GetServerVariable(It.IsAny<string>())).Returns("192.168.1.1");
actionContext.Setup(x => x.HttpContext).Returns(httpContext.Object);
//...
var deviceController = new DeviceController();
deviceController.ControllerContext = new ControllerContext(actionContext.Object);
But test not passed and throw an error:
System.NotSupportedException : Unsupported expression: x => x.GetServerVariable(It.IsAny()) Extension methods (here: HttpContextServerVariableExtensions.GetServerVariable) may not be used in setup / verification expressions.
The question is: how to mock HttpContext.GetServerVariable("REMOTE_ADDR")
?