加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

用NUnit2.1简单实现.net的测试驱动开发(TDD)---转帖

发布时间:2020-12-13 20:37:24 所属栏目:百科 来源:网络整理
导读:1 最初的测试用例 using System; using NUnit.Framework; namespace netshop { /// summary /// 四则运算TestCls测试用例 /// Edit by spgoal /// /summary [TestFixture] public class TestCase { public TestCase() { } private TestCls tc; [SetUp] publi
1最初的测试用例
using System;
using NUnit.Framework;
namespace netshop
{
/// <summary>
/// 四则运算TestCls测试用例
/// Edit by spgoal
/// </summary>
[TestFixture]
public class TestCase
{
public TestCase()
{
}
private TestCls tc;
[SetUp]
public void setup()
{
tc=new TestCls();
}
[Test]
public void testAdd()
{
Assert.AreEqual(10,tc.Add(5,5));
Assert.AreEqual(7,tc.Add(3,4));
}
[Test]
public void testSub()
{
Assert.AreEqual(1,tc.Sub(5,4));
}
[Test]
public void testMul()
{
Assert.AreEqual(10,tc.Mul(2,5));
}
[Test]
public void testDiv()
{
Assert.AreEqual(2,tc.Div(10,5));
}
}
}
2 编译这个测试用例,理所当然的是通不过的,因为TestCls类未建立,于是建立该类,不必多说,看代码:
using System;
namespace netshop
{
/// <summary>
/// 四则运算的简单例子
/// </summary>
public class TestCls
{
public TestCls()
{
}
//加法
public int Add(int a,int b)
{
return 0;
}
//减法
public int Sub(int a,int b)
{
return 0;
}
//乘法
public int Mul(int a,int b)
{
return 0;
}
//除法
public double Div(int a,int b)
{
return 0;
}
}
}
这时编译通过,但由于里面的方法没实现,所以所有测试用例都失败。
(加载测试用例的方法是:先运行Nunit-Gui V2.1程序,然后在菜单file—open—选择测试用例所在工程目录的bin目录下的dll文件。)

3 于是编写加减乘除四个函数的实现:
using System;
namespace netshop
{
/// <summary>
/// 四则运算的简单例子
/// </summary>
public class TestCls
{
public TestCls()
{
}
//加法
public int Add(int a,int b)
{
return a+b;
}
//减法
public int Sub(int a,int b)
{
return a-b;
}
//乘法
public int Mul(int a,int b)
{
return a*b;
}
//除法
public double Div(int a,int b)
{
return a/b;
}
}
}
这时测试通过了!

4 寻找令测试失败的测试用例
想想似乎漏了一些可以使程序出错的测试用例,想到了吧?就是除数为零的情况,于是修改testDiv测试用例
[Test]
public void testDiv()
{
Assert.AreEqual(2,5));
Assert.AreEqual(0,0));//除于0的情况
}
果然,运行Nunit,出错了^_^ (这人有问题,出错了还笑-_-b)

于是修改TestCls类代码
//除法
public double Div(int a,int b)
{
if(b!=0)
{
return a/b;
}
else
{
return 0;
}
}
编译后,再运行Nunit,全部通过!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读