对的,这是可能的。诀窍是不要使用 NUnit GUI Runner,而是有一个自定义的 ASP.net 测试页面。这是使用 Razor 的示例。以下进入 App_Code\MyRunner.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NUnit.Core;
using NUnit.Framework;
using NUnit.Core.Extensibility;
/// <summary>
/// Summary description for TestRunner
/// </summary>
public class MyRunner
{
public static IList<TestResult> Run(Type testCase)
{
NUnit.Core.CoreExtensions.Host.InitializeService();
TestExecutionContext.CurrentContext.TestPackage = new TestPackage(testCase.FullName);
MyListener listener = new MyListener();
if (TestFixtureBuilder.CanBuildFrom(testCase))
{
NUnit.Core.Test test = TestFixtureBuilder.BuildFrom(testCase);
test.Run(listener, NUnit.Core.TestFilter.Empty);
}
return listener.Results;
}
}
public class MyListener : EventListener
{
public IList<TestResult> Results { get { return _results; } }
public void RunFinished(Exception exception)
{
}
public void RunFinished(TestResult result)
{
}
public void RunStarted(string name, int testCount)
{
}
public void SuiteFinished(TestResult result)
{
}
public void SuiteStarted(TestName testName)
{
}
IList<TestResult> _results = new List<TestResult>();
public void TestFinished(TestResult result)
{
_results.Add(result);
}
public void TestOutput(TestOutput testOutput)
{
}
public void TestStarted(TestName testName)
{
}
public void UnhandledException(Exception exception)
{
}
}
public class Class1
{
[Test]
public void TestOnePlusOne()
{
Assert.AreEqual(1 + 1, 2);
}
[Test]
public void TestOnePlusTwo()
{
throw new Exception("Ooops");
}
}
这是一个与之配套的 CSHTML 页面。将其命名为 MyNUnit.cshtml:
@using NUnit.Core
@{
IList<TestResult> results = MyRunner.Run(typeof(Class1));
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
@foreach (TestResult result in results)
{
<tr>
<td>
@result.Name
</td>
<td>
@result.IsSuccess
</td>
<td>
@result.Message
</td>
</tr>
}
</table>
</body>
</html>