Удаление элементов TestCaseSource в тесте NUnit

Я использую TestCaseSource с NUnit. Приведенный ниже код генерирует IEnumerable из TestCaseData, представляющих запись архива, которая является входными данными для теста.

        private class GithubRepositoryTestCasesFactory
    {
        private const string GithubRepositoryZip = "https://github.com/QualiSystems/tosca/archive/master.zip";

        public static IEnumerable TestCases
        {
            get
            {
                using (var tempFile = new TempFile(Path.GetTempPath()))
                using (var client = new WebClient())
                {
                    client.DownloadFile(GithubRepositoryZip, tempFile.FilePath);

                    using (var zipToOpen = new FileStream(tempFile.FilePath, FileMode.Open))
                    using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                    {
                        foreach (var archiveEntry in archive.Entries.Where(a =>
                            Path.GetExtension(a.Name).EqualsAny(".yaml", ".yml")))
                        {
                            yield return new TestCaseData(archiveEntry);
                        }
                    }
                }
            }
        }
    }

    [Test, TestCaseSource(typeof (GithubRepositoryTestCasesFactory), "TestCases")]
    public void Validate_Tosca_Files_In_Github_Repository_Of_Quali(ZipArchiveEntry zipArchiveEntry)
    {
        var toscaNetAnalyzer = new ToscaNetAnalyzer();

        toscaNetAnalyzer.Analyze(new StreamReader(zipArchiveEntry.Open()));
    }

Приведенный выше код не работает в следующей строке:

zipArchiveEntry.Open()

за исключением:

System.ObjectDisposedException «Не удается получить доступ к удаленному объекту. Имя объекта:« ZipArchive »».

Есть ли способ контролировать удаление объектов, созданных для тестовых данных?


person Boris Modylevsky    schedule 13.06.2016    source источник
comment
Как насчет запоминания созданных объектов в статической переменной и вызова Dispose() каждого в TestFixtureTearDown.   -  person scher    schedule 13.06.2016
comment
@scher да, это возможно, но было бы менее красиво.   -  person Boris Modylevsky    schedule 13.06.2016


Ответы (1)


Проблема в том, что ZipArchive и его дочерние элементы удаляются в конце блока using.

Попробуйте соорудить что-то подобное в своем приспособлении:

// MyDisposable an IDisposable with child elements
private static MyDisposable _parent; 

// This will be run once when the fixture is finished running
[OneTimeTearDown]
public void Teardown()
{
    if (_parent != null)
    {
        _parent.Dispose();
        _parent = null;
    }
}

// This will be run once per test which uses it, prior to running the test
private static IEnumerable<TestCaseData> GetTestCases()
{
    // Create your data without a 'using' statement and store in a static member
    _parent = new MyDisposable(true);
    return _parent.Children.Select(md => new TestCaseData(md));
}

// This method will be run once per test case in the return value of 'GetTestCases'
[TestCaseSource("GetTestCases")]
public void TestSafe(MyDisposable myDisposable)
{
    Assert.IsFalse(myDisposable.HasChildren);
}

Ключевым моментом является установка статического члена при создании данных тестового примера, а затем удаление его при разборке прибора.

person Robert Gowland    schedule 16.06.2016