·首页 ·asp ·.net ·php ·JSP ·CGI ·数据库 ·网页设计 ·网管专栏 ·XML ·工具软件 ·办公软件 ·操作系统 ·程序设计 ·LINUX 
  当前位置: 普克>>计算机教程>>.net>>评论及其它>>单元测试和事先测试开发(2)
flash视频教学

photoshop专题

asp.net专题

office专题

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


评论及其它 发表时间:2006-4-8 字体:  返回
启用 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)
   
    只需少许改动,列表即可在两种情况下正常运行。请查看代码样例以获取更多细节和更多测试。
   
    几点说明
   
    为本月的专栏文章编写代码和文字大约花了我一个小时的时间。事先编写测试的优点就是您可以对在类中添加哪些内容以使测试通过有一个清楚的认识,从而简化代码的编写。
   
    如果要进行小型、递增的测试,则使用此方法最合适。我鼓励您在小型项目中使用此方法。事先测试开发是所谓的“敏捷方法”的一部分。


上一篇:单元测试和事先测试开发(1)
下一篇:动态装载和使用类型

普克创业投资网刊载此文不代表同意其说法或描述,仅为提供更多信息。
在百度中搜索单元测试和事先测试开发(2)的相关内容]   [在狗狗中搜索单元测试和事先测试开发(2)的相关内容]
Copyright @ 2006 PUPK.COM 普克创业投资网 版权所有
 建议使用1024*768以达到最好的浏览效果