views:

259

answers:

4

Hi all,

Currently I have a test class called TestClass.cs in C:\Projects\TestProject\TestClass.cs
I also have an Xml file in C:\Projects\TestProject\config\config.xml

In TestClass.cs, I have a test method to load the Xml from the filesystem like so:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Path.Combine(Assembly.GetExecutingAssembly().Location, "config\config.xml"));

Unfortunately, the Location property gives me the value:
C:\Projects\TestProject\TestResults\klaw_[computernamehere] [time here]\

instead of what I want, which is C:\Projects\TestProject\

I've tried Assembly.GetExecutingAssembly().CodeBase as well with similar results.

Any ideas?

+1  A: 

Well, it is telling the truth. Unlike NUnit / TestDriven.NET, etc - MSTest copied things around into a different folder for each test. Which is (IMO) a pain - for example, you need to either attribute files to include ([DeploymentItem]), or specify them in the testrunconfig (properties -> Deployment -> Add File...).

Contrast this to TestDriven.NET, where you could use the "Copy to Output Directory" flag.

Marc Gravell
+2  A: 

You need to mark this file with the DeploymentItemAttribute if you're using MSTest. This means it will be copied with the DLL.

David M
I added the DeploymentItemAttribute and passed in the path of the xml file, and loaded it directly in the unit test without having to worry about paths. That worked :)
Klaw
+2  A: 

Since this is a test, how about making the file an embedded resource? You can then read the embedded resource at runtime with the following code:

Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

The resource is normally the namespace + filename. But you can work this out by running the following code in the debugger:

AssemblyGetExecutingAssembly().GetManifestResourceNames();

This returns a list of embedded resources.

Justin Bannister
+1  A: 

In addition to marking an item with [DeploymentItem], you will also need to make sure your test run configuration has Enable Deployment checked along with the directory of where to grab items from.

Aaron Weiker