代码之家  ›  专栏  ›  技术社区  ›  simendsjo

使用moq从mvc操作返回的视图为空

  •  1
  • simendsjo  · 技术社区  · 14 年前

    这个话题说明了一切。

    我猜这是因为缺少一些与MVC相关的设置,但我对http、asp.net和MVC还很陌生,所以我不太清楚到底出了什么问题。

    public class MyController : Controller {
        public ActionResult MyAction(MyModel model) {
            return View(model);
        }
    }
    
    var controllerMock  = new Mock<MyController>() {
        CallBase = true // without this, the call to View(model) returns null
    };
    
    
    /*
     * I've also tried this before calling the action:
     * 
     * controllerMock.SetFakeControllerContext();
     *
     * from http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
     * But the same applies.
     **/
    
    ViewResult result = controllerMock.Object.MyAction(new MyModel()) as ViewResult;
    Assert.AreEqual("MyAction", result.ViewName); // ViewName etc is blank
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Fabiano    14 年前

    如果使用mvccontrib进行测试,可以尝试以下方法:

    var controller = new MyController();
    var builder = new TestControllerBuilder();
    builder.InitializeController(controller);
    
    var actionResult = controller.MyAction(new MyModel());
    ViewResult viewResult = actionResult.AssertViewRendered().ForView("");
    //or
    ViewResult viewResult = actionResult.AssertViewRendered().ForViewOrItself("MyAction");