如何使用NUnit进行单元测试


NUnit 是一个免费开源的(http://www.nunit.org)产品,它提供了一套测试框架和一个测试运行程序(test runner)。
注意:test tunner 知道如何寻找具有 [TestFixture] 属性的类和类中的 [Test] 方法。


如何安装 NUnit:

方法一:下载 NUnit 的C# 源码并自己编译,并安装在计算机上;

方法二:使用Microsoft Installer (MSI)文件。
注意:MSI只内置在Windows 2000以上,Windows NT或以下版本,需要在www.microsoft.com 中搜索“Microsoft Installer Redistributable”。


使用 test tunner 的3种方法:

1. NUnit GUI
 
 它提供一个独立的NUnit 图形化工具。
   从菜单Tool/Options中的个性化设置来打开Visual Studio支持。

2. NUnit 的命令行   
   需要配置Path运行环境。

3. Visual Studio 的插件
   有几种能把NUnit 集成到Visual Studio的插件,诸如 http://www.mutantdesign.co.uk/nunit-addin/
  TestDriven.Net :The Zero Friction Unit Testing Add-In for Microsoft Visual Studio

  TestDriven.Net makes it easy to run unit tests with a single click, anywhere in your Visual Studio solutions. It supports all versions of Microsoft Visual Studio and it integrates with the best .NET development tools.

支持NUnit , MbUnit, MSTest ,NCover,Reflector,TypeMock,dotTrace,MSBee

 

简单示例

一、在VS中创建一个类型为Class Library 的新项目
TestNUnit.csproj

二、代码类:创建一个名为Largest.cs的代码类文件

public   class  Cmp
{
   
public   static   int  Largest(  int [] list)
   {
         
int  index;
         
int  max  =  Int32.MinValue;  // 若 max=0; 则在list的元素为负数的时候运行错误
          
         
// list的长度为0,也就是list数组为空的时候,抛出一个运行期异常
          if (list.length  ==   0 )
         {
          
throw   new  ArgumentException( " largest: Empty list " );
         }

         
for (index  =   0 ;index  <  list.length; index ++ )
         {
            
if (list[index]  >  max) max  =  list[index];
         }
         
return  max;
   }
}


三、测试类:创建一个名为TestLargest.cs的测试类文件

注意:测试代码使用了Nunit.Framework,因此需要增加一个指向nunit.framework.dll 的引用才能编译。

using  Nunit.Framework;
[TestFixture]

public   class  TestLargest
{
  [Test]
  
public   void  LargestOf3()
  {
    Assert.AreEqual(
9 ,Cmp.Largest( new   int []{ 7 , 8 , 9 } ));  //  测试“9”在最后一位
    Assert.AreEqual( 9 ,Cmp.Largest( new   int []{ 7 , 9 , 8 } ));  //  测试“9”在中间位
    Assert.AreEqual( 9 ,Cmp.Largest( new   int []{ 9 , 7 , 8 } ));  //  测试“9”在第一位
    Assert.AreEqual( 9 ,Cmp.Largest( new   int []{ 9 , 9 , 8 } ));  //  测试存在重复的“9”
    Assert.AreEqual( 9 ,Cmp.Largest( new   int []{ 9 } ));      //  测试list中只存在“9”一个元素
    
    
//  测试list中负数的存在,若类Cmp中Largest方法的 int max=0; 则会检测抱错
    Assert.AreEqual( - 7 ,Cmp.Largest( new   int []{ - 9 , - 8 , - 7 } ));
  }
  
  [Test, ExpectedException(
typeof (ArgumentException))]
  
public   void  TestEmpty()
  {
    
//  测试list数组为空(长度为0)时,是否抛出异常
    Cmp.Largest( new   int [] {});
  }
}

生成解决方案(快捷键 Ctrl+Shift+B)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值