繁体   English   中英

如何从数据类型为字典的只读属性模拟或存根方法?

[英]How do I mock or stub a method from a readonly property whose datatype is dictionary?

我开始使用犀牛模型,遇到了一个复杂的问题。

我对类AppDefaults有依赖关系,该类具有只读属性“ Properties”,其数据类型为Dictionary。

我的被​​测类使用Dictionary函数.ContainsKey()的结果,该函数返回一个布尔值。

MyAppDefaultsInstance.Properties.ContainsKey(“ DefaultKey”)

我只是通过在要测试的类上创建一个公共虚拟函数来包装.Contains函数来解决此问题。 但是有没有一种方法可以模拟或存根.ContainsKey结果而无需包装器来模拟它?

示例代码:

    public class AppDefaults
{

    public readonly IDictionary<String, String> Properties = new Dictionary<string, string>();

    public AppDefaults()
    {
        LoadProperties();
    }

    private void LoadProperties()
    {
        //load the properties;
    }

    public virtual int GetPropertyAsInt(string propertyKey)
    {
        return XmlConvert.ToInt32(Properties[propertyKey]);
    }

}


public class DefaultManager
{
    AppDefaults _appsDefault;
    public int TheDefaultSize
    {
        get
        {
            int systemMax;
            int currentDefault = 10;

            if (_appsDefault.Properties.ContainsKey("DefaultKey"))
            {
                systemMax = _appsDefault.GetPropertyAsInt("DefaultKey");
            }
            else
            {
                systemMax = currentDefault;
            }

            return systemMax;
        }
    }

    public DefaultManager(AppDefaults appDef) {
        _appsDefault = appDef;
    }
}

[TestClass()]
public class DefaultManagerTest
{

    [TestMethod()]
    public void TheDefaultSizeTest()
    {
        var appdef = MockRepository.GenerateStub<AppDefaults>();

        appdef.Expect(m => m.Properties.ContainsKey("DefaultKey")).Return(true);

        appdef.Stub(app_def => app_def.GetPropertyAsInt("DefaultKey")).Return(2);

        DefaultManager target = new DefaultManager(appdef); 

        int actual;
        actual = target.TheDefaultSize;
        Assert.AreEqual(actual, 2);
    }
}

为什么不嘲笑.ContainsKey方法,而不是只用一些预定义的测试值填充字典:

// arrange
var appDef = new AppDefaults();
appDef.Properties["DefaultKey"] = "2";

// act
var target = new DefaultManager(appDef); 

// assert
Assert.AreEqual(target.TheDefaultSize, 2);

我不会暴露

AppDefaults.Properties

领域。 除此之外,您可以添加类似

GetProperty(string key) 

到AppDefaults(如果存在则返回键),然后在单元测试中模拟结果。 模拟的方法都将返回将检查target.TheDefaultSize对值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM