2011-12-01 28 views
0

我正在爲我們的質量檢查小組制定自動化策略,並且需要能夠捕獲腳本和EXE的輸出。當我運行此代碼作爲一個控制檯應用程序,我能夠成功地捕捉plink.exe的輸出:如何讓RedirectStandardOutput在NUnit中工作?

class Program 
{ 
    static void Main(string[] args) 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = @"C:\Tools\plink.exe"; 
     process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh"; 
     process.StartInfo.UseShellExecute = false; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.Start(); 

     string output = process.StandardOutput.ReadToEnd(); 
     process.WaitForExit(); 

     output = output.Trim().ToLower(); // Output is successfully captured here 

     if (output == "pass") 
     { 
      Console.WriteLine("Passed!"); 
     } 
    } 
} 

這個命令需要大約一分鐘來執行,我成功地捕獲結果的輸出變量。

然而,當我編譯相同的代碼作爲一個DLL,並通過NUnit的運行,該代碼立即完成和失敗== NULL輸出的值:

[TestFixture] 
public class InstallTest 
{ 
    [Test] 
    public void InstallAgentNix() 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = @"C:\Tools\plink.exe"; 
     process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh"; 
     process.StartInfo.UseShellExecute = false; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.Start(); 

     string output = process.StandardOutput.ReadToEnd(); 

     process.WaitForExit(); 

     output = output.Trim().ToLower(); 

     Assert.AreEqual("pass", output, "Agent did not get installed"); 
    } 
} 

我已經縮小問題下到行string output = process.StandardOutput.ReadToEnd()。如果我將該行註釋掉,執行時間大約是一分鐘,並且操作在遠程計算機上成功執行(test.sh在遠程Linux機器上執行)。

我希望我缺少一些簡單的東西 - 我不想找到不同的測試工具。

編輯:看起來類似於(未解決)問題在這裏:Why does a process started in dll work when tested using console application but not when called by another dll?

回答

0

好吧,我花了整個晚上,我想通了。除了重定向標準輸出以外,我還必須使用RedirectStandardInput。

這是在DLL中工作的固定代碼。作爲一個供參考,該修復程序解決的WinForms應用程序的問題,以及:

[TestFixture] 
public class InstallTest 
{ 
    [Test] 
    public void InstallAgentNix() 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = @"C:\Tools\plink.exe"; 
     process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh"; 
     process.StartInfo.UseShellExecute = false; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.StartInfo.RedirectStandardInput = true; 
     process.Start(); 

     string output = process.StandardOutput.ReadToEnd(); 

     process.WaitForExit(); 

     output = output.Trim().ToLower(); 

     Assert.AreEqual("pass", output, "Agent did not get installed"); 
    } 
} 
0

正如你自己發現,加入行

process.StartInfo.RedirectStandardOutput = true; 

解決了這個問題。 NUnit必須建立另一個層次的間接。感謝您的回答,使我免於痛苦的調查。

雖然我不認爲問題來自於dll/exe之間的區別,因爲我在作爲控制檯應用程序編譯的測試項目中遇到了這個問題。