3.如何在.NET中应用NUnit
我将举个例子,一步一步演示如何去使用NUnit.
第1步.为测试代码创建一个Visual Studio工程。
在Microsoft Visual Studio .NET中,让我们开始创建一个新的工程。选择Visual C#工程作为工程类型,Class Library作为模板。将工程命名为NUnitQuickStart.图4-1是一个描述本步骤的Visual Studio .NET。

图 4-1: 创建第一个NUnit工程
第2步.增加一个NUnit框架引用
在Microsoft Visual Studio .NET里创建这个例子时,你需要增加一个NUnit.framework.dll引用,如下:
在Solution Explorer右击引用,然后选择增加引用
NUnit.framework组件,在Add Reference对话框中按Select和OK按钮。
图4-2 描述了这步:
第3步.为工程加一个类.
为工程加一个NumbersFixture类。这里是这个例子的代码。
1
using System;
2
using NUnit.Framework;
3
4
namespace NUnitQuickStart
5

{
6
[TestFixture]
7
public class NumersFixture
8
{
9
[Test]
10
public void AddTwoNumbers()
11
{
12
int a=1;
13
int b=2;
14
int sum=a+b;
15
Assert.AreEqual(sum,3);
16
}
17
}
18
}
19

2

3

4

5



6

7

8



9

10

11



12

13

14

15

16

17

18

19

第4步.建立你的Visual Studio 工程,使用NUnit-Gui测试
从程序->NUnit2.2打开NUnit-gui,加载本本工程编译的程序集.
为了在Visual Studio .NET中自动运行NUnit-Gui,你需要建立NUnit-Gui作为你的启动程序:
在 Solution Explorer里右击你的NunitQuickStart工程。
在弹出菜单中选择属性。
在显示的对话框的左面,点击Configuration Properties夹
选择出现在Configuration Properties夹下的Debugging。
在属性框右边的Start Action部分,选择下拉框的Program作为Debug Mode值。
按Apply按钮
设置NUnit-gui.exe 作为Start Application。,你既可以键入nunit-gui.exe的全路径,也可使用浏览按钮来指向它。
图 4-3:将NUnit-Gui 作为工程的测试运行器
第5步.编译运行测试.
现在编译solution。成功编译后,开始应用程序。NUnit-Gui测试运行器出现。当你第一次开始NUnit-Gui,它打开时没有测试加载。从File菜单选择Oprn,浏览NUnitQuickStart.dll的路径。当你加载了测试的程序集,测试运行器为加载的程序集的测试产生一个可见的表现。在例子中,测试程序集仅有一个测试,测试程序集的结构如图4-4所示:
