2012-03-09 27 views
2

我有一些代碼,我需要看到,當我運行一個測試,並且 TestContext將不得不成爲我的測試類的一部分我需要 debug.writelines顯示正在測試的班級。我認爲 只是將一個TestContext傳遞給我的MessageStatus靜態方法,並且可能 必須但是這將是一個PITA,因爲UnitTest類將有 將TestContext傳遞給它正在測試的對象。太緊了 加上我的口味。單元測試代碼調用supresses Debug.WriteLine和Trace.WriteLine

在基本條件

[TestMethod] 
     public void TestA() 
     { 
      //.... 
      Assert.IsTrue(Blah.Blah())); 
     } 



public void Blah() 
{ 
    Debug.WriteLine("Hello"); 
} 

一直沒有出現,當我運行單元測試!

我可以將其更改爲:

TestContext t; 
[TestMethod] 
     public void TestA() 
     { 
      //.... 
      Assert.IsTrue(Blah.Blah(t))); 
     } 



public void Blah(TestContext p1) 
{ 
    p1.WriteLine("Hello"); 
} 

但是這是瘋狂這意味着要改變我的簽名和緊耦合。我讀的線程How to write output from a unit test?它並不能幫助:(

回答

1

您需要使用Console.WriteLine的產量在測試運行出現。然而,這是一個壞事。我建議使用像n日誌記錄框架。

1

如果您需要看到的Debug.WriteLine生產線或與Debug.Assert的你產生斷言處理可以創建自己的System.Diagnostic.TraceListener將輸出重定向到的TestContext - 見我的回答What do I have to do so that assertions won't block automated tests anymore?

public class MyListenerThatDoesNotShowDialogOnFail: 
     System.Diagnostics.TraceListener 
{ 
    // This is to avoid message box on Debug.Assert(false); 
    public override void Fail(string message, string detailMessage) 
    {// do something UnitTest friendly here like Assert.Fail(false) 
    } 

    // This (+Write) is to redirect Debug.WriteLine("Some trace text"); 
    public override void WriteLine(string message) 
    {// do something UnitTest friendly here like TestContext.Write(message) 
    } 
} 

測試設置監聽器中的某處。請注意,下面的示例是簡化的,您可能想要保存當前偵聽器並在測試結束時恢復。

Debug.Listeners.Clear(); 
Debug.Listeners.Add(new MyListenerThatDoesNotShowDialogOnFail()); 
+0

參見示例的TraceListener,簡單地追加跟蹤消息在字符串[跟蹤偵聽寫入到文本框(WPF應用程序)](http://stackoverflow.com/a/1389289) – 2016-07-05 07:49:58