1
我正在尝试通过编写一些简单的单元测试来学习Moq。他们中有些人有一类叫做AppSettingsReader做:设置模拟配置读取器时出错
public class BackgroundCheckServiceAppSettingsReader : IBackgroundCheckServiceAppSettingsReader
{
private string _someAppSetting;
public BackgroundCheckServiceAppSettingsReader(IWorkHandlerConfigReader configReader)
{
if (configReader.AppSettingsSection.Settings["SomeAppSetting"] != null)
this._someAppSetting = configReader.AppSettingsSection.Settings["SomeAppSetting"].Value;
}
public string SomeAppSetting
{
get { return _someAppSetting; }
}
}
的类接口的定义是这样的:
public interface IBackgroundCheckServiceAppSettingsReader
{
string SomeAppSetting { get; }
}
而且IWorkHandlerConfigReader
(我没有权限修改)是定义像这样:
public interface IWorkHandlerConfigReader
{
AppSettingsSection AppSettingsSection { get; }
ConnectionStringsSection ConnectionStringsSection { get; }
ConfigurationSectionCollection Sections { get; }
ConfigurationSection GetSection(string sectionName);
}
当我写单元测试,我创建了IWorkHandlerConfigReader
的Mock
并尝试建立预期b ehavior:
//Arrange
string expectedReturnValue = "This_is_from_the_app_settings";
var configReaderMock = new Mock<IWorkHandlerConfigReader>();
configReaderMock.Setup(cr => cr.AppSettingsSection.Settings["SomeAppSetting"].Value).Returns(expectedReturnValue);
//Act
var reader = new BackgroundCheckServiceAppSettingsReader(configReaderMock.Object);
var result = reader.SomeAppSetting;
//Assert
Assert.Equal(expectedReturnValue, result);
这将编译,但是当我运行测试,我看到以下错误:System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: cr => cr.AppSettingsSection.Settings["SomeAppSetting"].Value
有另一种方式比模拟对象来处理这个其他?我误解它应该如何使用?
谢谢你的建议!尽管如此,仍然有同样的错误。 – Zach
@Zach看起来像你正在尝试创建'AppSettingsSection'的模拟而不是创建它的实例 –
AppSettingsSection fakeSettingsSection = new AppSettingsSection(); //这会不会创建一个新的实例? – Zach