集成测试网络核心中的自定义HTTP客户端

时间:2017-02-27 08:13:03

标签: c# integration-testing asp.net-core-webapi

我正在试图弄清楚是否可以在集成测试中使用自定义HTTP客户端?

而不是从TestServer获取客户端实例

protected void btn_----_Click(object sender, EventArgs e)
{
    string response = "";
    for (int i = 0; i < mylist.Count; i++)
    {
        if (mylist[i].id == ddl_idList.SelectedValue)
        {
            Session["selectedidObj"] = mylist[i];
            response = "window.open('../folder/mypage.aspx','_blank');";
            break;
        }
    }

    ClientScript.RegisterClientScriptBlock(GetType(), "Comment", response, true);
}

使用我自己的实现。 Smthng喜欢:

Client = Server.CreateClient() 

当我这样做的时候,我经常得到404. WAIDW?

1 个答案:

答案 0 :(得分:0)

我面临同样的问题,在我的情况下,我无法使用现有的HttpClient,因为我需要在初始化时修改HttpClient。所以我的解决方案是创建一个服务器并使用我自己的HttpClient对其进行测试。

using(var server = WebHost.CreateDefaultBuilder(new List<string>().ToArray())
    .UseEnvironment("Test")
    .UseStartup<Startup>()
    .UseKestrel(options =>
    {
        options.Listen(IPAddress.Loopback, 5000);
    })
    .Build())
    {
        server.Start();
        var client = new HttpClient
        {
            BaseAddress = new Uri("http://localhost:5000")
        }
        var resp = client.GetAsync("test/testme").Result;
    }