【发布时间】:2014-11-20 04:57:12
【问题描述】:
我有一个继承自 BaseController 的 QuickController 类。 QuickController 中的一个方法调用 BaseController 上的一个属性,该属性依赖于 ConfigurationManager.AppSettings。
我想对 QuickController 进行单元测试,但找不到摆脱这种依赖关系的方法。这是我的测试:
[TestMethod]
public void TestMethod1()
{
var moqServiceWrapper = new Mock<IServiceWrapper>();
var controller = new QuickController(moqServiceWrapper.Object);
//Act
var result = controller.Estimator(QuickEstimatorViewModel);
//Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
}
QuickController 类
public class QuickController : BaseController
{
public QuickController(IServiceWrapper service)
: base(service) { }
public ActionResult Estimator(QuickEstimatorViewModel viewModel)
{
viewModel.RiskAddressLocation = RiskAddressLocation;
....
return View("QuickQuote", viewModel);
}
}
还有 BaseController 属性
public RiskAddressLocation RiskAddressLocation
{
get { return ConfigurationManager.AppSettings["..."]
.ToEnum<RiskAddressLocation>(true); }
}
我也尝试在继承自 QuickController 的 FakeQuickController 上调用该方法,但无法覆盖该属性,它是 BaseController 中始终被调用的那个。
有什么我可以在这里做的吗?
更新
从接受的答案来看,这是 VS2013 不喜欢的地方
public class BaseController{
public virtual RiskAddressLocation RiskAddressLocation {get{...;}
}
public class QuickController : BaseController{}
public class FakeQuickController : QuickController{
public override RiskAddressLocation RiskAddressLocation
{
get { return ...} // Doesn't compile (cannot override because
//BaseController.RiskAddressLocation' is not a function
}
}
但是,这很好用
public class BaseController{
public virtual RiskAddressLocation RiskAddressLocation(){...}
}
public class QuickController : BaseController{}
public class FakeQuickController : QuickController{
public override RiskAddressLocation RiskAddressLocation()
{
return ... ;
}
}
【问题讨论】:
-
看起来你想mock ConfigurationManager而不是试图模拟基地?
-
足够公平@RGraham,但我如何拦截基类中的 RiskAddressLocation 以便能够模拟它?
标签: c# asp.net-mvc-4 unit-testing moq