4

我有以下测试:

[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

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

4

1 回答 1

14

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

controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
于 2012-09-04T15:16:14.167 回答