我有以下操作方法
,我正在尝试最小起订量测试。注意到 AcceptVerbs
了吗?我需要确保我正在测试它。
方法如下。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include = "Subject, Content")]Post post,
HttpPostedFileBase imageFileName)
{
...
}
这是我的起订量代码...
[TestMethod]
public void Create_Action_snip_sniop_When_Http_Post_Is_Succesful()
{
// Arrange.
var mock = new Mock<ControllerContext>();
mock.SetupGet(m => m.HttpContext.Request.HttpMethod).Returns("POST");
// Snip some other arrangements.
var controller = PostController;
controller.ControllerContext = mock.Object;
// Act.
var viewResult = controller.Create(post, image.Object) as ViewResult;
// Assert.
Assert.IsNotNull(viewResult);
// TODO: Test that the request was an Http-Post.
我需要做什么来验证该请求是一个帖子?
最佳答案
作为单元测试运行时,您的属性不会被调用,因为它通常由 ControllerActionInvoker 作为 Mvc“堆栈”的一部分来调用。在这种情况下,我所做的就是编写一个测试,以确保将正确的属性应用于具有正确参数的操作。然后我相信该框架将正确完成其工作。
这样做需要反射(reflection):
public void Only_posts_are_allowed_to_my_action()
{
var method = typeof(MyController).GetMethod("MyAction");
var attribute = method.GetCustomAttributes(typeof(AcceptVerbsAttribute),false)
.Cast<AcceptVerbsAttribute>()
.SingleOrDefault();
Assert.IsNotNull( attribute );
Assert.AreEqual( 1, attributes.Count() );
Assert.IsTrue( attributes.Contains( HttpVerbs.Post ) );
}
关于asp.net-mvc - 如何在 ASP.NET 中使用 Moq 测试 HTTP-Post?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/718939/