2015-06-01 44 views
0

我正在製作一個非常簡單的C#程序,用於輸出文本並嘗試對其進行測試。我的測試一直失敗,因爲來自控制檯的文本與我正在比較的文本不相同。我認爲它只是沒有被正確地轉換成字符串,但我不知道。 下面是程序代碼:如何將控制檯輸出轉換爲字符串?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Lab3._1 
{ 
    public class ConsoleOutput 
    { 
     static void Main() 
     { 
      Console.WriteLine("Hello World!"); 
     } 
    } 
} 

下面是測試代碼:

using System; 
using System.IO; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 

namespace Lab3._1Test 
{ 
    [TestClass] 
    public class ConsoleOutputTest 
    { 
     [TestMethod] 
     public void WriteToConsoleTest() 
     { 
      var currentConsoleOut = Console.Out; 
      string newConsoleOut = currentConsoleOut.ToString(); 

      string ConsoleOutput = "Hello World!"; 

      Assert.AreEqual(newConsoleOut, ConsoleOutput); 
     } 
    } 
} 

以下是錯誤我得到:

Test Failed - WriteToConsoleTest 
Message: Assert.AreEqual failed. 
Expected:<System.IO.TextWriter+SyncTextWriter>.Actual:<Hello World!>. 
+0

斷言之前,設置一個斷點,看看有什麼'newConsoleOut','currentConsoleOut'是。 – Envil

+1

您是否設置了*斷點*來驗證'newConsoleOut'是什麼? –

+0

我想檢查控制檯輸出是否等於字符串「Hello World!」 –

回答

1

你的測試從來不打電話ConsoleOutput.Main所以Hello World!不會被寫入控制檯。然後你打電話ToStringTextWriter和比較string,所以你比較蘋果和橙子。

如果你想捕捉什麼寫入到控制檯,你應該把它重定向到一個備用TextWriter實現:

[TestMethod] 
public void WriteToConsoleTest() 
{ 
    // setup test - redirect Console.Out 
    var sw = new StringWriter();  
    Console.SetOut(sw); 

    // exercise system under test 
    ConsoleOutput.Main(); 

    // verify 
    Assert.AreEqual("Hello World!\r\n", sw.ToString()); 
} 
+0

當最後一行從「Equal」改爲「AreEqual」時,這可以起作用 –

+0

@MichaelReuter對不起,習慣的力量並沒有注意。我不使用MSTest。 –

2

您已經有點糊塗的了了解如何設置控制檯重定向,寫入並讀取結果。要達到什麼樣的你正在嘗試做的,你的測試方法更改爲:

[TestMethod] 
public void WriteToConsoleTest() 
{ 
    using (var sw = new StringWriter()) 
    { 
     Console.SetOut(sw); 
     ConsoleOutput.Main(); 

     Assert.AreEqual("Hello World!" + Environment.NewLine, sw.toString()); 
    } 
} 
+0

這似乎是正確的,但我仍然收到錯誤:消息:Assert.AreEqual失敗。預計。實際:。他們看起來和我一樣! –

+0

消息:Assert.AreEqual失敗。預計。實際:。 –

+0

@MichaelReuter,你有沒有看到我將「Environment.NewLine」添加到「Hello World!」的編輯? –

相關問題