gpt4 book ai didi

c# - 如何测试 Web API JSON 响应?

转载 作者:可可西里 更新时间:2023-11-01 08:21:22 25 4
gpt4 key购买 nike

我正在尝试为我的网络 API 设置单元测试。我从网上找到的一些零零碎碎的东西中整理了一些测试代码。我已经发送了测试请求并收到了响应,但我一直在测试响应。

这就是我到目前为止所得到的。这是使用 xunit 测试包,但我认为这对我要实现的目标并不重要。

(为困惑的代码道歉)

[Fact]
public void CreateOrderTest()
{
string baseAddress = "http://dummyname/";

// Server
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

HttpServer server = new HttpServer(config);

// Client
HttpMessageInvoker messageInvoker = new HttpMessageInvoker(new InMemoryHttpContentSerializationHandler(server));

// Order to be created
MotorInspectionAPI.Controllers.AccountController.AuthenticateRequest requestOrder = new MotorInspectionAPI.Controllers.AccountController.AuthenticateRequest() {
Username = "Test",
Password = "password"
};

HttpRequestMessage request = new HttpRequestMessage();
request.Content = new ObjectContent<MotorInspectionAPI.Controllers.AccountController.AuthenticateRequest>(requestOrder, new JsonMediaTypeFormatter());
request.RequestUri = new Uri(baseAddress + "api/Account/Authenticate");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;

CancellationTokenSource cts = new CancellationTokenSource();

using (HttpResponseMessage response = messageInvoker.SendAsync(request, cts.Token).Result)
{
Assert.NotNull(response.Content);
Assert.NotNull(response.Content.Headers.ContentType);

// How do I test that I received the correct response?

}

我希望我可以将响应检查为字符串,类似于

response == "{\"Status\":0,\"SessionKey\":"1234",\"UserType\":0,\"Message\":\"Successfully authenticated.\"}"

最佳答案

以下是您如何获得字符串形式的响应:

var responseString = response.Content.ReadAsStringAsync().Result;

但是 json 格式可能会有所不同,我打赌你不想测试它 - 所以我建议使用 Newtonsoft.Json 或一些类似的库,将字符串解析为 json 对象并测试 json 对象属性。就这样

using Newtonsoft.Json.Linq;   

dynamic jsonObject = JObject.Parse(responseString);
int status = (int)jsonObject.Status;
Assert.Equal(0, status);

关于c# - 如何测试 Web API JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21550057/

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