Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit - assembly that reads and writes file

I am unit testing an assembly that uses File.WriteAllLines() and File.ReadAllText() to read and write persistent data. When I run the unit test with the NUnit Gui the test fails with an unauthorizedAccessException.

The path that the file is attempting to read and write is being affected of course by the location of program execution. Depending on if I run NUnit under Visual Studio or directly from the Nunit /bin folder, this is where the attempted read and write operation is taking place.

I have tried to run NUnit as administrator and have copied all of the assemblies directly to the NUnit /bin folder and the test still fails.

I do not want to directly set a path in the assembly.

Any ideas on how to resolve this issue?

like image 911
Joe Pitz Avatar asked Sep 18 '25 23:09

Joe Pitz


2 Answers

You could use Path.GetTempFileName to get a temporary file to write to.

Alternatively, you could use Assembly.Location to find out where your assembly is, and use that as the directory.

like image 114
Jon Skeet Avatar answered Sep 20 '25 13:09

Jon Skeet


With NUnit 3 you should use TestContext to get either TestDirectory or WorkDirectory. Also there are File Asserts and Directory Asserts, which may help you write your tests in a more readable way.

like image 26
Michael Kruglos Avatar answered Sep 20 '25 15:09

Michael Kruglos