If your library reads properties directly from the app.config file throughout the code, your code will become fragile and difficult to test. It would be better to have a class responsible for reading the configuration and storing your configuration values โโin a strongly typed way. Let this class implement an interface that defines properties from a configuration or makes properties virtual. You can then mock this class (using a framework like RhinoMocks or manually creating a fake class that also implements the interface). Add an instance of the class to each class that needs access to the configuration values โโthrough the constructor. Set it so that if the value entered is null, it creates an instance of the corresponding 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(); }
source share