c# - 为什么我的 API 测试应该通过却失败了
问题描述
我是 C# 的新手,我需要通过 API 测试来测试服务器是否有正确的响应。在这里,我尝试更新不存在的 ID=100 的用户:
public void TestUpdate()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(mainURL + "/v2/100/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "PUT";
httpWebRequest.Headers.Add(authKey, authValue);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
externalDealId = "100",
status = "Closed"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Assert.That(httpResponse.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
但是当我运行此测试时,它失败并给出一条消息:
结果消息:System.Net.WebException:远程服务器返回错误:(404)未找到。怎样才能让我的测试通过?我只需要断言这个 ID 错误的请求会从服务器给出 404 响应。
解决方案
WebException
被抛出,因此您可以尝试使用该Assert.Throws
方法(可能取决于您正在使用的测试 API)
var we = Assert.Throws<WebException>(() =>
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // exception is thrown
});
Assert.AreEqual(WebExceptionStatus.ProtocolError, we.Status);
问题是,这ProtocolError
不仅是404
不幸的。
HttpClient
你可以试试
using (var httpc = new HttpClient())
{
string json = new JavaScriptSerializer().Serialize(new
{
externalDealId = "100",
status = "Closed"
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpc.PutAsync(url, content);
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
}
推荐阅读
- javascript - 识别在php中的while循环内单击的按钮?
- python - 防止删除 SQLAlchemy 中的模型实例
- php - 如何使用 PHP 检测浏览器和设备信息?
- php - 我不能调用变量
- r - 如何仅执行已保存的 R 脚本的一部分
- python - 在 QWebEngineView 的同一窗口中打开浏览器选项卡。未发送推荐人。如何配置?
- matlab - 如何在matlab上旋转图像而不会得到黑色背景
- c# - 如何更快地上传文件?
- dart - 解析 JSON 文件以获取列表中的列表
- c# - 如何使用 lambda 表达式在 Entity Framework 中加入两个实体?