[英]How Can I Use NUnit with ASP.NET Website (Not Web Project)?
我是單元測試的新手,我想試試NUnit。
在ASP.NET Web項目中,我可以在我的Web項目解決方案中創建一個用於單元測試的新項目,並添加對我原始項目的引用,在NUnit中,我可以為我的單元測試項目加載dll文件來運行測試。
但是,我正在開發一個ASP.NET網站,因為ASP.NET網站沒有dll文件,我無法在我的解決方案中添加一個單獨的項目,該項目引用了我的網站項目,因此,我無法訪問類在主要項目中進行測試。 即使我決定將我的測試留在我的主網站項目中,我也無法直接在NUnit Gui中加載網站的dll(因為沒有任何dll文件)。
當我嘗試使用Visual Studio為我的網站創建單元測試時,我也遇到了問題,不知道它們是否相關。
任何幫助都會被貶低。
為什么不能切換到Web應用程序項目? 或者,您可以將業務邏輯移動到外部類庫項目,然后在Nunit測試項目中引用后者。
對的,這是可能的。 訣竅不是使用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>
您可以通過以下方式提供對您的網站項目的引用
添加reference-> projects->添加項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.