当前位置: 首页 > 图文教程 > 网络编程 > ASP > 单元测试和事先测试开发(2)

ASP
WEB打印设置解决方案四
截取固定长度字符串显示在页面
如何得到上一次插入记录后自动产生的ID
组件:Adodb.Stream 浅释
一个统计当前在线用户的解决方案
实例演练ASP+XML编程
IP地址分段计算
身份证验证代码函数
简单购物车教程
ASP分页函数
asp中对ip进行过滤限制函数
不用Golobal和session实现在线人数统计
ASP实现结构化列举并查看某路径下所有文件
常用Response对象的使用祥解
在ASP网站设计中表单验证
动网论坛代码分析
轻松实现将上传图片到数据库
读取数据库中数据到数组的类
网址和邮件地址的转换函数
ASP编码优化

ASP 中的 单元测试和事先测试开发(2)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 60 ::
收藏到网摘: n/a

       启用 Foreach
  
    许多用户希望能够使用 foreach 遍历我的列表。为此,我需要在类中实现 Ienumerable,并定义一个单独的用于实现 Ienumerable 的类。第一步,测试:
  
  [Test]
  public void TestForeach()
  {
  IntegerList list = new IntegerList();
  list.Add(5);
  list.Add(10);
  list.Add(15);
  list.Add(20);
  
  ArrayList items = new ArrayList();
  
  foreach (int value in list)
  {
  items.Add(value);
  }
  
  Assertion.AssertEquals("Count", 4, items.Count);
  Assertion.AssertEquals("index 0", 5, items[0]);
  Assertion.AssertEquals("index 1", 10, items[1]);
  Assertion.AssertEquals("index 2", 15, items[2]);
  Assertion.AssertEquals("index 3", 20, items[3]);
  }
  
  我还通过 IntegerList 实现 IEnumerable:
  
  public IEnumerator GetEnumerator()
  {
  return null;
  }
  
  
    运行测试时,此代码生成异常。为了正确地实现此功能,我将使用一个嵌套类作为枚举器。
  
  class IntegerListEnumerator: IEnumerator
  {
  IntegerList list;
  int index = -1;
  
  public IntegerListEnumerator(IntegerList list)
  {
  this.list = list;
  }
  public bool MoveNext()
  {
  index++;
  if (index == list.Count)
  return(false);
  else
  return(true);
  }
  public object Current
  {
  get
  {
  return(list[index]);
  }
  }
  public void Reset()
  {
  index = -1;
  }
  }
  
  
    此类将一个指针传递给 IntegerList 对象,然后只返回此对象中的元素。
  
    这样,便可以对列表执行 foreach 操作,但遗憾的是 Current 属性属于对象类型,这意味着每个值将被装箱才能将其返回。此问题可采用一种基于模式的方法加以解决,此方法酷似当前方法,但它通过 GetEnumerator() 返回一个真正的类(而非 IEnumerator),且此类中的 Current 属性为 int 类型。
  
    然而执行此操作后,我要确保在不支持该模式的语言中仍然可以使用这种基于接口的方法。我将复制编写的上一个测试并修改 foreach 以转换为接口:
  
    foreach (int value in (IEnumerable) list)
  
    只需少许改动,列表即可在两种情况下正常运行。请查看代码样例以获取更多细节和更多测试。
  
    几点说明
  
    为本月的专栏文章编写代码和文字大约花了我一个小时的时间。事先编写测试的优点就是您可以对在类中添加哪些内容以使测试通过有一个清楚的认识,从而简化代码的编写。
  
    如果要进行小型、递增的测试,则使用此方法最合适。我鼓励您在小型项目中使用此方法。事先测试开发是所谓的“敏捷方法”的一部分。