我有一些REST api端点,我通过网络客户端的ajax调用,我想编写一些自动化测试,以确保它们在Web浏览器之外正常工作。
我正在编写它们作为单元测试测试,这是我到目前为止所做的:
[TestClass]
public class ApiTests
{
string local_host_address = "http://localhost:1234//";
public async Task<string> Post(string path, IEnumerable<KeyValuePair<string, string>> parameters)
{
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(0,0,5);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response_message = await client.PostAsync(local_host_address + path, new FormUrlEncodedContent(parameters));
var response = await response_message.Content.ReadAsStringAsync();
if (response_message.IsSuccessStatusCode)
{
return response;
}
else
{
throw new Exception("Request failed");
}
}
}
[TestMethod]
[TestCategory("ApiTests")]
public void TestLogon()
{
var parameters = new Dictionary<string, string>();
parameters["email"] = "bob@aol.com";
parameters["password"] = "rosebud";
Task.Run( () =>
{
var output = Post("Default.aspx/Logon", parameters);
Console.WriteLine(output.Result);
}).Wait();
}
}
...非常基本,它只是尝试调用特定端点,并返回结果。问题是,此调用返回基本的default.aspx网页正文,而不是default.aspx / logon生成的结果。我做错了什么,但我用调试器一直在做它,我看不到我的错误。 default.aspx / logon端点存在,当我通过网站访问它时,它可以正常工作。我错过了还是忽略了什么?
-TTM
解决方案:
Bruno对我的代码片段的更改效果非常好。其他任何试图解决测试REST端点问题的人都可以将其放入单元测试并传入POCO,它将返回JSON响应。
答案 0 :(得分:4)
虽然您将请求标记为application / json,但您正在以FormUrlEncoded发送正文。
如果您的API是REST并且使用JSON,而不是使用 Dictionary ,则可以反序列化对象(例如使用Newtonsoft.Json):
public async Task<string> Post<T>(string path, T data)
{
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, 5);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = JsonConvert.SerializeObject(data);
var response_message = await client.PostAsync(local_host_address + path, new StringContent(json, Encoding.UTF8, "application/json");
var response = await response_message.Content.ReadAsStringAsync();
if (response_message.IsSuccessStatusCode)
{
return response;
}
else
{
throw new Exception("Request failed");
}
}
}