使用 MOLES 的 ASP .net 单元测试控制器
我如何使用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框架测试我的控制器?
How can i unit test a controller that contains HttpConext using moles framework?
My Code for the controller is
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);
}
How should i test my controller using moles framework?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
快速的答案是不要使用 Moles,而是删除对静态 HttpContext 对象的依赖。
如果您使用 HttpContextBase(在 .NET 4.0 中的 System.Web.Abstractions 中)而不是 HttpContext,您将能够在单元测试中提供假的 HttpContext。您将需要在 MVC 应用程序中使用 IoC 容器,并确保在配置 IoC 容器时将 HttpContextWrapper(HttpContext.Current) 映射到 HttpContextBase。
网上有很多关于如何完成此操作的信息。只需 Google 一下 HttpContextBase、HttpContextWrapper 和 MVC,我相信您就会找到大量示例代码和解释来帮助您。
The quick answer is don't use Moles, but instead remove your dependency on the static HttpContext object.
If you use HttpContextBase (in System.Web.Abstractions in .NET 4.0) instead of HttpContext you'll be able to supply a fake HttpContext in your unit tests. You will need to use an IoC container in your MVC app and ensure you map HttpContextWrapper(HttpContext.Current) to HttpContextBase in when configuring the IoC container.
There's plenty of info on how this is done on the web. Just Google for HttpContextBase, HttpContextWrapper and MVC and I'm sure you'll find plenty of example code and explanations to help you.