2011-06-03 60 views
1

我如何使用moles框架测试包含HttpConext的控制器? 我的控制器代码是ASP .net单元测试控制器使用MOLES

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

应该如何使用摩尔框架测试我控制器?

+0

这可能会帮助你:http://blog.dotnetwiki.org/2010/08/24/NewUnitTestingAspNETApplicationsWithPexAndMolesTutorial.aspx – 2011-06-03 10:50:36

+0

仅供参考0不确定你使用Unity作为你的IOC容器,而Moq作为你的隔离框架,您可以使用automocking轻松地将上下文截断。 http://www.dotnetcurry.com/ShowArticle.aspx?ID=767 – Spock 2013-06-16 12:50:08

回答

1

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

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

有很多关于如何在网上完成的信息。只需谷歌的HttpContextBase,HttpContextWrapper和MVC,我相信你会发现很多示例代码和解释来帮助你。

+0

只是好奇,你说“不要使用痣”的任何理由?这是一般还是这种特殊情况? – Spock 2013-06-16 12:27:37

+0

对不起,忽略了,对于这种特殊情况:) – Spock 2013-06-16 12:43:20

+0

+1 for HttpContextBase – Spock 2013-06-16 12:53:50