2009-05-28 103 views
2

我在Visual Studio 2008解决方案中有这种设置:一个WCF服务项目(WCFService)使用库(Lib1,它需要app.config文件中的一些配置项)。我有一个单元测试项目(MSTest),其中包含与Lib1相关的测试。为了运行这些测试,我需要一个测试项目中的配置文件。有没有办法从WCFService自动加载它,所以我不需要在两个地方更改配置条目?测试项目和配置文件

+0

可以收集在一个文件中(或几个)的所有配置条目和使用SectionInformation.ConfigSource属性来自WCF服务项目和测试项目指向该文件。 – charisk 2009-05-28 11:46:59

回答

2

让您的库直接从app.config文件直接读取代码中的属性,这会让您的代码变得脆弱而难以测试。最好有一个类负责读取配置并以强类型的方式存储配置值。让这个类实现一个接口,该接口定义配置中的属性或使属性变为虚拟。然后你可以嘲笑这个类(使用像RhinoMocks这样的框架,或者手工制作一个也实现了界面的假类)。将类的实例注入每个需要通过构造函数访问配置值的类中。设置它,以便如果注入的值为空,则它创建适当类的实例。

public interface IMyConfig 
{ 
     string MyProperty { get; } 
     int MyIntProperty { get; } 
} 

public class MyConfig : IMyConfig 
{ 
     public string MyProperty 
     { 
     get { ...lazy load from the actual config... } 
     } 

     public int MyIntProperty 
     { 
     get { ... } 
     } 
    } 

public class MyLibClass 
{ 
     private IMyConfig config; 

     public MyLibClass() : this(null) {} 

     public MyLibClass(IMyConfig config) 
     { 
      this.config = config ?? new MyConfig(); 
     } 

     public void MyMethod() 
     { 
      string property = this.config.MyProperty; 

      ... 
     } 
} 

测试

public void TestMethod() 
{ 
     IMyConfig config = MockRepository.GenerateMock<IMyConfig>(); 
     config.Expect(c => c.MyProperty).Return("stringValue"); 

     var cls = new MyLib(config); 

     cls.MyMethod(); 

     config.VerifyAllExpectations(); 
}