Как макет для модульного теста NUnit HttpContext.Current.Request.InputStream в API-контроллер в c#? - PullRequest
0 голосов
/ 16 марта 2020

Как смоделировать запрос контроллера веб-API в c# с помощью NUnit. Вот мой контроллер

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

1 Ответ

1 голос
/ 16 марта 2020

Избегайте связи с 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;

//...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...