c# - 我是否在我的测试方法中 stub 或填充方法?

标签 c# unit-testing microsoft-fakes stubs

我的测试方法中有一个方法 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/

相关文章:

c# - 在 C# 中模拟局部变量

c# - Akka.NET 可以在 F# 系统中创建 C# actor 吗?

c# - 限制 .NET 类型是否只能通过 ByVal 或 ByRef

c# - 区分 machine.config 和 web.config 中的 ConnectionString

asp.net-mvc-3 - 如何对调用 html.EditorFor 的扩展方法进行单元测试

c# - 如何对返回 JsonResult 的 Action 方法进行单元测试?

C#反序列化已移动或重命名的类

silverlight - 使用 MVVM Light 和 DispatcherHelper 进行单元测试

c# - Microsoft Fakes 生成 UnitTestIsolationException

c# - 如何在 c# .NET 的方法中参数化 Azure TableOperation.Retrieve<Element>