模拟httpContext.Current Api控制器单元测试

时间:2016-07-05 08:36:22

标签: c# unit-testing asp.net-web-api2

我正在尝试使用httpContext模拟Moq framework,以便在请求来自单元测试时确认httContext.Current is not null,但无法使其正常工作。

在谷歌之后,我带来了以下步骤,以便在我拨打Api controller之前确定接下来会采取哪些步骤。

第1步

Add Moq package to project

第2步

using Moq;

第3步

var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();

request.Setup(r => r.UrlReferrer).Returns(new Uri("http://tempuri.org/?ReturnUrl=%2f"));
response.Setup(r => r.Cookies).Returns(new HttpCookieCollection());
context.Setup(c => c.Request).Returns(request.Object);
context.Setup(c => c.Response).Returns(response.Object);

在发出控制后请求之前,有人可以帮助我完成我需要做的后续步骤。

2 个答案:

答案 0 :(得分:1)

在您的情况下,编写集成测试可能要容易得多。

    [Test]
    public async Task get_should_succeed()
    {
        //arrange
        var url = string.Format("{0}{1}", BaseUrl, "controller");

        using(var httpServer = CreateHttpServer())
        using (var client = CreateHttpInvoker(httpServer))
        {
            using (var request = CreateHttpRequest(HttpMethod.Get, url))
            //act
            using (var response = await client.SendAsync(request, CancellationToken.None))
            {
                //assert
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
    }

ControllerTestBase的简化版本:

public abstract class ControllerTestBase
{
    protected ControllerTestBase()
    {
        BaseUrl = "http://localhost/api/";
    }

    public string BaseUrl { get; set; }

    public static HttpServer CreateHttpServer()
    {
        var httpConfiguration = WebApiConfig.Register();
        return new HttpServer(httpConfiguration);
    }

    public static HttpMessageInvoker CreateHttpInvoker(HttpServer httpServer)
    {
        return new HttpMessageInvoker(httpServer);
    }

    public HttpRequestMessage CreateHttpRequest(HttpMethod httpMethod, string url)
    {
        return new HttpRequestMessage(httpMethod, url);
    }
}

答案 1 :(得分:0)

首先,不要使用HttpContext.Current,因为它不支持单元测试。在Controller内,有RequestResponse个属性,可用于访问有关请求或响应的任何信息。使用它们而不是HttpContex.Current

在单元测试中,您可以设置自己的ControllerContext。请查看另一个stackoverflow问题,该问题描述了如何在Web Api中伪造ControllerContext

Testing a Web API method that uses HttpContext.Current.Request.Files?