gpt4 book ai didi

asp.net-web-api - ASP.Net Web Api Url.Link 在单元测试中不返回 UriString

转载 作者:行者123 更新时间:2023-12-03 07:29:06 25 4
gpt4 key购买 nike

我有以下测试:

[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

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

最佳答案

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

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

关于asp.net-web-api - ASP.Net Web Api Url.Link 在单元测试中不返回 UriString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12246159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com