我尝试测试路由到我的Controller的方法。我已经进行了以下单元测试:
[Test]
public void POST_PlaylistItem_Should_route_to_PlaylistItemController_Create_method()
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/PlaylistItem/");
var config = new HttpConfiguration();
WebApiConfig.Register(config);
var route = Helpers.RouteRequest(config, request);
route.Controller.Should().Be<PlaylistItemController>();
route.Action.Should().Be("Create");
}
我需要能够使用消息发布内容,以便我的控制器可以在以下两个签名之间做出决定:
[HttpPost]
public PlaylistItemDto Create(PlaylistItemDto playlistItemDto)
[HttpPost]
public IEnumerable<PlaylistItemDto> CreateMultiple(List<PlaylistItemDto> playlistItemDtos)
我正在查看一些资源,我找到了一个使用async + HttpClient http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client#PostingResource进行此操作的示例,但我并不热衷于使用不熟悉的技术过度复杂化我的示例,直到我掌握了基础知识。使用HttpClient我无法轻松地向控制器发送消息/它就像服务器没有运行一样。
答案 0 :(得分:1)
好吧,我明白了。请注意,我还没有转换为基于属性的路由,这是首选,但这是一个很好的起始示例:
目标是测试这两个方法签名不会使Web API发生冲突/混淆:
[HttpPost]
public PlaylistItemDto Create(PlaylistItemDto playlistItemDto)
[HttpPost]
public IEnumerable<PlaylistItemDto> CreateMultiple(List<PlaylistItemDto> playlistItemDtos)
在我的WebApiConfig类中:
config.Routes.MapHttpRoute(
name: "Create",
routeTemplate: "PlaylistItem",
defaults: new
{
controller = "PlaylistItem",
action = "Create"
}
);
config.Routes.MapHttpRoute(
name: "CreateMultiple",
routeTemplate: "PlaylistItem/CreateMultiple",
defaults: new
{
controller = "PlaylistItem",
action = "CreateMultiple"
}
);
这表示只有PlaylistItem动作名称的任何内容都将被路由到Create动作。任何PlaylistItem / CreateMultiple都将被路由到CreateMultiple操作。
然后,检查一下是否有效:
[Test]
public void POST_PlaylistItem_Should_route_to_PlaylistItemController_Create_method()
{
// setups
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/PlaylistItem/");
var config = new HttpConfiguration();
// act
WebApiConfig.Register(config);
var route = Helpers.RouteRequest(config, request);
// asserts
route.Controller.Should().Be<PlaylistItemController>();
route.Action.Should().Be("Create");
}
[Test]
public void POST_CreateMultiple_PlaylistItem_Should_route_to_PlaylistItemController_CreateMultiple_method()
{
// setups
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/PlaylistItem/CreateMultiple");
var config = new HttpConfiguration();
// act
WebApiConfig.Register(config);
var route = Helpers.RouteRequest(config, request);
// asserts
route.Controller.Should().Be<PlaylistItemController>();
route.Action.Should().Be("CreateMultiple");
}
其中RouteRequest来自Testing route configuration in ASP.NET WebApi