C# – Integration testing and database connection string in app.config

cdatabaseintegration-tests

I am working on a project where SqlConnection is created via a static method, lets say it's DatabaseAccess.GetSqlConnection(). This method reads the .config file to get the connection string and creates a connection.

Is it ok to refactor the code to use an ISqlConnectionCreator (or ISqlConnectionFactory) responsible for creating the actual connections just for the sake of testing (as it seems more "by the book" for me) or go easy and just create a .config file in the test project containing test connection strings?

The second solution seems more error-prone and creates an indirect relation between tests and the tested classes.

I want to make sure there is a justification for the extra work of refactoring code to use the injected connection creator.

Best Answer

From a pragmatic view I would recommend to use whatever works best, with the least maintenance effort.

In this specific situation, I would probably go with "option 3": separate the part which reads the connection string from the part which creates the actual connection into two different methods. So the connection string becomes an input parameter of method 2, and in your test code, you can omit the config evaluation and provide the test connection string any way you like, for example, as part of the hardcoded test data. As a result, you do neither need a test config file, nor an ISqlConnectionCreator.

Related Topic