异常的 Web API 单元测试
本文关键字:单元测试 API Web 异常 | 更新日期: 2023-09-27 18:33:59
我为异常编写了一个单元测试。但看起来它无法正常工作。它总是说"404 未找到"状态。这意味着找不到 URL 请求。如果我在浏览器上粘贴相同的网址,它HttpResponse.StatusCode
说BAD REQUEST
.
我不明白为什么它不适用于单元测试。
[TestMethod()]
public void GetTechDisciplinesTestException()
{
var config = new HttpSelfHostConfiguration("http://localhost:51546/");
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
using (var server = new HttpSelfHostServer(config))
using (var client = new HttpClient())
{
server.OpenAsync().Wait();
using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51546/api/techdisciplines/''"))
using (var response = client.SendAsync(request).Result)
{
//Here Response Status Code says 'Not Found',
//Suppose to be 'Bad Request`
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
}
server.CloseAsync().Wait();
};
}
我尝试使用HttpSelfHostServer
它工作正常,它使用 IISExpress。
[TestMethod()]
public void GetTechDisciplinesTestException()
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51546/api/techdisciplines/''"))
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
}
};
}
所以我不知道HttpSelfHostServer
没有在代码中徘徊?如何强制HttpSelfHostServer
使用IISExpress
? 如何处理?
撇开为什么你的特定方法不起作用,我是否可以建议你不要费心通过HTTPRequest测试该特定行为 - 只需直接针对控制器类进行测试:
[TestMethod]
[ExpectedException(typeof(HttpResponseException))]
public void Controller_Throws()
{
try{
//setup and inject any dependencies here, using Mocks, etc
var sut = new TestController();
//pass any required Action parameters here...
sut.GetSomething();
}
catch(HttpResponseException ex)
{
Assert.AreEqual(ex.Response.StatusCode,
HttpStatusCode.BadRequest,
"Wrong response type");
throw;
}
}
因为这样,你就可以真正在控制器上"单元测试"该行为,并避免任何间接测试
例如,如果你的控制器在你抛出HttpResponseException
之前关闭并试图命中数据库,那么你并不是真正孤立地测试控制器 - 因为如果你确实得到了一个异常,你不会100%确定是什么抛出了它。
通过直接测试,您可以注入例如模拟依赖项,除了您告诉它们做什么之外,它什么都不会做。