WEB开发网
开发学院软件开发Java 实战 Groovy: @Delegate 注释 阅读

实战 Groovy: @Delegate 注释

 2009-09-28 00:00:00 来源:WEB开发网   
核心提示: 清单 10. 首先编写一个失败的测试classFixedListTestextendsGroovyTestCase{voidtestAdd(){ListthreeStooges=newFixedList(3)threeStooges.add("Moe")threeStooge

清单 10. 首先编写一个失败的测试 

class FixedListTest extends GroovyTestCase{
  
  void testAdd(){
    List threeStooges = new FixedList(3)
    threeStooges.add("Moe")    
    threeStooges.add("Larry")
    threeStooges.add("Curly")
    threeStooges.add("Shemp")      
    assertEquals threeStooges.sizeLimit, threeStooges.size()
  }
}
$ groovy FixedListTest.groovy 
There was 1 failure:
1) testAdd(FixedListTest)junit.framework.AssertionFailedError: 
   expected:<3> but was:<4>

似乎 add() 方法应当在 FixedList 中被重写,如清单 11 所示。重新运行这些测试仍然失败,但是这一次是因为抛出了异常。

清单 11. 重写 ArrayList 的 add() 方法

class FixedList{
  @Delegate private List list = new ArrayList()
  final int sizeLimit
  
  //snip...
  
  boolean add(Object element){
    if(list.size() < sizeLimit){
      return list.add(element)
    }else{
      throw new UnsupportedOperationException("Error adding ${element}:" +
                 " the size of this FixedList is limited to ${sizeLimit}.")
    }
  }
}
$ groovy FixedListTest.groovy 
There was 1 error:
1) testAdd(FixedListTest)java.lang.UnsupportedOperationException: 
   Error adding Shemp: the size of this FixedList is limited to 3.

上一页  3 4 5 6 7 8 9 10  下一页

Tags:实战 Groovy Delegate

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接