I currently have 2 projects, one is a standard ASMX web service and the other is a test project. The web service project has a Web.config file that contains my connection string. I’m aware of how to change the connection string to qa or production. My issue is that I’m unsure how to change the connection string for my tests project. What I want is to use SQLite for tests.
Here is what my targets file looks like that I added to my tests .csproj file.
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ConnectionString>Data Source=:memory:</ConnectionString>
</PropertyGroup>
<Target Name="BeforeBuild"
DependsOnTargets="Clean" />
<Target Name="AfterBuild"
DependsOnTargets="UpdateConfigFileForEnvironment" />
<Target Name="UpdateConfigFileForEnvironment">
<PropertyGroup>
<AppConfigFileName>$(OutDir)Web.config</AppConfigFileName>
</PropertyGroup>
<FileUpdate
Files="$(AppConfigFileName)"
Encoding="ASCII"
Regex="ConnectionStringBuild"
ReplacementText="$(ConnectionString)" />
</Target>
</Project>
And here is the Web.config file in the web service project. I omitted the majority of the content as it’s irrelevant.
<appSettings>
<add key="ConnectionString" value="ConnectionStringBuild" />
</appSettings>
The issue when I run my unit tests via ReSharper in VS2008 getting the AppSettings entry ConnectionString nothing is returned. Also, if I run msbuild in the command line on my test project the connection string successfully gets updated.
How can I modify the connection string when running tests?
You should structure your data access classes in such a way that you pass a connection string into it as a dependency (see Configuration Settings are a Dependency by Paul Hiles).
This will allow you to pass in a different connection string in your test code from the one in configuration.