我正在尝试在我的ASP.NET Web 2控制器中对路由进行单元测试。我严格遵循新出版的“ASP.NET网络应用程序2”一书中的配方11-6。这是我的控制器:
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
private AccountService _accountService;
public AccountController(AccountService service)
{
_accountService = service;
}
[Route("{id}")]
public IHttpActionResult Get(string id)
{
return Ok(_accountService.Get(id));
}
[Route("all")]
public IHttpActionResult GetAll()
{
return Ok(_accountService.GetAll());
}
}
下面是我的单元测试(xunit):
public class AccountRoutingTest
{
readonly HttpConfiguration _config;
public AccountRoutingTest()
{
_config = new HttpConfiguration();
_config.MapHttpAttributeRoutes();
_config.EnsureInitialized();
}
[Theory]
[InlineData("http://acme.com/api/account/john")]
public void GetRoutingIsOk(string url)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var routeTester = new RouteContext(_config, request);
Assert.Equal(typeof(AccountController), routeTester.ControllerType);
Assert.True(routeTester.VerifyMatchedAction(Reflection.GetMethodInfo((AccountController c) => c.Get(""))));
}
[Theory]
[InlineData("http://acme.com/api/account/all")]
public void GetAllRoutingIsOk(string url)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var routeTester = new RouteContext(_config, request);
Assert.Equal(typeof(AccountController), routeTester.ControllerType);
Assert.True(routeTester.VerifyMatchedAction(Reflection.GetMethodInfo((AccountController c) => c.GetAll())));
}
}
第一个单元测试通过,但第二个单元测试失败。在下面的行中,我隔离了RouteContext助手类中的问题,其中GetActionMapping方法只检测Get(id)操作,而不是GetAll():
_actionMappings = actionSelector.GetActionMapping(descriptor)[request.Method.ToString()];
我尝试用GetAll()属性显式地修饰HttpGet ()操作方法,并将属性路由转换为集中式路由--但没有成功。我的想法快用完了。为什么GetAll()操作(以及除Get(id)操作之外的所有其他操作)没有被GetActionMapping方法检测到?
当从浏览器或Fiddler进行测试时,路由是很好的。
发布于 2014-08-21 07:16:27
看上去像一个小虫子:)
变化
_actionMappings = actionSelector.GetActionMapping(descriptor)[request.Method.ToString()];
至:
_actionMappings = actionSelector.GetActionMapping(descriptor).
SelectMany(x => x).Where(x => x.SupportedHttpMethods.Contains(request.Method));
https://stackoverflow.com/questions/25386162
复制相似问题