2011-09-06 41 views
2

過濾非斷言例外我已經不具有明確的斷言表達式的方法測試。返回的測試值是一個非常長的字符串,必須由程序員檢查它是否正確。出於這個原因,如果代碼執行沒有例外,我打電話'Assert.Inclusive'。C#如何在單元測試

但是,如果某種異常的拋出,我想稱之爲「Assert.Fail」與異常消息。事情是這樣的:

 [TestMethod()] 
     public void Test() 
     { 
     try { 
      string toBeChecked = MethodToBeTested(); 
      //the string is so particular that no clear 
      //assertion can be made about it. 

      Console.WriteLine(toBeChecked);    
      Assert.Inconclusive("Check the console output.");    
     } catch(Exception e) { 
      Assert.Fail(e.Message); 
     } 
     } 

這段代碼的問題是,如果沒有正規的異常被拋出,Assert.Inconclusive方法也拋出了被逮住的異常,所以Assert.Fail被調用,並從IDE測試結果窗格中似乎測試失敗了。這不是我想要的。

有沒有辦法來過濾例外,如捕捉每個異常,但斷言樣的呢?

(我使用.NET框架3.5SP1)

+0

這是否可以離散測試的方法調用其他方法?如果您可以測試它們都按預期工作,則可以在調用方法中獲得一些信心。 –

+0

@Greg B:在這種情況下,它是一種「單片」方法。但我不介意,我只想要其他開發人員能夠看到不確定的結果,但沒有例外,除非實際上有一個。 –

回答

2

爲什麼不忽略Assert.Inconclusive()?事實上,爲什麼要捕獲任何異常 - 如果代碼拋出異常,單元測試框架將會將其標記爲失敗。少即是多:

[TestMethod()] 
    public void Test() 
    { 
    string toBeChecked = MethodToBeTested(); 
    Console.WriteLine(toBeChecked);    
    } 

但是,這是一個貧窮的單元測試,如果我們不能自動檢查的結果。我們正在檢查的是沒有拋出異常。 對於結果字符串,您是否沒有斷言?

例如,是不爲空或空?我們期望它包含一個我們可以測試的特定子字符串嗎?

至少給測試一個有用的名字,其中包括像:ManualAssertRequired

+0

好吧,我不知道,拋出異常意味着測試失敗。不幸的是,沒有額外的斷言可以做出,所以是的,測試並沒有像往常一樣有用。 –

1

努力趕上,而不是Exception特定的異常類型或添加其他漁獲量由Assert.Inconclusive方法是AssertInconclusiveException引起NUnit的例外......

例如修改這樣的:

[TestMethod()] 
    public void Test() 
    { 
    try { 
     string toBeChecked = MethodToBeTested(); 
     //the string is so particular that no clear 
     //assertion can be made about it. 

     Console.WriteLine(toBeChecked);    
     Assert.Inconclusive("Check the console output.");  
    } catch(AssertInconclusiveException e) { 
     // do nothing... 
    } catch(Exception e) { 
     Assert.Fail(e.Message); 
    } 
    } 
+0

是否存在AssertInconclusiveException的超類,它還會捕獲其他每個斷言? –

+1

的確有:'UnitTestAssertException' –

2

的Assert.Inconclusive方法應該拋出一個AssertInconclusiveException所以你可以標記試驗,ExcpectedException(typeof(AssertInconclusiveExcpetion))或使用事端g像這樣:

[TestMethod()] 
    public void Test() 
    { 
    try { 
     string toBeChecked = MethodToBeTested(); 
     //the string is so particular that no clear 
     //assertion can be made about it. 

     Console.WriteLine(toBeChecked);    
     Assert.Inconclusive("Check the console output.");    
    } catch(AsssertInconclusiveException) { 
     /* Do nothing */ 
    } 
    } catch(Exception e) { 
     Assert.Fail(e.Message); 
    } 
    }