views:

109

answers:

2

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?

A: 

You can gather all the configuration entries in one file (or several) and use the SectionInformation.ConfigSource property to point to that file from both the WCF service project and the test project.

roul
+2  A: 

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;

          ...
      }
 }

Test

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

      var cls = new MyLib( config );

      cls.MyMethod();

      config.VerifyAllExpectations();
 }
tvanfosson