Visual Studio Unit Tests with Resources


I have a project that needs to load a lot of historical data from a JSON file to support various computations. This is a Windows Forms app built in C# using Visual Studio 2008. In the application, I can open the JSON file like this:

string json = File.ReadAllText(Path.Combine(Application.StartupPath, "figures.json"));

But I also want to write unit tests against the parts of the app that need this file. I’m using Visual Studio’s built-in unit test framework. I was trying to figure out how to ensure the unit test can get access to the file. It turns out, I just add this annotation to any test method that needs the file:


Then I can open the file like this:

string json = File.ReadAllText(Path.Combine(testContextInstance.TestDeploymentDir, "figures.json"));

I can also put the annotation on the test class, rather than tagging each separate method. Unfortunately I can’t apply it to the whole test assembly. I was hoping I could stick it in AssemblyInfo.cs, but then I get an error that it only works on classes and methods. Oh well!

blog comments powered by Disqus Prev: Javascript: setTimeout/setInterval on Object Instances Next: C# Access Modifiers and Unit Tests