Web API单元测试异常?

Jam*_*123 3 c# asp.net-mvc unit-testing asp.net-web-api

我为异常写了一个单元测试.但看起来它无法正常工作.它总是说'404 Not Found'状态.这意味着找不到网址请求.如果我在浏览器上粘贴相同的URL,它HttpResponse.StatusCodeBAD 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();
        };
    }
Run Code Online (Sandbox Code Playgroud)

我试过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);
            }               
        };
    }
Run Code Online (Sandbox Code Playgroud)

所以我不知道HttpSelfHostServer代码中没有问题?如何强制HttpSelfHostServer使用IISExpress?怎么处理?

Ste*_*rne 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;
     }
}
Run Code Online (Sandbox Code Playgroud)

从这种方式来说,您真正对控制器上的行为进行"单元测试",并避免任何间接测试

例如,如果你的控制器在你扔掉之前试图击中一个数据库HttpResponseException,那么你并不是真的单独测试控制器 - 因为如果你确实得到了一个例外,你就不会百分之百确定是什么扔了它.

通过直接测试,你可以注入例如Mock依赖项,除了你告诉他们做的事情之外别无他法.