在NUnit测试中处理TestCaseSource元素

时间:2016-06-13 08:47:43

标签: c# nunit nunit-3.0 testcasesource

我正在使用带有NUnit的TestCaseSource。下面的代码生成IEnumerable of 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'。“

有没有办法控制处理为测试数据案例创建的对象?

1 个答案:

答案 0 :(得分: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);
}

关键是在创建测试用例数据时设置静态成员,然后将其丢弃在夹具上。