【发布时间】:2014-07-19 16:24:55
【问题描述】:
在使用 Moq 进行单元测试时,我收到以下错误:
Message: System.NotSupportedException :
Invalid setup on non-virtual (overridable in VB) member:
cm => cm.AppSettings[It.IsAny<string>()]
根据这些发现,我知道最好在 Moq 中使用抽象类或接口。
- Why does the property I want to mock need to be virtual?
- Moq is throwing Invalid setup on a non-overridable member, when class is in Service Project
- Invalid setup on a non-virtual (overridable in VB) member
- Moq: Invalid setup on a non-overridable member: x => x.GetByTitle(“asdf”)
简而言之,我已经完成了我的作业。 =)
但是如果我真的在使用接口呢?
ConfigurationServiceTests
[TestFixture]
public class ConfigurationServiceTests {
[Test]
public void DialectShouldQueryConfigurationManagerAppSettings() {
// Given
configurationManagerMock
.Setup(cm => cm.AppSettings[It.IsAny<string>()])
.Returns(It.IsAny<string>());
// When
var dialect = configurationService.Dialect;
// Then
dialect.Should().BeOfType<string>();
configurationManagerMock.Verify(cm => cm.AppSettings[It.IsAny<string>()]);
}
[SetUp]
public void ConfigurationServiceSetUp() {
configurationManagerMock = new Mock<IConfigurationManager>();
configurationService =
new ConfigurationService(configurationManagerMock.Object);
}
private Mock<IConfigurationManager> configurationManagerMock;
private IConfigurationService configurationService;
}
IConfigurationManager
public interface IConfigurationManager {
NameValueCollection AppSettings { get; }
ConnectionStringSettingsCollection ConnectionStrings { get; }
}
IConfigurationService
public interface IConfigurationService {
string ConnectionDriver { get; }
string ConnectiongString { get; }
string Dialect { get; }
}
配置服务
public class ConfigurationService : IConfigurationService {
public ConfigurationService(IConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
}
public string ConnectionDriver {
get { return configurationManager.AppSettings["ConnectionDriver"]; }
}
public string ConnectionString {
get {
return configurationManager
.ConnectionStrings[ConnectionStringKey]
.ConnectionString;
}
}
public string Dialect {
get { return configurationManager.AppSettings[DialectKey]; }
}
private readonly IConfigurationManager configurationManager;
private const string ConnectionStringKey = "DefaultConnectionString";
private const string DialectKey = "Dialect";
}
我为什么要创建IConfigurationManager 接口?
除此之外,我想在我的生产代码中直接使用 Ninject 绑定它。所以我不需要接口的具体实现,因此我对上述异常感到非常惊讶。
kernel.Bind<IConfiguration>().To<ConfigurationManager>().InSingletonScope();
这样做可以让我对我的ConfigurationService 进行单元测试。
有什么想法吗?
【问题讨论】:
标签: c# unit-testing ninject moq