【发布时间】:2016-03-03 22:02:29
【问题描述】:
public class DemoController : Controller
{
private readonly ICommonOperationsRepository _commonRepo;
public DemoController (ICommonOperationsRepository commonRepo)
{
_commonRepo = commonRepo;
}
public ActionResult Default()
{
var model = new DemoModel();
try
{
**ConcreteClass cc = new ConcreteClass(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());
cc.ConcreteClassMethod();**
model.ListTopListing.AddRange(_commonRepo.GetListings());
}
catch (Exception ex)
{
ExceptionHandler objErr = new ExceptionHandler(ex, "DemoController .Default()\n Exception : " + ex.Message);
objErr.LogException();
}
return View(model);
}
}
我正在尝试对我的控制器进行单元测试。 ConcreteClass 构造函数及其方法 ConcreteClassMethod 都对 HttpRequest 变量有一些依赖,我无法从我的单元测试中传递这些变量。
我想要一种方法,当我调用 DemoController 的默认操作时,我可以简单地跳过 ConcreteClass 的构造函数和 ConcreteClassMethod 的执行。
【问题讨论】:
-
您不能创建对象的新实例并停止调用构造函数。您必须创建一个空的无参数构造函数。要么重新考虑你的方法的工作方式。您还可以使用依赖注入来注入值。
-
不知道该怎么做。你能详细解释一下吗?
-
请看我的回答,尤其是我刚刚添加的最后一点。如果您需要更多信息,请告诉我。
-
请看修改。
标签: asp.net-mvc unit-testing dependency-injection nunit moq