1

如何使用 moles 框架对包含 HttpConext 的控制器进行单元测试?我的控制器代码是

public ActionResult Index()
        {
             MyRepositoryClass myRepo = new MyRepositoryClass (System.Web.HttpContext.Current);
             string fs = ipser.GetCityName();
             return View();
        }

My code for the controller in unit test project is
public class MyClassTest
{

   [TestMethod]
   [HostType("Moles")]
    public void Index_Test()
    {
         string originalViewName="Index";
         MyController myContl = new MyController ();
         var result =myContl.Index() as ViewResult;
         Assert.IsNotNull(result, "Should return a view");
         Assert.AreEqual(originalViewName, result.ViewName, "View name should have been {0}", originalViewName);
    }

我应该如何使用 moles 框架测试我的控制器?

4

1 回答 1

1

快速的答案是不要使用 Moles,而是删除您对静态 HttpContext 对象的依赖。

如果您使用 HttpContextBase(在 .NET 4.0 中的 System.Web.Abstractions 中)而不是 HttpContext,您将能够在单元测试中提供假的 HttpContext。您需要在 MVC 应用程序中使用 IoC 容器,并确保在配置 IoC 容器时将 HttpContextWrapper(HttpContext.Current) 映射到 HttpContextBase。

网上有很多关于如何做到这一点的信息。只需在 Google 上搜索 HttpContextBase、HttpContextWrapper 和 MVC,我相信您会找到大量示例代码和解释来帮助您。

于 2011-08-13T11:42:43.993 回答