bbsimonbb
bbsimonbb

Reputation: 28992

In my xunit tests, why is this run-once code running twice?

I have 3 tests that require the same setup of a temp file. Following this answer I've implemented a collection, to try to do the setup and takedown once. It's not working. A breakpoint in the setup and takedown blocks fires twice, and I have to protect the block with ifs. Why twice, when I have three tests? I want it to fire once. Three I could understand, but why twice?

The following code will show the problem. I've evacuated the tests and put the protecting ifs in comments. If you put breakpoints in the File.WriteAllText and File.Delete, you should see them fire twice each, and the second hit on File.Delete will generate an exception.

using FluentAssertions;
using System;
using System.IO;
using Xunit;

namespace Tests
{
    [Collection("FileSystemHelper Collection")]
    public class FileSystemHelperShould : IClassFixture<FileFixture>
    {
        FileFixture _fileFixture;

        public FileSystemHelperShould(FileFixture fileFixture)
        {
            _fileFixture = fileFixture;
        }
        [Fact]
        public void WhenCalledWithMangledFilePath_ReturnCorrectCapitalization()
        {
            // test goes here
        }

        [Fact]
        public void WhenCalledWithMangledFolderPath_ReturnCorrectCapitalization()
        {
            // test goes here
        }
        [Fact]
        public void WhenCalledAsExtensionMethod_ReturnCorrectCapitalization()
        {
            // test goes here
        }
    }
    [CollectionDefinition("FileSystemHelper Collection")]
    public class FileHelperCollection : ICollectionFixture<FileFixture>
    {
        // empty class defines the collection
    }
    public class FileFixture : IDisposable
    {
        public string TempDir { get; set; }
        public string NewFolder { get; set; }
        public string NewFile { get; set; }
        public FileFixture()
        {

            TempDir = Path.GetTempPath();
            NewFolder = Path.Combine(TempDir, "NeWfoLder");
            NewFile = Path.Combine(NewFolder, "NewfIlE.Txt");
            //if (!Directory.Exists(NewFolder))
                Directory.CreateDirectory(NewFolder);
            //if (!File.Exists(NewFile))
                File.WriteAllText(NewFile, "Hello Cobber");
        }

        public void Dispose()
        {
            try
            {
                //if (File.Exists(NewFile))
                    File.Delete(NewFile);
                //if (Directory.Exists(NewFolder))
                    Directory.Delete(NewFolder);
            }
            catch (Exception) { }
        }
    }
}

Upvotes: 2

Views: 504

Answers (1)

Adam Vincent
Adam Vincent

Reputation: 3811

It's an open GitHub Issue, marked as bug

https://github.com/xunit/xunit/issues/2268

Upvotes: 1

Related Questions