I am working on some unit tests for a class. This class is working with a file. I have implemented several unit tests and run them on their own, but noticed that the test fails, when I let them all run at the same time. So I figured out that VisualStudio is running the unit tests in parallel.
To avoid problems during the preparation of the file for each test, I tried to implement a thread lock. But so far this is not working.
Following up, I have provided a simple example to explain my problem:
[TestClass]
public class UnitTest1
{
private static object lockObject = new object();
private void DoSomething()
{
File.Create(@"D:\test.txt");
for (int i = 0; i < 100000; i++)
{
}
File.Delete(@"D:\test.txt");
}
[TestMethod]
public void TestMethod1()
{
lock (lockObject)
{
DoSomething();
}
}
[TestMethod]
public void TestMethod2()
{
lock (lockObject)
{
DoSomething();
}
}
}
The tests are failing because each process cannot access the file, since it is already in use from a different process.
Does anyone know what I did wrong?