我目前有 2 个项目,一个是标准的 ASMX 网络服务,另一个是测试项目。 Web 服务项目有一个包含我的连接字符串的 Web.config
文件。我知道如何将连接字符串更改为质量检查或生产。我的问题是我不确定如何更改我的测试项目的连接字符串。我想要的是使用 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
,连接字符串会成功更新。
如何在运行测试时修改连接字符串?
最佳答案
您应该以将连接字符串作为依赖项传递给它的方式构建您的数据访问类(参见 Paul Hiles 的 Configuration Settings are a Dependency)。
这将允许您在测试代码中传递与配置中不同的连接字符串。
关于c# - 通过 Visual Studio 2008 运行测试时如何修改 Web.config 中的连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402279/