如何在C#的api控制器中模拟单元测试NUnit HttpContext.Current.Request.InputStream?

问题描述 投票:0回答:1

如何使用NUnit在C#中模拟Web API控制器请求这是我的控制器

public class SearchApiController : ApiController
{     

 [HttpPost]
    public HttpResponseMessage Applications(string authToken)
    {
        string req;
        using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
        {
            req = reader.ReadToEnd();
        }


    }   
}

我尝试过这样的测试用例:

            var httpRouteDataMock = new Mock<IHttpRouteData>();
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://this.com");
            var controllerContext = new HttpControllerContext(new HttpConfiguration(), 
            httpRouteDataMock.Object, httpRequestMessage);
            _controller.ControllerContext = controllerContext;

当我使用普通的mvc控制器和ControllerContext时,它工作正常

c# unit-testing asp.net-web-api nunit streamreader
1个回答
0
投票

避免耦合到HttpContext

ApiController已经具有属性

HttpRequestMessage Request { get; set; }

提供对当前请求的访问。

更改设计

public class SearchApiController : ApiController  

    [HttpPost]
    public async Task<HttpResponseMessage> Applications(string authToken) {
        Stream stream = await this.Request.Content.ReadAsStreamAsync();
        string req;
        using (var reader = new StreamReader(stream)) {
            req = reader.ReadToEnd();
        }

        //...
    }   
}

现在,您原始示例中的测试关系更紧密

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://this.com");
//...set the content of the request as needed
httpRequestMessage.Content = new StringContent("some data");

var httpRouteDataMock = new Mock<IHttpRouteData>();
var controllerContext = new HttpControllerContext(new HttpConfiguration(), 
    httpRouteDataMock.Object, httpRequestMessage);
_controller.ControllerContext = controllerContext;

//...
© www.soinside.com 2019 - 2024. All rights reserved.