如何通过Visual Studio 2008运行测试时修改Web.config中的连接字符串?

时间:2012-05-01 18:26:04

标签: c# visual-studio testing msbuild nunit

我目前有2个项目,一个是标准的ASMX Web服务,另一个是测试项目。 Web服务项目有一个Web.config文件,其中包含我的连接字符串。我知道如何将连接字符串更改为qa或production。我的问题是我不确定如何更改我的测试项目的连接字符串。我想要的是使用SQLite进行测试。

以下是我添加到测试.csproj文件中的目标文件的样子。

<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>

这是Web服务项目中的Web.config文件。我省略了大部分内容,因为它无关紧要。

  <appSettings>
    <add key="ConnectionString" value="ConnectionStringBuild" />
  </appSettings>

在VS2008中通过ReSharper运行单元测试时,返回AppSettings条目ConnectionString的问题。此外,如果我在测试项目的命令行中运行msbuild,则连接字符串会成功更新。

如何在运行测试时修改连接字符串?

1 个答案:

答案 0 :(得分:3)

您应该以这样的方式构建数据访问类,即将连接字符串作为依赖项传递给它(请参阅Paul Hiles的Configuration Settings are a Dependency)。

这将允许您在测试代码中传入与配置中的连接字符串不同的连接字符串。