在Visual Studio 2013中使用HttpClient进行单元测试/集成测试Web API [英] Unit Testing / Integration Testing Web API with HttpClient in Visual Studio 2013

查看:105
本文介绍了在Visual Studio 2013中使用HttpClient进行单元测试/集成测试Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用Visual Studio 2013测试我的API控制器.我的一个解决方案有一个Web API项目和一个Test项目.在我的测试项目中,我对此进行了单元测试:

I am having a hard time trying to test my API controller with Visual Studio 2013. My one solution has a Web API Project and a Test project. In my test project, I have a Unit Test with this:

[TestMethod]
public void GetProduct()
{
    HttpConfiguration config = new HttpConfiguration();
    HttpServer _server = new HttpServer(config);

    var client = new HttpClient(_server);

    var request = new HttpRequestMessage
    {
        RequestUri = new Uri("http://localhost:50892/api/product/hello"),
        Method = HttpMethod.Get
    };

    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    using (var response = client.SendAsync(request).Result)
    {
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

        var test = response.Content.ReadAsAsync<CollectionListDTO>().Result;
    }
}

我不断收到404 .我尝试使用一个Visual Studio(IIS Express)实例运行我的API,并尝试在另一个实例中调试此单元测试.但是没有运气.我已经验证可以将此URL放在浏览器中(一个Visual Studio正在调试时),并且可以看到JSON响应.但是我不知道如何使它与我的单元测试和HttpClient一起使用.我尝试过在线查找示例,但似乎找不到.有人可以帮忙吗?

I keep getting a 404. I have tried running my API with one instance of Visual Studio (IIS Express), and trying to debug this Unit Test in another instance. But no luck. I have verified that I can put this URL in a browser (when one Visual Studio is debugging) and I see my JSON response. But I can't figure out how to get it to work with my unit test and HttpClient. I have tried to find examples online but can't seem to find one. Can someone help?

更新1: 我尝试添加一条路线,但没有任何反应.

UPDATE 1: I tried adding in a route but nothing happened.

HttpConfiguration config = new HttpConfiguration();

// Added this line
config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/product/hello/");

HttpServer _server = new HttpServer(config);

var client = new HttpClient(_server);

[...rest of code is the same]

这是我的API控制器

[HttpGet]
[Route("api/product/hello/")]
public IHttpActionResult Hello()
{
     return Ok();
}

更新分辨率: 如果我在没有HttpServer对象的情况下新建HttpClient,则能够使它工作.我仍然需要运行两个VS实例. 1个运行我的API代码,另一个运行我的单元测试.

UPDATE Resolution: I was able to get it to work if I new up HttpClient without a HttpServer object. I would still need to have two instances of VS running though. 1 running my API code and another to run the Unit Test.

这是一种可行的方法.

[TestMethod]
public void Works()
{
    var client = new HttpClient(); // no HttpServer

    var request = new HttpRequestMessage
    {
        RequestUri = new Uri("http://localhost:50892/api/product/hello"),
        Method = HttpMethod.Get
    };

    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    using (var response = client.SendAsync(request).Result)
    {
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}

谁知道为什么HttpServerHttpConfiguration传递到HttpClient时为什么不起作用?我已经看到许多使用此示例.

Anyone know why it doesn't work with a HttpServer and a HttpConfiguration passed into HttpClient? I have seen many examples that use this.

推荐答案

参考下面的文章,我能够做到...

Referencing the following article I was able to do...

ASP.NET Web API集成使用内存托管进行测试

.在下面的示例中,我创建了一个使用属性路由的简单ApiController.我将HttpConfiguration配置为映射属性路由,然后将其传递给新的HttpServer. HttpClient然后可以使用配置的服务器对测试服务器进行集成测试调用.

by working with a HttpServer and a HttpConfiguration passed into HttpClient. In the following example I created a simple ApiController that uses attribute routing. I configured the HttpConfiguration to map attribute routes and then passed it to the new HttpServer. The HttpClient can then use the configured server to make integration test calls to the test server.

public partial class MiscUnitTests {
    [TestClass]
    public class HttpClientIntegrationTests : MiscUnitTests {

        [TestMethod]
        public async Task HttpClient_Should_Get_OKStatus_From_Products_Using_InMemory_Hosting() {

            var config = new HttpConfiguration();
            //configure web api
            config.MapHttpAttributeRoutes();

            using (var server = new HttpServer(config)) {

                var client = new HttpClient(server);

                string url = "http://localhost/api/product/hello/";

                var request = new HttpRequestMessage {
                    RequestUri = new Uri(url),
                    Method = HttpMethod.Get
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                using (var response = await client.SendAsync(request)) {
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                }
            }
        }
    }

    public class ProductController : ApiController {
        [HttpGet]
        [Route("api/product/hello/")]
        public IHttpActionResult Hello() {
            return Ok();
        }
    }
}

无需为了集成测试控制器而运行另一个VS实例.

There was no need to have another instance of VS running in order to integration test the controller.

以下简化的测试版本也可以正常工作

The following simplified version of the test worked as well

var config = new HttpConfiguration();
//configure web api
config.MapHttpAttributeRoutes();

using (var server = new HttpServer(config)) {

    var client = new HttpClient(server);

    string url = "http://localhost/api/product/hello/";

    using (var response = await client.GetAsync(url)) {
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}

在您的情况下,您需要确保正确配置服务器以匹配您的Web API设置.这意味着您必须使用HttpConfiguration对象注册api路由.

In your case you need to make sure that you are configuring the server properly to match your web api setup. This would mean that you have to register your api routes with the HttpConfiguration object.

var config = new HttpConfiguration();
//configure web api
WebApiConfig.Register(config);
//...other code removed for brevity

这篇关于在Visual Studio 2013中使用HttpClient进行单元测试/集成测试Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆