Integration testing Web API endpoints with MSTest
Using in-memory server
[TestMethod]
public void Get()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost/api/hello"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var test = response.Content.ReadAsAsync<MyResponseModel>().Result;
Assert.AreEqual("hello world", test.Greeting);
}
}
[TestMethod]
public void Post()
{
// Prepare request body
List<KeyValuePair<string, string>> bodyProperties = new List<KeyValuePair<string, string>>();
bodyProperties.Add(new KeyValuePair<string, string>("Name", ""));
// How to send an array
for (var i = 1; i < 8; i++)
{
bodyProperties.Add(new KeyValuePair<string, string>("ProductIds[]", i.ToString()));
}
var RequestUri = new Uri("http://localhost/api/Products");
using (var response = client.PostAsync(RequestUri, new FormUrlEncodedContent(bodyProperties)).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var test = response.Content.ReadAsAsync<MyResponseObject>().Result;
Assert.AreEqual(typeof(List<MyType>), test.GetType());
Assert.AreEqual("Done", test.Message);
}
}