NUnit 2.5.9 官网学游记(二)快速入门A

快速入门(Quick Start)一章官网上举了一个例子,可以快速掌握NUnit的使用方法。不过这一章我并不按官网上的来,而是在阅读了官网的材料后,将自己理解的NUnit使用方法详细地展示出来,仅供各位参考。

注意:

1.本文认为读者已经阅读了“NUnit 2.5.9 官网学游记(一)入门”;

2.环境使用的是Visual Studio 2005

 

快速入门的目的

使读者快速掌握NUnit的使用方法,起码了解如何测试某个类的某个Method。

 

创建新项目

image

这里可以创建一个控制台应用程序。示例程序是一个简单银行系统,这里我就将项目名称定义为Bank。

 

添加新的类

image

右键单击项目->添加->类,示例程序中展示的是简单银行系统的底层类Account,因此该类取名为Account。

 

Account.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:   
   5:  namespace Bank
   6:  {
   7:      public class Account
   8:      {
   9:          private float balance;
  10:          public void Deposit(float amount)
  11:          {
  12:              balance += amount;
  13:          }
  14:   
  15:          public void Withdraw(float amount)
  16:          {
  17:              balance -= amount;
  18:          }
  19:   
  20:          public void TransferFunds(Account destination, float amount)
  21:          {
  22:          }
  23:   
  24:          public float Balance
  25:          {
  26:              get { return balance; }
  27:          }
  28:      }
  29:  }

从代码中很容易看出,Account提供了存款(Deposit)、取款(Withdraw)和转账的方法。下面我们就将通过编写一个测试类来具体说明测试类的写法。

 

添加一个测试类

测试类的名称规则为:被测试类名+Test,如Account类的测试类为AccountTest。

 

AccountTest.cs

   1:  namespace bank
   2:  {
   3:    using NUnit.Framework;
   4:   
   5:    [TestFixture]
   6:    public class AccountTest
   7:    {
   8:      [Test]
   9:      public void TransferFunds()
  10:      {
  11:        Account source = new Account();
  12:        source.Deposit(200.00F);
  13:        Account destination = new Account();
  14:        destination.Deposit(150.00F);
  15:   
  16:        source.TransferFunds(destination, 100.00F);
  17:        Assert.AreEqual(250.00F, destination.Balance);
  18:        Assert.AreEqual(100.00F, source.Balance);
  19:      
  20:      }
  21:    }
  22:  }

注意这个类需要添加NUnit的引用,右键单击项目->添加引用

image

先演示一下NUnit的用法,该类的写法稍后介绍。

 

运行测试

1.编译项目(生成解决方案)

2.打开NUnit.exe

3.选择File->Open Project…

image

选择Debug文件夹中生成的应用程序Bank.exe,单击“打开”

4.NUnit侧栏出现测试项目

image

侧栏显示出了需要测试的类及方法,此时可以点击“Run”按钮,运行测试。

image

此时测试条显示红色,表示测试中有错误,测试失败。在错误与失败标签(Errors and Failures)下,列出了测试失败的原因:

Bank.AccountTest.TransferFunds :
Expected : 250.00f 
But was : 150.00f
同时指明了错误发生的位置:

在 Bank.AccountTest.TransferFunds() 位置 D:\DotHide\My Documents\Visual Studio 2005\Projects\Bank\Bank\AccountTest.cs:行号 21

 

分析错误

从给出的信息中不难看出测试失败的原因就是Account类的源代码中并没有实现TransferFunds()方法。现在先不要关闭NUnit程序,让我们加入该方法的实现内容

   1:  public void TransferFunds(Account destination, float amount)
   2:  {
   3:      destination.Deposit(amount);
   4:      Withdraw(amount);
   5:  }

现在重新编译项目,运行测试,可以发现测试成功了

image

下期预告

测试类编写说明及测试异常处理将在“快速入门B”中进行介绍

posted @ 2011-01-27 11:16  DotHide  阅读(760)  评论(0)    收藏  举报