Search code examples
c#unit-testingnunitnunit-3.0

File access issue in unit test running some test cases


I have a concurrency issue in my test's arrange block, where I do create some files in a subfolder(IO exception on file access in some test case runs). I have a parameterized test and test cases seems to run in parallel despite [NonParallelizable] attribute.

The issue is observed on tests run in Test-Explorer of VS2019.

Is there a possibility to prevent a parallel execution of test cases for some tests, it would be nice, if another tests(not test cases) in the fixture could still run in parallel.

[TestFixture]
public class ClassToTest_Fixture
{
    [TestCase("SubFolder", new[] { "a", "b", "c", "d", "e", "f", "g", "h" })]
    [TestCase("SubFolder", new[] { "a", "b", "c", "d", "e", "f", "g", "h" })]
    [TestCase("SubFolder", new[] { "a", "b", "c", "d", "e", "f", "g", "h" })]
    [TestCase("SubFolder", new[] { "a", "b", "c", "d", "e", "f", "g", "h" })]
    [TestCase("SubFolder", new[] { "a", "b", "c", "d", "e", "f", "g", "h" })]
    [NonParallelizable] //Doesn't help
    public void TestMethod(string folder, string[] files)
    {
        #region Arrange
        var fldr = Path.Combine(TestContext.CurrentContext.TestDirectory, folder);
        if(!Directory.Exists(fldr))
        {
            Directory.CreateDirectory(fldr);
        }
        foreach(var fn in files)
        {
            File.Create(Path.Combine(fldr, fn));
        } 
        #endregion Arrange

        //Act
        //Assert
    }

    [Test]
    public void TestMethodCanBeRunInParallel( )
    {
    }
}

Solution

  • I have a concurrency issue .... test cases seems to run in parallel was a wrong assumption, which I have made intuitively. After I have added an output with a time stamps and Thread.CurrentThread.ManagedThreadId I have found that testcases do run non parallel even without [NonParallelizable] attribute.

    The issue was (my bad), that I haven't payed enough attention to the return value of File.Create(fileName), which is a FileStream.
    Since I have not disposed a FileStream I had issues (IO exceptions) with next test case run.

    Adding FileStream.Close() has solved the issue:

    ...
    File.Create(Path.Combine(fldr, fn))?.Close();
    ...