C# 单元测试项目能否加载目标应用程序的 app.config 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/344069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:57:01  来源:igfitidea点击:

Can a unit test project load the target application's app.config file?

c#.netunit-testingapp-config

提问by Jordan Parmer

I am unit testing a .NET application (.exe) that uses an app.config file to load configuration properties. The unit test application itself does not have an app.config file.

我正在对使用 app.config 文件加载配置属性的 .NET 应用程序 (.exe) 进行单元测试。单元测试应用程序本身没有 app.config 文件。

When I try to unit test a method that utilizes any of the configuration properties, they return null. I'm assuming this is because the unit test application is not going to load in the target application's app.config.

当我尝试对使用任何配置属性的方法进行单元测试时,它们返回null。我假设这是因为单元测试应用程序不会加载到目标应用程序的 app.config 中。

Is there a way to override this or do I have to write a script to copy the contents of the target app.config to a local app.config?

有没有办法覆盖它,或者我必须编写一个脚本来将目标 app.config 的内容复制到本地 app.config?

Thispost kind-of asks this question but the author is really looking at it from a different angle than I am.

这篇文章有点问这个问题,但作者确实从与我不同的角度看待它。

EDIT:I should mention that I'm using VS08 Team System for my unit tests.

编辑:我应该提到我正在使用 VS08 Team System 进行单元测试。

采纳答案by Jeromy Irvine

The simplest way to do this is to add the .configfile in the deployment section on your unit test.

最简单的方法是.config在单元测试的部署部分添加文件。

To do so, open the .testrunconfigfile from your Solution Items. In the Deployment section, add the output .configfiles from your project's build directory (presumably bin\Debug).

为此,请.testrunconfig从您的解决方案项中打开该文件。在部署部分,添加.config项目构建目录(大概是bin\Debug)中的输出文件。

Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.

在运行测试之前,部署部分中列出的任何内容都将复制到测试项目的工作文件夹中,因此您的依赖于配置的代码将运行良好。

Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .configto match the unit test's name.

编辑:我忘了补充,这在所有情况下都不起作用,因此您可能需要包含一个启动脚本来重命名输出.config以匹配单元测试的名称。

回答by Cory Foy

If you are using NUnit, take a look at this post. Basically you'll need to have your app.config in the same directory as your .nunit file.

如果您正在使用 NUnit,请查看这篇文章。基本上,您需要将 app.config 与 .nunit 文件放在同一目录中。

回答by Patrick Desjardins

I use NUnitand in my project directory I have a copy of my App.Config that I change some configuration (example I redirect to a test database...). You need to have it in the same directoryof the tested project and you will be fine.

我使用NUnit,在我的项目目录中,我有一个 App.Config 的副本,我更改了一些配置(例如我重定向到测试数据库......)。你需要把它放在被测试项目的同一目录中,你会没事的。

回答by bryanbcook

Whether you're using Team System Testor NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.

无论您使用的是Team System Test还是NUnit,最佳实践都是为您的测试创建一个单独的类库。 编译时,只需将 App.config 添加到您的测试项目中,就会自动复制到您的 bin 文件夹中

If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :

如果您的代码依赖于特定的配置测试,那么我编写的第一个测试将验证配置文件是否可用(这样我就知道我没有疯):

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

And the test:

和测试:

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.

理想情况下,您应该编写代码,以便将配置对象传递到您的类中。这不仅将您与配置文件问题分开,而且还允许您为不同的配置场景编写测试。

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

回答by bryanbcook

In Visual Studio 2008 I added the app.configfile to the test project as an existing item and selected copy as link in order to make sure it's not duplicated. That way I only have one copy in my solution. With several test projects it comes in really handy!

在 Visual Studio 2008 中,我将该app.config文件作为现有项目添加到测试项目中,并选择了副本作为链接以确保它不会重复。这样我的解决方案中只有一个副本。有了几个测试项目,它就派上用场了!

Add Existing Item

添加现有项目

Add As Link

添加为链接

回答by Jane

I couldn't get any of these suggestions to work with nUnit 2.5.10 so I ended up using nUnit's Project -> Edit functionality to specify the config file to target (as others have said it needs to be in the same folder as the .nunit file itself). The positive side of this is that I can give the config file a Test.config name which makes it much clearer what it is and why it is)

我无法在 nUnit 2.5.10 中获得任何这些建议,所以我最终使用 nUnit 的项目 -> 编辑功能来指定要定位的配置文件(正如其他人所说,它需要与 . nunit 文件本身)。这样做的积极方面是我可以给配置文件一个 Test.config 名称,这使它更清楚它是什么以及为什么它是)

回答by Antti

If you have a solution which contains for example Web Application and Test Project, you probably want that Test Project uses Web Application's web.config.

如果您有一个包含 Web 应用程序和测试项目的解决方案,您可能希望该测试项目使用 Web 应用程序的 web.config。

One way to solve it is to copy web.config to test project and rename it as app.config.

一种解决方法是将 web.config 复制到测试项目并将其重命名为 app.config。

Another and better solution is to modify build chain and make it to make automatic copy of web.config to test projects output directory. To do that, right click Test Application and select properties. Now you should see project properties. Click "Build Events" and then click "Edit Post-build..." button. Write following line to there:

另一个更好的解决方案是修改构建链并使其自动复制 web.config 到测试项目输出目录。为此,右键单击测试应用程序并选择属性。现在您应该看到项目属性。单击“构建事件”,然后单击“编辑构建后...”按钮。在那里写下一行:

copy "$(SolutionDir)\WebApplication1\web.config" "$(ProjectDir)$(OutDir)$(TargetFileName).config"

And click OK. (Note you most probably need to change WebApplication1 as you project name which you want to test). If you have wrong path to web.config then copy fails and you will notice it during unsuccessful build.

然后单击确定。(请注意,您很可能需要更改 WebApplication1 作为您要测试的项目名称)。如果您的 web.config 路径错误,则复制失败,您会在构建失败时注意到它。

Edit:

编辑:

To Copy from the current Project to the Test Project:

从当前项目复制到测试项目:

copy "$(ProjectDir)bin\WebProject.dll.config" "$(SolutionDir)WebProject.Tests\bin\Debug\App.Config"

回答by Zyo

If you application is using setting such as Asp.net ConnectionString you need to add the attribute HostType to your method, else they wont load even if you have an App.Config file.

如果您的应用程序正在使用诸如 Asp.net ConnectionString 之类的设置,您需要将 HostType 属性添加到您的方法中,否则即使您有 App.Config 文件,它们也不会加载。

[TestMethod]
[HostType("ASP.NET")] // will load the ConnectionString from the App.Config file
public void Test() {

}

回答by Hari Das

This is very easy.

这很容易。

  • Right click on your test project
  • Add-->Existing item
  • You can see a small arrow just beside the Add button
  • Select the config file click on "Add As Link"
  • 右键单击您的测试项目
  • 添加-->现有项目
  • 您可以在“添加”按钮旁边看到一个小箭头
  • 选择配置文件点击“添加为链接”

回答by MichaelChan

This is a bit old but I found a better solution for this. I was trying the chosen answer here but looks like .testrunconfig is already obsolete.

这有点旧,但我为此找到了更好的解决方案。我在这里尝试选择的答案,但看起来 .testrunco​​nfig 已经过时了。

1. For Unit Tests, Wrap the config is an Interface (IConfig)

1. 对于单元测试,包装配置是一个接口(IConfig)

for Unit tests, config really shouldn't be part of what your testing so create a mock which you can inject. In this example I was using Moq.

对于单元测试,配置真的不应该成为你测试的一部分,所以创建一个你可以注入的模拟。在这个例子中,我使用的是 Moq。

Mock<IConfig> _configMock;
_configMock.Setup(config => config.ConfigKey).Returns("ConfigValue");
var SUT = new SUT(_configMock.Object);

2. For Integration test, dynamically add the config you need

2.对于集成测试,动态添加你需要的配置

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if(config.AppSettings.Settings[configName] != null)
{
    config.AppSettings.Settings.Remove(configName);
}
config.AppSettings.Settings.Add(configName, configValue);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");