Test project and configuration file

I have this setup in my Visual Studio 2008 solution: one WCF service project (WCFService) that uses a library (Lib1, which requires some configuration entries in the app.config file). I have a unit test (MSTest) project that contains tests related to Lib1. To run these tests, I need a configuration file in a test project. Is there a way to download it automatically from WCFService, so I donโ€™t need to change configuration entries in two places?

+2
source share
1 answer

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(); } 
+2
source

Source: https://habr.com/ru/post/1343539/


All Articles