2009-09-02 142 views

回答

13

最接近的匹配是Assert.Inconclusive() - 它不會使測試失敗,但它也不會成功。它屬於第三階段,稱爲Inconclusive

單一的不確定測試會導致整個測試套件無法確定。

有重載支持自定義消息以及:

Assert.Inconclusive("Ploeh"); 
+6

令人煩惱的是,一個不確定的測試足以導致MSTEST.EXE返回與失敗相同的狀態碼(1),所以如果您使用批處理文件將其設置爲全部關閉,您將無法區分沒有更多的工作。 – 2011-11-14 17:35:21

3

我有一個類似的問題,因爲我使用NUnit的一些項目。嘗試使用

Console.Write("Some Warning"); 
+3

Assert.Inconclusive();實際上由NUnit支持。 http://www.nunit.org/index.php?p=utilityAsserts&r=2.5.8 – 2011-11-04 14:45:11

1

這是我黑客如何與NUnit的(我知道這個問題是關於MSTEST,但這應該工作太)警告。與往常一樣,我對任何改進都感興趣。這種方法正在爲我工​​作。

背景:我有代碼檢查測試本身的正確評論,並有邏輯來檢測是否有人複製並粘貼另一個測試而不改變評論。這些是警告我希望向開發人員顯示沒有正常Assert.Inconclusive阻止實際測試運行的開發人員。有些專注於測試,清理重構階段是刪除警告。

任務:在所有其他斷言運行後發出警告。這意味着即使在開發過程中通常在測試中出現Assert.Fail之後也會顯示警告。

實施:(最好爲所有測試文件基類):

public class BaseTestClass 
{ 
    public static StringBuilder Warnings; 

    [SetUp] 
    public virtual void Test_SetUp() 
    { 
      Warnings = new StringBuilder(); 
    } 

    [TearDown] 
    public virtual void Test_TearDown() 
    { 
     if (Warnings.Length > 0) 
     { 
      string warningMessage = Warnings.ToString(); 

      //-- cleared if there is more than one test running in the session 
      Warnings = new StringBuilder(); 
      if (TestContext.CurrentContext.Result.Status == TestStatus.Failed) 
      { 
       Assert.Fail(warningMessage); 
      } 
      else 
      { 
       Assert.Inconclusive(warningMessage); 
      } 
     } 
    } 

測試使用

[Test] 
public void Sample_Test() 
{ 
    if (condition) Warning.AppendLine("Developer warning"); 
    Assert.Fail("This Test Failed!"); 
} 

實際結果:

"This Test Failed!" 
"Developer warning" 

測試狀態失敗 - 紅色

如果測試通過並且出現警告,您將會收到Inconclusive-YELLOW狀態。

0

您可能想要使用自定義例外。

Assert.Inconclusive的問題在於,測試瀏覽器指出測試甚至沒有運行。在未來的運行測試時,特別是如果測試是由其他開發人員運行這可能會產生誤導:

enter image description here

的方式我是來更喜歡如下。首先,定義一個自定義UnitTestWarningException。我給了我一個額外的構造函數,所以我可以傳遞我的警告消息字符串。格式風格與參數:

public class UnitTestWarningException : Exception 
{ 
    public UnitTestWarningException(string Message) : base(Message) { } 

    public UnitTestWarningException(string Format, params object[] Args) : base(string.Format(Format, Args)) { } 
} 

然後,在您要結束與警告單元測試點,拋出UnitTestWarningException代替:

[TestMethod] 
public void TestMethod1() 
{ 
    . 
    . 
    . 
    try 
    { 
    WorkflowInvoker.Invoke(workflow1, inputDictionary); 
    } 
    catch (SqlException ex) 
    { 
    if (ex.Errors.Count > 0 
     && ex.Errors[0].Procedure == "proc_AVAILABLEPLACEMENTNOTIFICATIONInsert") 
    { 
     //Likely to occur if we try to repeat an insert during development/debugging. 
     //Probably not interested--the mail has already been sent if we got as far as that proc. 

     throw new UnitTestWarningException("Note: after sending the mail, proc_AVAILABLEPLACEMENTNOTIFICATIONInsert threw an exception. This may be expected depending on test conditions. The exception was: {0}", ex.Message); 
    } 
    } 
} 

結果:測試資源管理器,然後顯示,測試已經執行,但有UnitTestWarningException失敗,顯示您的警告:

enter image description here