Q:

Error when setting up a mock config reader

I'm trying to learn Moq by writing some simple unit tests.  Some of them have to do with a class called 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; }
    }
}

The interface for the class is defined like this:
public interface IBackgroundCheckServiceAppSettingsReader
{
    string SomeAppSetting { get; }
}

And the IWorkHandlerConfigReader (which I do not have permission to modify) is defined like so:
public interface IWorkHandlerConfigReader
{
    AppSettingsSection AppSettingsSection { get; }
    ConnectionStringsSection ConnectionStringsSection { get; }
    ConfigurationSectionCollection Sections { get; }

    ConfigurationSection GetSection(string sectionName);
}

When I write the unit test, I create a Mock of the IWorkHandlerConfigReader and try to set up the expected behavior:
//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);

This compiles, but when I run the test, I see the following error: System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: cr => cr.AppSettingsSection.Settings["SomeAppSetting"].Value
Is there another way to approach this other than a Mock object?  Am I misunderstanding how it should be used?

A:

You are actually asking dependency for AppSettingsSection instance. So, you should setup this property getter to return some section instance with data you need:
// 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);

