【问题标题】:Mock a local variable in an MVC action method?在 MVC 操作方法中模拟局部变量?
【发布时间】:2012-08-03 14:45:50
【问题描述】:

使用 Moq 或 Rhino,我想在我的 MVC 操作方法之一中模拟一个局部变量。

例如,在我的程序中,我有一个“ProfileController”,其方法如下所示:

        public ActionResult Profile(ProfileOptions oProfile)
        {
            ProfileViewModel oModel = new ProfileViewModel(); // <--can I mock this?

            //… do work, using oModel along the way

            return View(oModel);

         }

我的测试将在测试类的[SetUp] 方法中创建一个新的 ProfileController,并且我会使用它对其操作方法运行各种测试。

我想在我的测试中调用Profile 方法时模拟上面的oModel 变量,但由于它是本地的并且不是通过注入传递的,我能以某种方式做到这一点吗?

【问题讨论】:

    标签: asp.net-mvc mocking nunit moq


    【解决方案1】:

    如果您确实需要模拟对象,可以使用在类级别声明和实例化的构造方法/类型,然后模拟该类型。

    public class MyController
    {
        // If you're using DI, you should use constructor injection instead of this:
        protected IProfileViewModelBuilder _builder = new ProfileViewModelBuilder();
    
        ...
        public ActionResult Profile(ProfileOptions oProfile)
        {
            ProfileViewModel oModel = _builder.Build(); // <--I CAN mock this!
    
            //… do work, using oModel along the way
    
            return View(oModel);
    
         }
        ...
    
    }
    

    这种方法的一个好处是,如果将来创建 ViewModel 变得更加复杂,所需的任何更改都将被隔离到一个位置。

    希望对你有帮助,

    迈克

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2010-10-02
      相关资源
      最近更新 更多