[英]How do I get 'RedirectStandardOutput' to work in NUnit?
我正在為我們的 QA 小組制定自動化策略,需要能夠捕獲腳本和 EXE 文件的輸出。 當我將此代碼作為控制台應用程序運行時,我能夠成功捕獲 plink.exe 的輸出:
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 機器上執行)。
我希望我錯過了一些簡單的東西 - 我不想找到不同的測試工具。
它看起來類似於此處的(未解決的)問題: 為什么在使用控制台應用程序測試時在 DLL 文件中啟動的進程可以工作,但在被另一個 DLL 文件調用時卻不能工作?
好吧,我花了一整夜,但我想通了。 除了重定向標准輸出以使其正常工作之外,我還必須重定向標准輸入。
這是在 DLL 文件中工作的固定代碼。 作為僅供參考,此修復程序也解決了 Windows 窗體應用程序中的問題:
[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");
}
}
正如您自己發現的那樣,添加行
process.StartInfo.RedirectStandardOutput = true;
解決了這個問題。 NUnit 必須設置另一個間接級別。 感謝您的回答,使我免於痛苦的調查。
雖然我不認為問題來自 DLL 文件/EXE 文件之間的差異,因為我在編譯為控制台應用程序的測試項目中遇到了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.