设置模拟配置读取器时出错

时间:2014-02-25 13:50:37

标签: c# .net unit-testing moq

我正在尝试通过编写一些简单的单元测试来学习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);
}

当我编写单元测试时,我创建Mock的{​​{1}}并尝试设置预期的行为:

IWorkHandlerConfigReader

这是编译,但是当我运行测试时,我看到以下错误://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);

除了Mock对象之外,还有其他方法可以解决这个问题吗?我误解了它应该如何使用?

1 个答案:

答案 0 :(得分:2)

您实际上是在询问AppSettingsSection实例的依赖关系。因此,您应该设置此属性getter以返回包含所需数据的部分实例:

// Arrange
string expectedReturnValue = "This_is_from_the_app_settings";
var appSettings = new AppSettingsSection(); 
appSettings.Settings.Add("SomeAppSetting", expectedReturnValue);

var configReaderMock = new Mock<IWorkHandlerConfigReader>();
configReaderMock.Setup(cr => cr.AppSettingsSection).Returns(appSettings);
var reader = new BackgroundCheckServiceAppSettingsReader(configReaderMock.Object);

// Act
var result = reader.SomeAppSetting;

// Assert
Assert.Equal(expectedReturnValue, result);