ASP.Net Web Api Url.Link在单元测试中没有返回UriString

时间:2012-09-03 10:34:18

标签: asp.net-web-api

我有以下测试:

[Test]
public void Add_New_Group_Should_Return_StatusCode_Created_And_A_Header_Location_To_The_New_Group()
{
    var newGroup = new GroupData { ID = 1, UserID = 1, Name = "Group 1", Description = "Description 1" };

    var fakeGroupDAL = A.Fake<IGroupDAL>();
    var contactGroupsController = new ContactGroupsController(fakeGroupDAL);
    SetupControllerForTests(contactGroupsController, HttpMethod.Post);

    var response = contactGroupsController.AddGroup(new ContactGroupApiRequest(), newGroup);

    Assert.IsTrue(response.StatusCode == HttpStatusCode.Created, "Should have returned HttpStatusCode.Created");

}

调用以下配置方法:

private static void SetupControllerForTests(ApiController controller, HttpMethod httpMethod)
{
    var config = new HttpConfiguration();
    var request = new HttpRequestMessage(httpMethod, "http://localhost/contactgroups");

    var route = config.Routes.MapHttpRoute("ContactGroupsApi", "{controller}/{action}/{request}", new { request = RouteParameter.Optional });
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "contactgroups" } });


    controller.ControllerContext = new HttpControllerContext(config, routeData, request);
    controller.Request = request;
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}

我正在尝试测试以下操作方法:

[HttpPost]
public HttpResponseMessage AddGroup([FromUri]ApiRequest req, [FromBody] GroupData contactGroup)
{

    if(ModelState.IsValid && contactGroup !=null)
    {
        _groupDal.AddGroup(contactGroup);

        contactGroup.Name = HttpUtility.HtmlEncode(String.Format("{0} - {1}", contactGroup.Name, contactGroup.Description));

        var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(contactGroup.Name) };

        var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group",  UserId = contactGroup.UserID, GroupId = contactGroup.ID});

        response.Headers.Location = new Uri(uriString);

        return response;
    }

    return Request.CreateResponse(HttpStatusCode.BadRequest);
}

当正常调用时,action方法运行良好,但由于对Url.Link的调用返回null,因此在测试中失败。

var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group",  UserId = contactGroup.UserID, GroupId = contactGroup.ID});  

所有这些代码都非常基于以下文章:Unit test ASP.NET Web Api

我怀疑在测试中运行时路由表信息不足。知道我做错了什么吗?

1 个答案:

答案 0 :(得分:14)

我通过将HttpRouteData添加到控制器的HttpRequestMessage的HttpRouteDataKey属性来修复我的测试。像这样:

controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;