利用单元测试,我们可以找出很多意想不到的问题,在Nunit对项目进行单元测试 过程中就查找出了很多隐藏的问题,下面是单元测试中遇到的问题与解决方案:
1.TQL_Part表
1.1问题1
下面是项目中的代码:
/**//// <summary> /// 根据taskid,获得对应的Part记录 /// </summary> /// <param name="taskId"></param> /// <returns></returns> public WYEng.Model.TQL_Part GetPaperPart(int taskId) ...{ SqlParameter[] parm = new SqlParameter[1]; parm[0] = new SqlParameter(PARM_TASKID, SqlDbType.Int); parm[0].Value = taskId; WYEng.Model.TQL_Part part = new WYEng.Model.TQL_Part(); using (SqlDataReader rdr = XPWY.DBUtility.DBHelperSQL.ExecuteReader(SQL_SELECT_PART, parm)) ...{ while (rdr.Read()) ...{ part.PartCode = rdr.GetString(0); part.SetCode = rdr.GetString(1); part.SubjectId = rdr.GetInt32(2); part.DisplayOrder = rdr.GetInt32(3); part.Description = rdr.GetString(4); } } return part; }
写测试用例如下:
运行Nunit,状态条为红色,经检查发现原因是model层中的TQL_PArt的description下的代码段有问题using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using WYEng.SQLServerDAL; namespace WYEng.TestUnit ...{ [TestFixture] public class TQL_Part ...{ SQLServerDAL.TQL_Part part; WYEng.Model.TQL_Part p; [SetUp] public void CreateObject() ...{ part = new WYEng.SQLServerDAL.TQL_Part(); p=new WYEng.Model.TQL_Part(); } [TearDown] public void DeleteObject() ...{ part = null; p=null; } [Test] public void GetPaperPart() ...{ //输入TaskId的值,然后可以获取其Part所有信息 p = part.GetPaperPart(1); //正常情况 Assert.AreEqual(p.PartCode, "6666"); } } }
if (value != null && value.Length > 50)
throw new ArgumentOutOfRangeException("Invalid value for Description", value, value.ToString());
数据库中description的字段为Varchar(500),而这里只为50,现在更正为 if (value != null && value.Length > 50)
修正后,运行后的状态条为绿色。