ASP.NET MVC - 单元测试覆盖初始化方法

标签 asp.net asp.net-mvc-3

我有一个如下所示的抽象类,它被所有其他 Controller 继承。是否可以完全测试这种方法?顺便说一句,我正在尝试使用最小起订量,但没有运气。如果你能帮助我将不胜感激:

public abstract class ApplicationController : Controller
{  
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
       base.Initialize(requestContext);

       //do some stuff here
    }
}

最佳答案

如果您查看基本 Initialize 方法的源代码,您会发现它所做的是设置 ControllerContext 和 url 的东西。现在,下载 MvcContrib TestHelper 并查看 TestControllerBuilder .构建器设置了您需要的所有内容,以便拥有 Controller 上下文和您所依赖的其他内容。
好的,我们还没有结束 - 你想测试你自己的 Initialize 覆盖吗?
TestControllerBuilder 不会调用您的 Initialize,因为它以不同的方式进行初始化。我建议您将自定义 Initialize() 逻辑分解为不同的方法。然后使用公共(public)方法创建假( stub )子类,该方法调用此因式 protected 初始化。你和我在一起吗?

就像是:

public abstract class ApplicationController : Controller
{  

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
   {
      base.Initialize(requestContext);
      MyInitialzie()
   }
    protected void MyInitialize()
    {
       ControllerContext.XXX // do whatewer you want here. Context is already setted up
    }
}

class FakeController: ApplicationController 
{
   public void CallMyInitialize()
   {
      MyInitialize();
   }
}

后来在测试课上:
[Test]
public void MyInitializeTest()
{
    TestControllerBuilder builder = new TestControllerBuilder();
    FakeController controller = new FakeController();
    builder.InitializeController(controller);

    controller.CallMyInitialize();
    //TODO: verification of MyInitialize assumptions
}

明白了吗?

关于ASP.NET MVC - 单元测试覆盖初始化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769163/

相关文章:

javascript - ASP.NET DataGrid ClientID 值返回 null

c# - 限制对远程 api 的并行请求

.NET:Web 服务文档的自定义格式?

asp.net - 将 ASP.NET MVC4 应用程序部署到 GoDaddy 编译器问题

asp.net-mvc-3 - 获取asp.net mvc中的当前目录

asp.net-mvc - ASP.NET MVC 3 - 部分、显示模板与编辑器模板

java - 在 aspx 表单中查找直接链接或使用 android 读取表单

c# - 长期静态页面缓存

c# - MVC3 - 获取经过身份验证的用户的部门名称

c# - rendersection 的这段代码是什么意思?