【发布时间】:2021-01-08 17:29:59
【问题描述】:
我想对我的 Api 进行测试,所以我需要测试一个 PUT 端点。 我已经测试了我所有的 Get 端点,所以直到现在我都不需要在我的请求中发送正文。 我该怎么做?
测试
public void TestUpdateSinglePlayerStats()
{
string id = "2019";
HttpWebRequest request = (HttpWebRequest)WebRequest
.Create("http://localhost:5000/GameStats/Update/" + id);
request.Headers.Add("Authorization", "Bearer " + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjIwMTkiLCJyb2xlIjoiVXNlciIsIm5iZiI6MTYxMDEyMzY2OSwiZXhwIjoxNjEwMjEwMDY5LCJpYXQiOjE2MTAxMjM2Njl9.Dd2wzUJ5LnPBw0CbDXZZTIiQLX8074F_E1wW-qBPQzw");
request.ContentType = "application/json";
request.Method = "PUT";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
}
我的 API 端点
试过了
string id = "2019";
StatUpdateModel info = new StatUpdateModel();
info.Score = 4000;
info.Round = 3;
info.MonstersKilled = 102;
info.GameMode = "Singleplayer";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(info);
HttpWebRequest request = (HttpWebRequest)WebRequest
.Create("http://localhost:5000/GameStats/Update/" + id);
request.Headers.Add("Authorization", "Bearer " + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjIwMTkiLCJyb2xlIjoiVXNlciIsIm5iZiI6MTYxMDEyMzY2OSwiZXhwIjoxNjEwMjEwMDY5LCJpYXQiOjE2MTAxMjM2Njl9.Dd2wzUJ5LnPBw0CbDXZZTIiQLX8074F_E1wW-qBPQzw");
request.ContentType = "application/json";
request.Method = "PUT";
request.ContentLength = byte1.Length;
Stream stream = request.GetRequestStream();
stream.Write(byte1, 0, byte1.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
【问题讨论】:
-
这能回答你的问题吗? Setting a WebRequest's body data
-
试过了,但我收到错误消息,说无法从我的模型转换为 char[](编辑了我的问题)
标签: c# api asp.net-core testing xunit