1. NUnit测试框架简介
2. NUnit测试实例
3. 参考资料及代码下载
<1>. NUnit简介
TDD测试驱动开发是极限编程的一个重要特点,它以不断的测试推动代码的开发,既简化了代码,同时也保证了软件指令,另一方面说编写的测试用例将成为重要文档(可以作为SDK提供给开发者,测试即文档)。 [NUnit]即是一个对于.net平台上进行测试的框架。最初是从JUnit移植到.net平台上的,完全采用c#开发。
<2>. NUnit测试实例
1. nunit下载安装
点击下载压缩包,下载完毕之后,解压到某个目录下,基本目录如下:
其中bin下存放的主要是需要使用的dll及nunit的gui测试程序。doc中是nunit的详细文档,sample包含了unit的测试实例, 有cpp,csharp,vb等语言的测试实例。解压完之后,nunit的安装也就完成。下面来通过一个简单的测试实例来看看unit的测试框架的使用。
新建一个vs类库工程HelloUnit, 添加一个class Account:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloUnit
{
public class Account
{
private float balance;
public void Deposit(float amount)
{
balance += amount;
}
public void Withdraw(float amount)
{
balance -= amount;
}
public void TransferFunds(Account destination, float amount)
{
this.balance -= amount;
destination.balance += amount;
}
public float Balance
{
get { return balance; }
}
}
}
新添加一个测试类AccountTest,添加nunit.framework.dll引用,添加using声明using NUnit.Framework;,测试代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace HelloUnit.Tests
{
[TestFixture]
public class AccountTest
{
[Test]
public void TransferFundsTest()
{
Account source = new Account();
// 存入200
source.Deposit(200.00f);
Account dest = new Account();
// 存入150
dest.Deposit(150.00F);
// 从source转账100到dest
source.TransferFunds(dest, 100.00F);
Assert.AreEqual(250.00F, dest.Balance);
Assert.AreEqual(100.00F, source.Balance);
}
}
}
上面的代码需要注意的是在类AccountTest中添加了TestFixture属性,表明该类中存在测试代码,在方法TransferFundsTest上使用Test属性,表明该方法是一个测试方法,每个测试方法都是固定的声明格式:public void test-func-namespace(),也就是没有返回值,没有参数。 上面的测试代码使用了nunit framework中的assert类。
编译上面的工程,确保生成该类库的dll,打开nunit.exe(/bin/framework-version/),ctrl+o,打开刚刚生成的dll文件,现在在该gui的左侧列出了所有的测试方法,点击右侧的Run按钮,如果下面的进度条一直保持是green状态,那么表明测试是全部pass掉的,否则说明出现了问题,那么将在Run按钮下侧的区域中显示出错信息。
<3>. 参考资料及代码下载
nunit online doc
/Files/xuqiang/HelloUnit.rar