2016-06-13 111 views
1

我正在使用NUnit的TestCaseSource。以下代碼生成表示歸檔條目的TestCaseData的IEnumerable,它是測試的輸入。處理NUnit測試中的TestCaseSource元素

 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' 「。

是否有任何方法來控制爲測試數據案例創建的對象的處置?

+0

如何記住靜態變量中創建的對象,並調用[TestFixtureTearDown](http://www.nunit.org/index.php?p=fixtureTeardown&r=2.4.8)中的每個對象的Dispose()。 – scher

+0

@scher是的,這是可能的,但不會很漂亮。 –

回答

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); 
} 

的關鍵是創建測試用例數據時,則在夾具處置它推倒設置靜態成員。