c# - Web API单元测试异常?

标签 c# asp.net-mvc unit-testing asp.net-web-api

我为异常编写了一个单元测试。但看起来它无法正常工作。它总是说“404 Not Found”状态。这意味着找不到 url 请求。如果我在浏览器上粘贴相同的 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 测试该特定行为 - 只需直接针对 Controller 类进行测试:

[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;
     }
}

因为这样你就真正地“单元测试”了 Controller 上的行为,并避免了任何间接测试

例如,如果您的 Controller 在您抛出 HttpResponseException 之前关闭并尝试访问数据库,那么您并不是真正在孤立地测试 Controller ——因为如果您确实返回异常您不会 100% 确定是什么原因造成的。

通过直接测试,您可以注入(inject)例如模拟依赖项,它们只会执行您告诉它们执行的操作。

关于c# - Web API单元测试异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19166967/

相关文章:

c# - 线程 : Application Freezes after using Thread. 加入()

asp.net-mvc - ASP.NET MVC 5.1、ASP.NET Web API 2.1 是否需要 IIS 7.5?

php - 在 Laravel 4 单元测试中,如何在请求中设置 cookie?

javascript - 如何在 Angular 单元测试中创建 ArrayBuffer 变量,Jasmine/Karma

c# - SQL:按日期分组

C# T4 使用 web.config 中的 assemblyBinding/BindingRedirect

asp.net-mvc - 存储库模式 - MVC 店面

c# - 将 ASP.NET MVC 模型封装为可重用程序集

javascript - 如何使用 mocha sinon 模拟类异步/等待函数

c# - 从 IoC 容器加载重物会阻塞 UI