Web API单元测试异常?

时间:2013-10-03 18:52:54

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

我为异常写了一个单元测试。但看起来它无法正常工作。它总是说'404 Not Found'状态。这意味着找不到网址请求。如果我在浏览器上粘贴相同的网址,则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?如何处理?

1 个答案:

答案 0 :(得分:10)

暂且不说为什么你的特定方法不起作用,我是否可以建议你不要通过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%肯定是什么扔了它。

通过直接测试,您可以注射例如模拟依赖关系,除了你告诉他们做的事情之外什么也不做。