gpt4 book ai didi

nunit - HTTP 自托管和单元测试

转载 作者:行者123 更新时间:2023-12-01 12:42:12 25 4
gpt4 key购买 nike

我正在进行一组单元测试,其中包括使用自托管服务器测试 HTTP 客户端/服务器功能。但我什至无法进行最简单的测试。这是我的代码

单元测试1.cs

    using System;
using System.Net.Http;
using System.Web.Http.SelfHost;
using NUnit.Framework;
using SomeWebService;

namespace UnitTestProject1
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var baseAddress = new Uri("http://localhost:9876");
var config = new HttpSelfHostConfiguration(baseAddress);
new Bootstrap().Configure(config);
var server = new HttpSelfHostServer(config);
using (var client = new HttpClient(server))
{
client.BaseAddress = baseAddress;
var response = client.GetAsync("").Result;
Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode);
}
}
}
}

Bootstrap.cs

    using System.Web.Http;

namespace SomeWebService
{
public class Bootstrap
{
public void Configure(HttpConfiguration config)
{
config.Routes.MapHttpRoute(name: "API Default", routeTemplate: "{controller}/{id}", defaults: new
{
controller = "Home",
id = RouteParameter.Optional
});
}
}
}

和 HomeController.cs

    using System.Net.Http;
using System.Web.Http;

namespace SomeWebService
{
class HomeController:ApiController
{
public HttpResponseMessage Get()
{
return this.Request.CreateResponse();
}
}
}

测试结果在:

      Actual status code: NotFound
Expected: True
But was: False

我做错了什么?

安装包

Install-Package Microsoft.Net.Http -version 2.0.20710
Install-Package Microsoft.AspNet.WebApi.SelfHost -version 4.0.20918
Install-Package Microsoft.AspNet.WebApi.Core -version 4.0.20710

最佳答案

如果您希望测试运行得更快,可以通过使用纯内存主机来避免整个 TCP/IP 堆栈,

        [Test]
public void TestMethod1()
{
var config = new HttpConfiguration();
new Bootstrap().Configure(config);
var server = new HttpServer(config);
using (var client = new HttpClient(server))
{
client.BaseAddress = baseAddress;
var response = client.GetAsync("").Result;
Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode);
}
}

关于nunit - HTTP 自托管和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com