asp.net-mvc - 如何在 ASP.NET 中使用 Moq 测试 HTTP-Post?

标签 asp.net-mvc unit-testing moq

我有以下操作方法,我正在尝试最小起订量测试。注意到 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/

相关文章:

unit-testing - 如何在 Swift 中对 NSFetchedResultsController 进行单元测试

php - Laravel 按需测试通知

c# - 使用 Moq 模拟 TraceListener

vb.net - 如何模拟 OleDbDataAdapter(query, connStr)

asp.net - 仅当用户有权查看该页面时,我如何显示链接到该页面的按钮? ASP.NET MVC

c# - 如何在 Ajax 调用后更新 session ?

javascript - NestJS:拦截器测试中不允许通过字符串文字进行对象访问

MySQL数据库与ASP.NET全局连接

c# - 依赖注入(inject)与泛型相结合

c# - 如何使用 Moq 提供方法实现?