2012-08-06 21 views
1

使用Moq或Rhino,我想在我的一個MVC動作方法中嘲諷一個局部變量。模擬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,但因爲它是本地的而不是通過注入傳入的,所以我可以以某種方式執行此操作?

回答

0

如果您確實需要模擬對象,您可以使用在類級別聲明和實例化的構造方法/類型,然後模擬該類型。

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); 

    } 
    ... 

} 

一個好處這種方法是,如果您在未來的視圖模型的創建變得更加複雜,所需要的任何更改都隔離到一個位置。

希望幫助,

邁克