Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

.net - Trouble with NUnit when determining the assembly's directory

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...