测试项目和配置文件配置文件、测试、项目

2023-09-06 09:44:49 作者:▓招摇过市。

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

I have this kind of setup in my Visual Studio 2008 solution: One WCF service project (WCFService) which uses library (Lib1, which requires some configuration entries in app.config file). I have a unit test project (MSTest) which contains tests related to Lib1. In order to run those tests, I need a config file in test project. Is there any way to load it automatically from WCFService, so I do not need to change config entries on two places?

推荐答案

而你的图书馆从整个code app.config文件读取属性直接将会使你的code脆而硬测试。这将是最好有负责读取配置和强类型的方式存储您的配置值的一类。有这个类要么实现从配置定义属性的接口或使虚拟的属性。然后,你可以模拟这个类后(使用像RhinoMocks或手工制作一个假的类,它也实现了界面的框架)。注入类的实例为每个通过构造需要配置值接入类别。设置它,这样,如果注入的值为空,那么它会创建正确的类的实例。

Having your library read properties directly from the app.config file throughout the code is going to make your code brittle and hard to test. It would be better to have a class responsible for reading the configuration and storing your configuration values in a strongly-typed manner. Have this class either implement an interface that defines the properties from the configuration or make the properties virtual. Then you can mock this class out (using a framework like RhinoMocks or by hand crafting a fake class that also implements the interface). Inject an instance of the class into each class that needs access to the configuration values via the constructor. Set it up so that if the injected value is null, then it creates an instance of the proper class.

 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();
 }
 
精彩推荐
图片推荐