[英]How to run NUnit programmatically
我有一些引用NUnit的程序集,並使用單個測試方法創建一個測試類。 我能夠獲得此程序集的文件系統路徑(例如“C:... \\ test.dll”)。 我想以編程方式使用NUnit來運行此程序集。
到目前為止,我有:
var runner = new SimpleTestRunner();
runner.Load(path);
var result = runner.Run(NullListener.NULL);
但是,調用runner.Load(path)會拋出FileNotFound異常。 我可以通過堆棧跟蹤看到問題是NUnit在堆棧中調用Assembly.Load(path)。 如果我將路徑更改為“Test,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”,那么我仍會得到相同的錯誤。
我已經向AppDomain.Current.AssemblyResolve添加了一個事件處理程序,以查看我是否可以手動解析此類型,但我的處理程序永遠不會被調用。
讓Assembly.Load(...)工作的秘訣是什么?
如果要在控制台模式下打開,請添加nunit-console-runner.dll引用並使用:
NUnit.ConsoleRunner.Runner.Main(new string[]
{
System.Reflection.Assembly.GetExecutingAssembly().Location,
});
如果你想以gui模式打開,添加nunit-gui-runner.dll引用並使用:
NUnit.Gui.AppEntry.Main(new string[]
{
System.Reflection.Assembly.GetExecutingAssembly().Location,
"/run"
});
這是最好的方法,因為您不必指定任何路徑。
另一個選項是在Visual Studio調試器輸出中集成NUnit runner:
public static void Main()
{
var assembly = Assembly.GetExecutingAssembly().FullName;
new TextUI (new DebugTextWriter()).Execute(new[] { assembly, "-wait" });
}
public class DebugTextWriter : StreamWriter
{
public DebugTextWriter()
: base(new DebugOutStream(), Encoding.Unicode, 1024)
{
this.AutoFlush = true;
}
class DebugOutStream : Stream
{
public override void Write(byte[] buffer, int offset, int count)
{
Debug.Write(Encoding.Unicode.GetString(buffer, offset, count));
}
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { Debug.Flush(); }
public override long Length { get { throw new InvalidOperationException(); } }
public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); }
public override void SetLength(long value) { throw new InvalidOperationException(); }
public override long Position
{
get { throw new InvalidOperationException(); }
set { throw new InvalidOperationException(); }
}
};
}
“讓Assembly.Load工作的秘訣是什么?”
System.Reflection.Assembly.Load采用包含程序集名稱的字符串,而不是文件的路徑。
如果要從文件加載程序集,請使用:
Assembly a = System.Reflection.Assembly.LoadFrom(pathToFileOnDisk);
(LoadFrom實際上在內部使用Assembly.Load)
順便說一下,有什么理由可以使用NUnit-Console命令行工具並將它傳遞給測試程序集的路徑嗎? 然后,您可以使用System.Diagnostics.Process在客戶端應用程序中運行它,可能更簡單?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.