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