【发布时间】:2013-06-21 23:37:47
【问题描述】:
我知道我不能使用 Moq 在我的测试方法中模拟出静态方法调用,那么我需要做什么来重构该方法以便我可以测试它?我也有一个调用基类方法的方法,我需要重构它吗?如果需要怎么做?我不想使用 MS.Fakes 或 TypeMocks 来创建 shim,我宁愿重构并编写可靠的代码!
public override DateTime ResolveDate(ISeries comparisonSeries, DateTime targetDate)
{
if (comparisonSeries == null)
{
throw new ArgumentNullException("comparisonSeries");
}
switch (comparisonSeries.Key)
{
case SeriesKey.R1:
case SeriesKey.R2:
case SeriesKey.R3:
case SeriesKey.R4:
case SeriesKey.R5:
return DateHelper.PreviousOrCurrentQuarterEnd(targetDate);
}
return base.ResolveDate(comparisonSeries, targetDate);
}
[TestMethod]
public void SomeTestMethod()
{
var mockIAppCache = new Mock<IAppCache>();
var mockISeries = new Mock<ISeries>();
ReportFR2 report = new ReportFR2(SeriesKey.FR2, mockIAppCache);
DateTime resolvedDate = report.ResolveDate(mockISeries, DateTime.Now);
//Assert.AreEqual("something", "something");
}
【问题讨论】:
-
或者我想在我的被测方法中调用静态方法?我认为答案是否定的,因为单元测试只测试被测方法中的逻辑,而不是其他任何东西,除非它是私有方法。如果我错了,请有人纠正我!
-
用接口包装 DateHelper 并将您的 IDateHelper 作为包含类中的方法参数或作为构造函数参数注入,就像您对 IAppCache 所做的那样?
-
什么会更好? 1)用接口包装 DateHelper 并将其传入或 2)在类中的“受保护的内部虚拟”方法中隔离静态方法,然后我可以模拟出该方法。
-
取决于实现。如果 DateHelper 有一些您想在测试场景中使用的方法,只需在您直接调用的方法中设置 Now ,虚拟方法可能是一个不错的选择。不过,我会在界面方面犯错。
-
如果我在接口一侧“出错”,我将不得不将我的类从静态类重构为实例类,对吧?还是有别的办法?
标签: c# unit-testing moq moq-3