简体   繁体   中英

mocking httpContext.Current Api controller unit test

I am trying to mock httpContext using Moq framework to esnure that httContext.Current is not null when request comes from Unit test but couldn't really make it working.

After doing google, i came with following steps so for and not sure what steps are next before i make post call to Api controller .

step 1

Add Moq package to project

step 2

using Moq;

step 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);

Can someone help me out for the next steps i need to do before making Post controller request.

In your case it might be a lot easier to write integration tests.

    [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);
            }
        }
    }

A simplified version of 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);
    }
}

First of all, don't use HttpContext.Current , because it does not support unit testing. Inside your Controller there are Request and Response properties which can be used to access any info about Request or Response. Use them instead of HttpContex.Current .

Inside you unit tests you can set your own ControllerContext . Please, look at another stackoverflow question which describes how to fake ControllerContext in Web Api:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM