开发者

App.config in Test Projects

I'm building an ASP.NET app in VS2010. I have a number of separate assemblies (class libraries) and corresponding Test projects for each.

In one of the class libraries I use an App.config file to store settings. The assembly itself uses the following code to retrieve settings:

 string tmp = ConfigurationManager.AppSettings["mySetting"];

The problem is that when I try to create a Unit Test in a separate test project, the test does not pick up the setting in the App.config file. If I COPY the App.config file into the Test project, it works.

How can I ensure that each assembly use开发者_StackOverflows its own copy of an App.config file. It would introduce problems if I had to copy config files around. There's an additional problem because there may be multiple config files, one per assembly - how could they all co-exist in a single test project anyway?

Thanks!


Well, if you need a App.config file shared across several projects, I would simply "Add as Link" the original App.config file in each project.

Let's say you have ProjectA with the original App.config. Then you have ProjectATest1 and ProjectATest2. In each of the TestX project:

  1. right click on the solution name in Visual Studio
  2. select "Add Existing Item"
  3. navigate to the ProjectA App.config and select it
  4. click in the "Add" button down arrow
  5. select "Add as Link"

It'll create a App.config shortcut in each TestX project. If you change it, it will change everywhere.

Hope this helps.


First up, if you're doing unit testing, then you probably want to look at mocking out the configuration, rather than reading it anyway.

If you really want to make the config available (I've done it for integration tests in the past), then you can add a post-build step to your assemblys (I'm assuming a 1-1 mapping of assembly to test-assemblies).

The post build step (on your test assembly) would look something like this:

  copy /y  "<path to your assembly under test>.dll.config" "$(TargetDir)\$(TargetName).dll.config"

Essentially, you're copying the app.config that has been renamed for you by visual studio for the assembly you're testing, to match the expected configuration name for your test assembly.


One should not have config files for the assemblies. If you do so, every application will end up having one config file per dll/reference project.

The assemblies pick up the config values from the application (Windows/Web) context in which they are loaded.

So if you have an WebApp, the assemblies would use WebApp's web.config file to read the config values. Similarly if you have a Windows App/Unit Test app, the libraries should read the values from app.config.

Please read this related question - C#.NET Compiling the settings.settings file from various projects in a solution into 1 config file

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜