Ali Sharabiani Ali Sharabiani - 1 year ago 60
C# Question

When multiple unit tests copy the same file, running all unit tests fail


I am writing unit tests for a method, which copies a file from a source to a destination. Basically it includes this code:

public void MyMethod()
// ...
File.Copy(source, destination, true);
// ...

In my unit test project, I have a test file: (
), which is located in the
folder of my unit test project. And I've set the
Copy to Output
property to

I have 3 unit tests which are testing this method.

When they hit the line of the code which copies the file:
source = "Resources\\test.png"


When I run the unit test individually, they all pass and everything is fine.
However, when I run All Tests in Visual Studio, I get this run time error and unit tests fail:


Could not find a part of the path 'Resources\test.png'.

My Thoughts...(UPDATED)

  • Probably because Visual Studio runs each unit tests simultaneously in a separate thread and they all accessing the same file at the same time?

  • I think for every unit test, Visual Studio is cleaning
    folders. Then it copies all the required project files in that folder. This causes sometimes the file actually does not exist?


How can I fix this problem?

Is there any settings of configurations to resolve this?

How can I run all unit tests in Visual Studio (and Team City) when multiple unit tests are accessing the same file?

Answer Source

What happened was, since I was using relative path to the testing files, for some reason when running the unit tests in batch, test runner working directory is different than when running individual tests, hence it couldn't find the directory.

So I used this function to build the absolute path to the testing files:

    private string GetFilePath([CallerFilePath] string path = "")
        return path;


    string projectDir = Path.GetDirectoryName(GetFilePath());
    string testFile = Path.Combine(projectDir, @"Resources\test.png";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download