首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TestCaseSource元素在NUnit测试中的处理

TestCaseSource元素在NUnit测试中的处理
EN

Stack Overflow用户
提问于 2016-06-13 08:47:42
回答 1查看 500关注 0票数 2

我将TestCaseSource与NUnit结合使用。下面的代码生成表示存档条目的IEnumerable of TestCaseData,它是测试的输入。

代码语言:javascript
复制
        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()));
    }

上面的代码在下面的行中失败:

代码语言:javascript
复制
zipArchiveEntry.Open()

除以下情况外:

System.ObjectDisposedException“无法访问已释放的对象.对象名称:'ZipArchive'.”

是否有任何方法来控制为测试数据用例创建的对象的处理?

EN

回答 1

Stack Overflow用户

发布于 2016-06-16 19:23:24

问题是,ZipArchive及其子程序在using块的末尾被释放。

试着在你的夹具里安装这样的东西:

代码语言:javascript
复制
// 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);
}

关键是在创建测试用例数据时设置静态成员,然后在夹具拆卸时对其进行处理。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37785331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档