您在单元测试中检查 HttpVerbs 吗?
在查看标准 ASP.MVC Web 项目模板附带的单元测试时,我注意到这些测试不会测试每个操作方法上是否设置了正确的 HttpVerbs 属性。
通过反射来测试这一点非常容易,但问题是它是否值得付出努力。 您是否在单元测试中检查 HttpVerbs,还是将其留给集成测试?
While looking at the unit tests that come with the standard ASP.MVC Web Project template, I noticed that these do not test whether or not a proper HttpVerbs attribute is set on each action method.
It's very easy to test this with reflection, but the question is whether or not it It's worth the effort. Do you check HttpVerbs in your unit test, or do you leave this up to Integration testing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
雪化雨蝶2024-08-01 06:06:21
如果其他人发现这个问题:我已经开始在单元测试中检查所有操作方法接受属性。 稍微反思一下就可以解决问题。 如果您也想这样做,这里有一些代码:
protected void CheckAcceptVerbs<TControllerType>(string methodName, HttpVerbs verbs)
{
CheckAcceptVerbs(methodName, typeof(TControllerType).GetMethod(methodName, BindingFlags.Public|BindingFlags.Instance,null,new Type[]{},null), verbs);
}
protected void CheckAcceptVerbs<TControllerType>(string methodName, Type[] ActionMethodParameterTypes, HttpVerbs verbs)
{
CheckAcceptVerbs(methodName, typeof(TControllerType).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, ActionMethodParameterTypes, null), verbs);
}
private void CheckAcceptVerbs<TControllerType>(string methodName, MethodInfo actionMethod, HttpVerbs verbs)
{
Assert.IsNotNull(actionMethod, "Could not find action method " + methodName);
var attribute =
(AcceptVerbsAttribute)
actionMethod.GetCustomAttributes(false).FirstOrDefault(
c => c.GetType() == typeof(AcceptVerbsAttribute));
if (attribute == null)
{
Assert.AreEqual(HttpVerbs.Get, verbs);
return;
}
Assert.IsTrue(HttpVerbsEnumToArray(verbs).IsEqualTo(attribute.Verbs));
}
第一个方法适用于不带参数的操作方法,第二个方法适用于带参数的操作方法。 您也可以直接使用第三种方法,但我将前两个重载编写为便利函数。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您还可以使用 MvcContrib.TestHelper 通过操作来测试路由。
You could also use the MvcContrib.TestHelper to test the route with actions.