我正在为我的Web API设置单元测试.我已经把我在网上找到的一些测试代码从黑客入侵.我已经发送测试请求并收到响应,但是我坚持测试响应.
@H_404_2@所以这是我到目前为止.这是使用xunit测试包,但我不认为对我想要实现的重要.
@H_404_2@(为代码的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? }@H_404_2@我希望我可以检查一个字符串的响应,一些事情
response == "{\"Status\":0,\"SessionKey\":"1234",\"UserType\":0,\"Message\":\"Successfully authenticated.\"}"
解决方法
以下是您如何将您的回复作为字符串:
var responseString = response.Content.ReadAsStringAsync().Result;@H_404_2@但是json格式可能会有所不同,我敢打赌你不想测试 – 所以我建议使用Newtonsoft.Json或者一些类似的库,解析该字符串到json对象,并测试json对象属性.那会去的
using Newtonsoft.Json.Linq; dynamic jsonObject = JObject.Parse(responseString); int status = (int)jsonObject.Status; Assert.Equal(status,0);