Trouble with NUnit when determining the assembly&#

2020-02-09 05:49发布

I've just started to work with NUnit in order to provide some test coverage for my projects.

Within my main library.dll I need to load up configuration data from an external file that goes with the library, library.xml.

This works fine when I'm using the library, because I use the following to get the directory in which to look for the config file:

string settingspath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

The problem I've noticed is that when I'm unit testing with NUnit, it copies my assemblies to a Shadow Copy, but doesn't take any of the other files with it, so of course my init fails due to missing config files.

Should I be doing something different to locate config files from within my library? (it's a server app, and I don't want to use the standard app settings, or user's local settings, etc)

标签: .net nunit
8条回答
太酷不给撩
2楼-- · 2020-02-09 06:44

Encountered the same problem ... following is my workout:

Before the SUT run, update AppDomain's Base Directory in this way....

String root_path = "{{your path}}";
AppDomain.CurrentDomain.SetData("APPBASE", root_path);
查看更多
We Are One
3楼-- · 2020-02-09 06:46

Use can use TestContext.CurrentContext.TestDirectory as mentioned by Charlie Poole from NUnit here:

The need to access files in the same directory as the test assembly is the most commonly cited reason for disabling shadow copy. However, this is spurious.

NUnit doesn't copy any assemblies: shadow copy is a function of .NET itself. Consequently, the problem needs to be viewed as "How can I access the file where it is?" rather than "How can I get the file copied to where I think it should be?"

There are three ways to locate a file that is located in the same directory as the assembly:

1) Use Assembly.Codebase - this will give you the location as a URI, which you must then tranform to an appropriate path.

2) Use the current directory, which NUnit has historically set to directory containing the executing test assembly. However, this may not be true for future releases.

3) Use NUnit's TestContext.CurrentContext.TestDirectory, which is the available in the most recent releases.

All of these approaches actually use Assembly.Codebase under the covers, with NUnit doing the work of tranforming the URI correctly in #2 and #3. The common approach of using Assembly.Location is incorrect, unless you actually want the location of the shadow copy cache.

查看更多
登录 后发表回答