1

我只是在学习如何通过 MSTest 使用 Moq。在现有应用程序中,我有以下要测试的方法:

/// <summary>
/// Return the marker equipment Id value give a coater equipment Id value.
/// </summary>
/// <param name="coaterEquipmentId">The target coater</param>
/// <returns>The marker equipment Id value</returns>
internal static string GetMarkerEquipmentId(string coaterEquipmentId)
{
    return CicApplication.CoaterInformationCache
        .Where(row => row.CoaterEquipmentId == coaterEquipmentId)
        .Select(row => row.MarkerEquipmentId)
        .First();
}

CicApplication对象是具有名为CoaterInformationCache的属性的“全局”对象,该属性是 CoaterInformation 类的列表。

我假设我需要以某种方式模拟 CicApplication.CoaterInformationCache,并且我可能需要将此方法传递给包含 CoaterInformation 类列表的接口,而不是通过仅包含运行时值的全局对象访问列表?

非常感谢

4

1 回答 1

2

全局/静态是单元可测试性的祸根。为了使这个可测试,你是正确的,你应该消除CicApplication全局。您可以创建一个接口,即ICicApplication使用相同的公共 API,并将一个实例传递到您的应用程序代码中。

public interface ICicApplication
{
    public List<CoaterInformation> CoaterInformationCache { get; }
}

public DefaultCicApplication : ICicApplication
{
    public List<CoaterInformation> CoaterInformationCache
    {
        // Either use this class as an adapter for the static API, or move
        // the logic here.
        get { return CicApplication.CoaterInformationCache; }
    }
}

由于这是一个静态方法,您可以将其作为方法参数传递,否则,将静态方法转换为实例方法并初始化ICicApplication对象上的字段(也许将实例传递给构造函数)。

然后,当您设置单元测试时,您可以传入一个使用 Moq 设置的模拟实例:

Mock<ICicApplication> appMock = new Mock<ICicApplication>();
appMock
    .SetupGet(ca => ca.CoaterInformationCache)
    .Returns(new List<CoaterInformation> { ... });
于 2012-12-20T16:00:05.690 回答