gpt4 book ai didi

使用 webClient.UploadString 的 C# 单元测试

转载 作者:太空宇宙 更新时间:2023-11-03 13:02:46 25 4
gpt4 key购买 nike

我正在使用 webClient.uploadString(uri,parameter) 方法。它命中一个返回字符串的 url。每当出现错误请求或其他类似错误时,服务器都会抛出异常。

在进行单元测试时,我需要将响应状态代码与某些特定状态代码进行比较。

UploadString 方法只返回字符串。

我的查询是:如何从 WebClient 获取响应对象以便比较状态码

最佳答案

只能判断请求失败的状态码:

try
{
var client = new WebClient();
client.DownloadString("...");
}
catch (WebException ex)
{
var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
...
}

如果你想在请求成功时确定状态码,你需要 monkey patch 网络客户端...

我实际上建议您使用 HttpClient 代替 WebClient。它有一个好得多的界面:

var client = new HttpClient();
HttpResponseMessage response = client.GetAsync("...").Result;
HttpStatusCode status = response.StatusCode;
string result = response.Content.ReadAsStringAsync().Result;

请记住,您所描述的不是单元测试,而是 integration test。而且它似乎没有用。

关于使用 webClient.UploadString 的 C# 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31854723/

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