使用内存中HttpServer对WebApi控制器进行单元测试 - 未找到HTTP资源

时间:2014-12-07 18:35:19

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

来自Yusef的博客文章:http://blogs.msdn.com/b/youssefm/archive/2013/01/28/writing-tests-for-an-asp-net-webapi-service.aspx

我正在尝试为WebApi项目设置一些单元测试但是继续得到:

"No HTTP resrouce was found that matches the request URI http://localhost/api/Filter"

测试用例:

[TestMethod]
    public void TestMethod1()
    {
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
        HttpServer server = new HttpServer(config);
        using (HttpMessageInvoker client = new HttpMessageInvoker(server))
        {
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/Filter"))
            {
                request.Content = new StringContent(ValidJSONRequest);
                request.Content.Headers.Add("content", "application/json");
                using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
                {
                    Assert.AreEqual(ValidJSONResponse, response.Content.ReadAsStringAsync().Result);
                }
            }
        };
    }

NB。 ValidJSONRequest / ValidJSONResponse是包含JSON对象的字符串。

在IIS中运行表达此路由工作完美且行为符合预期,我不能为我的生活找出正在发生的事情?我错过了什么?

2 个答案:

答案 0 :(得分:0)

问题是您未在测试过的网址id上指定http://localhost/api/Filter,并且配置的路由没有将id配置为可选的。

因此,要么测试指定id的ULR,如http://localhost/api/Filter/1,要么对路由配置进行检查,以便id是可选的,如下所示:而不是

config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");

config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}/{id}",
     defaults: new { id = System.Web.Http.RouteParameter.Optional } // optional id
     );

通过这种方式,测试的网址将匹配DefaultApi路由。

当然,您需要在控制器中使用Postxxx方法,因为您正在尝试POST操作,而不是在测试的网址和路由中都没有指定操作名称定义。但是,如果你说它在本地IIS上工作,那么这种方法必须存在。

答案 1 :(得分:0)

是的,我还不确定这里到底发生了什么,但我找到了解决方法。

这篇博客文章包含一些细节 - 实际上控制器上下文需要加载到内存中...... http://www.tugberkugurlu.com/archive/challenge-of-solving-an-asp-net-web-api-self-hosting-problem-no-http-resource-was-found-that-matches-the-request-uri

那么如何解决呢?将此测试用例添加到测试类中,它可以正常工作。

[TestMethod]
public void Filter_Test()
{
    FilterController controller = new FilterController();
}