如何使用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框架测试我的控制器?
发布于 2011-08-13 19:42:44
简单的答案是不要使用Moles,而是删除对静态HttpContext对象的依赖。
如果你使用HttpContextBase (在.NET 4.0的System.Web.Abstractions中)而不是HttpContext,你将能够在你的单元测试中提供一个假的HttpContext。您需要在您的MVC应用程序中使用IoC容器,并确保在配置IoC容器时将HttpContextWrapper(HttpContext.Current)映射到HttpContextBase。
网上有很多关于如何做到这一点的信息。只需在谷歌上搜索HttpContextBase,HttpContextWrapper和MVC,我相信你会找到大量的示例代码和解释来帮助你。
https://stackoverflow.com/questions/6225010
复制相似问题