[英]testing ASP.NET MVC controller Httpget
We just started using ASP.NET MVC3 and we want to unit test our controller. 我们刚刚开始使用ASP.NET MVC3,我们想对控制器进行单元测试。
Here is my controller function: 这是我的控制器功能:
[HttpGet]
Public ActionResult Action()
{
Guid Id = Guid.Empty;
string[] UrlSegments = Request.Url.Segments;
Guid.TryParse(UrlSegments[UrlSegments.Count() - 1], out Id);
if(Id == Guid.Empty)
return RedirectToAction("ErrorPage");
}
I want to test this controller function.I have put the matching route to match this function in my global.asax file. 我想测试这个控制器功能,我已经在我的global.asax文件中放入了匹配路由来匹配这个功能。 Basically I am trying to retrieve the guid from the URl and if it is not good then take him to error page. 基本上,我试图从URl中检索Guid,如果它不好,则将其带到错误页面。 HttpRequestBase class URl is no setter,so I am confused how to test this functionality? HttpRequestBase类URl没有设置程序,所以我很困惑如何测试此功能?
As for testing read the link provided in the comments above but I would recommend doing some reading on MVC Routing or here , it does exactly what you are trying to achieve. 至于测试,请阅读上面注释中提供的链接,但是我建议您对MVC路由或此处做一些阅读,它确实可以达到您想要的目的。
Have a look in your global.ascx.cs file you will find something like this: 看看您的global.ascx.cs文件,您会发现类似以下内容:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This is the out of the box route for the MVC framework. 这是MVC框架的现成路线。
Routes will match a url based on the convention you give them. 路由将根据您为其指定的约定匹配网址。
So based on the default route above and given a url like this: 因此,根据上面的默认路由并给定了这样的网址:
http://localhost:portnumber/MyController/MyAction/8B4B93DE-76CA-4552-B4AA-460400761EAD
It will try and match this url to a controller called MyController with an action called MyAction, which receives and Id. 它将尝试将该URL与名为MyController的控制器进行匹配,并使用一个名为MyAction的动作来接收和标识。 It will only hit this action if all the criteria match. 如果所有条件都匹配,它将仅执行此操作。
If there is no id in the URL and id defined on your action method is not a nullable type then it simple wont execute. 如果URL中没有id,并且您在action方法上定义的id不是可为null的类型,则将不会执行。 It will rather try match another Url, if it cant find one it will give a 404. 它宁愿尝试匹配另一个Url,如果找不到另一个Url,则会给出404。
Like this: 像这样:
public class MyController : Controller {
[HttpGet]
Public ActionResult MyAction(Guid id)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.