我的测试方法中有一个方法 base.ResolveDate()
来自基类及其公共(public)和虚拟。我想用我自己的方法对这个方法进行 stub /填充,那么我是 stub 还是填充? Stub 或 Shim,我该怎么做?根据我使用 MS Fakes 的经验,它似乎是一个 stub ,因为 stub 只能影响可覆盖的方法。 - ALM 2012
测试方法如下:
public override DateTime ResolveDate(ISeries comparisonSeries, DateTime targetDate)
{
if (comparisonSeries == null)
{
throw new ArgumentNullException("comparisonSeries");
}
switch (comparisonSeries.Key)
{
case SeriesKey.SomeKey1:
case SeriesKey.SomeKey2:
case SeriesKey.SomeKey3:
case SeriesKey.SomeKey4:
case SeriesKey.SomeKey5:
return DateHelper.PreviousOrCurrentQuarterEnd(targetDate);
}
return base.ResolveDate(comparisonSeries, targetDate);
}
这是我想要 Stub/Shim 的基类方法吗?
public virtual DateTime ResolveDate(ISeries comparisonSeries, DateTime targetDate)
{
if (this.key == comparisonSeries.Key)
return targetDate;
return DateHelper.FindNearestDate(targetDate, comparisonSeries.AsOfDates);
}
最佳答案
要独立于其基本实现来测试派生方法,您需要对其进行填充。给定以下被测系统:
namespace ClassLibrary7
{
public class Parent
{
public virtual string Method()
{
return "Parent";
}
}
public class Child : Parent
{
public override string Method()
{
return base.Method() + "Child";
}
}
}
您可以为 Child.Method() 编写以下测试。
using ClassLibrary7;
using ClassLibrary7.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
var child = new Child();
var shim = new ShimParent(child);
shim.Method = () => "Detour";
string result = child.Method();
Assert.IsFalse(result.Contains("Parent"));
Assert.IsTrue(result.Contains("Detour"));
Assert.IsTrue(result.Contains("Child"));
}
}
}
}
请注意,包含前两个断言只是为了说明父方法是如何绕行的。在实际测试中,只需要为子方法断言。
关于c# - 我是否在我的测试方法中 stub 或填充方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947747/