是的,这是可能的。窍门是不使用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>
因此,单元测试ASP.NET网站是不可能的? – bahith 2010-03-03 11:48:35
这可能与该网站的已发布版本有关。这样,你就可以在Nunit测试项目中链接到一个DLL。然而,这是一个相当尴尬的解决方案。我实际上对网站项目有负面印象。 – Kerido 2010-03-03 12:00:40
非常感谢。 – bahith 2010-03-03 12:08:09