Ali Sharabiani Ali Sharabiani - 24 days ago 8
C# Question

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

Description

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: (
test.png
), which is located in the
Resources
folder of my unit test project. And I've set the
Copy to Output
property to
Always
.

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"
.

Issue

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:


System.IO.DirectoryNotFoundException

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
    bin/Debug
    and
    bin/Release
    folders. Then it copies all the required project files in that folder. This causes sometimes the file actually does not exist?



Question

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

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;
    }

Then:

    string projectDir = Path.GetDirectoryName(GetFilePath());
    string testFile = Path.Combine(projectDir, @"Resources\test.png";