5.对泛型配置接口的实现进行单元测试
使用最流行的单元测试框架和Mock类库:xUnit+Moq进行单元测试。
public class AppConfigAdapterTest { [Fact] public void GetStringTest() { var key = "key"; var value = "value"; var configuration = new AppConfigAdapter(this.GetConfigurationManager(o => o.Add(key, value.ToString()))); Assert.Equal(configuration.Get(key, string.Empty), value); } [Fact] public void GetIntTest() { var key = "key"; var value = 1; var configuration = new AppConfigAdapter(this.GetConfigurationManager(o => o.Add(key, value.ToString()))); Assert.Equal(configuration.Get(key, int.MinValue), value); } [Fact] public void GetBoolTest() { var key = "key"; var value = true; var configuration = new AppConfigAdapter(this.GetConfigurationManager(o => o.Add(key, value.ToString()))); Assert.Equal(configuration.Get(key, false), value); } [Fact] public void GetDateTimeTest() { var key = "key"; var value = DateTime.Parse(DateTime.Now.ToString()); var configuration = new AppConfigAdapter(this.GetConfigurationManager(o => o.Add(key, value.ToString()))); Assert.Equal(configuration.Get(key, DateTime.MinValue), value); } [Fact] public void GetDecimalTest() { var key = "key"; var value = 1.1m; var configuration = new AppConfigAdapter(this.GetConfigurationManager(o => o.Add(key, value.ToString()))); Assert.Equal(configuration.Get(key, decimal.MinValue), value); } private IConfigurationManager GetConfigurationManager(Action<NameValueCollection> set) { var appSettings = new NameValueCollection(); set(appSettings); var configurationManager = new Mock<IConfigurationManager>(); configurationManager.Setup(o => o.AppSettings).Returns(appSettings); return configurationManager.Object; } } |
运行结果:
6.总结
使依赖ConfigurationManager静态类的代码转换为依赖IConfigurationManager接口,运行时注入ConfigurationManagerWrapper实现类。单元测试时使用Mock模拟IConfigurationManager对象。