【问题标题】:Xunit- Add body to a HttpWebRequestXunit-将正文添加到 HttpWebRequest
【发布时间】: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


【解决方案1】:

使用参考答案中建议的方法并将您的对象序列化为包含 json 的字符串。

根据 .NET 的版本,您可以执行以下操作(.NET Framework 4.5+ 和 Newtownsoft.Json NuGet 包):

// ...
ASCIIEncoding encoding = new ASCIIEncoding();
string infoString = JsonConvert.SerializeObject(info);
byte[] byte1 = encoding.GetBytes(infoString);
// ...

或者对于 .NET Core 3.1 或 .NET 5.0:

string infoString = JsonSerializer.Serialize(info);

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 2021-09-12
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多