微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何测试web API的JSON响应?

我正在为我的Web API设置单元测试.我已经把我在网上找到的一些测试代码从黑客入侵.我已经发送测试请求并收到响应,但是我坚持测试响应.

所以这是我到目前为止.这是使用xunit测试包,但我不认为对我想要实现的重要.

(为代码的mash道歉)

[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(status,0);

原文地址:https://www.jb51.cc/csharp/93984.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐