2014-02-25 26 views
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); 
} 

当我写单元测试,我创建了IWorkHandlerConfigReaderMock并尝试建立预期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

有另一种方式比模拟对象来处理这个其他?我误解它应该如何使用?

回答

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); 
+0

谢谢你的建议!尽管如此,仍然有同样的错误。 – Zach

+0

@Zach看起来像你正在尝试创建'AppSettingsSection'的模拟而不是创建它的实例 –

+0

AppSettingsSection fakeSettingsSection = new AppSettingsSection(); //这会不会创建一个新的实例? – Zach