模拟使用索引的属性

问题描述 投票:1回答:1

我试图解耦ConfigurationManager所以我可以嘲笑它。

这是我的课程和界面

public class Settings
{
    public string this[string index] => ConfigurationManager.AppSettings[index];
}

public class ConfigurationRepository : IConfigurationRepository
{    
    public virtual Settings AppSettings
    {
        get { return new Settings(); }
    }
}

public interface IConfigurationRepository
{
   Settings AppSettings { get; }
}

这是我如何嘲笑它

_configurationManager = new Mock<IConfigurationRepository>();
_configurationManager.SetupGet(m => m.AppSettings["someKey"]).Returns("someResult");

但是当我尝试测试它时,我得到一个例外

非虚拟(在VB中可覆盖)成员的无效设置:m => m.AppSettings [“someKey”]

测试失败,它甚至没有通过我的Setup方法。

我不知道为什么我会得到这个例外,有谁能告诉我我做错了什么?

c# unit-testing nunit moq
1个回答
1
投票

具体的Settings类的索引器属性需要为qqxswpoi,以便Moq能够覆盖其默认行为

virtual

我还建议重构存储库实现,以避免每次调用public class Settings { public virtual string this[string index] => ConfigurationManager.AppSettings[index]; } 属性时初始化类。

AppSettings
© www.soinside.com 2019 - 2024. All rights reserved.