Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load this file into an NUnit Test?

I have the following IntegrationTest project structure ...

enter image description here

If i wish to use that test data 126.txt in an NUnit Test, how do I load that plain txt file data?

NOTE: The file is -linked- and I'm using c# (as noted by the image).

cheers :)

like image 661
Pure.Krome Avatar asked May 21 '11 08:05

Pure.Krome


People also ask

How NUnit is used in unit testing?

To mark a method as a test case, we need to add a Test attribute. It tells the NUnit framework that it should run this method. It's a good approach to run our test methods with different arguments, without copy-pasting our test methods. We can define test method parameters by using the [TestCase] attribute.


2 Answers

You could specify in the properties of the file to be copied to the output folder and inside the unit test:

string text = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestData", "126.txt")); 

As an alternative you could embed this file as a resource into the test assembly and then:

var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream("ProjectName.Tests.IntegrationTests.TestData.126.txt")) using (var reader = new StreamReader(stream)) {     string text = reader.ReadToEnd(); } 
like image 152
Darin Dimitrov Avatar answered Sep 21 '22 12:09

Darin Dimitrov


If you do not want the files as ManifestResources, but just as file on the system. See Trouble with NUnit when determining the assembly's directory for more info and this answer in particular

Also interesting is the info from NUnit https://bugs.launchpad.net/nunit-vs-adapter/+bug/1084284/comments/3

But here is the quick info:

Path.Combine(TestContext.CurrentContext.TestDirectory, @"Files\test.pdf") 

Where Files\test.PDF is just a file in your test project, with build action content and copy to output directory copy if newer

All credits go out to the people in the other post, but took me a while to find that answer, and that is the reason why i am adding the answer to this post.

like image 26
Ben Croughs Avatar answered Sep 18 '22 12:09

Ben Croughs