在.Net项目中如何写单元测试

发表于:2015-5-28 11:08

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:yuandong    来源:51Testing软件测试网采编

  引言
  不要再犹豫写单元测试是否浪费时间,是否能减少开发过程中的bug,Just do it!
  开发环境及相关配置
  Win7 OS
  Visual Studio 2012 IDE
  .Net Framework 4.5
  Resharper (username:ronle , key:ZoJzmeVBoAv9Sskw76emgksMMFiLn4NM)
  NUnit Framework(Installed by NuGet package manage tool)
  Windows Console Application Project in C# Programming (Just an project example,you could use Unit Testing in other project such as Mvc,WCF,Web Service )
  代码示例
  代码主要功能:通过比较寻找一个list中的最大值。
  1.项目代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestDemo
{
public class Cmp
{
public static int Largest(int[] list)
{
int max = Int32.MinValue;
if (list.Length == 0)
{
throw new AggregateException("Empty list");
}
for (int index=0; index < list.Length; index++)
{
if (list[index] > max)
{
max = list[index];
}
}
return max;
}
}
}
  2.针对项目代码写的测试代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using  UnitTestDemo;
namespace UnitTestDemo.Test
{
[TestFixture]
public class TestCmp
{
[Test]
public void LargestOfNegative()
{
Assert.AreEqual(-7,Cmp.Largest(new int[]{-9,-7,-8}));
}
[Test,ExpectedException(typeof(AggregateException))]
public void LargestOfEmpty()
{
Cmp.Largest(new int[] {});
}
}
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号