I'm trying to setup unit tests for my web API. I've hacked together some test code from bits and pieces I've found on the web. I've got as far as sending the test request off and receiving a response, but I'm stuck on testing the response.
So here's what I've got so far. This is using the xunit test package, but I don't think that matters for what I'm trying to achieve.
(Apologies for the mash of code)
[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?
}
I'm hoping I can check the response as a string, something along the lines of
response == "{\"Status\":0,\"SessionKey\":"1234",\"UserType\":0,\"Message\":\"Successfully authenticated.\"}"
Here is how you get your response as string:
var responseString = response.Content.ReadAsStringAsync().Result;
However json format can vary and I bet you don't want to test that - so I recommend using Newtonsoft.Json or some similar library, parse the string to json object and test json object properties instead. That'll go
using Newtonsoft.Json.Linq;
dynamic jsonObject = JObject.Parse(responseString);
int status = (int)jsonObject.Status;
Assert.Equal(0, status);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With