Java的DBC接口设计
来源:优易学  2011-2-13 19:28:00   【优易学:中国教育考试门户网】   资料下载   IT书店
  SpringContracts 是一个契约式框架他通过annotation和AOP思想进行设计 本文主要讲述一下他和Junit的结合,与spring的结合大家可以看官方文档 看例子:
  @Invariant( condition="this.capacity > 0 and this.size <= this.capacity" )
  public interface Stack {
  @Postcondition( condition="return >= 0" )
  public int getSize();
  @Precondition( bindArgs="arg1=element", condition="!empty element" )
  @Postcondition( bindArgs="arg1=element", condition="this.size == old:this.size + 1 and this.top == element" )
  public void push( Object elem );
  @Postcondition( condition="(this.size > 0) ==> (!empty return)" )
  public Object getTop();
  public Object pop();
  @Precondition(condition="arg1 > 0")
  public void setNumber(int number);
  }
  SpringContracts 的annotation表达式主要是EL和groovy,默认是EL. 有了这个接口那的所有实现类就必须遵循这个契约限制。
  例如:
  public void testPushShouldThrowExceptionWhenInputNullObject(){
  Stack stack = new StackImp();
  stack.push(null);//这时候将抛出Exception condition="!empty element"
  }
  要执行以上unit test你还需要配置aop.xml文件,默认在META-INF/aop.xml
  内容如下:
  <?xml version="1.0"?>
  <aspectj>
  <aspects>
  <aspect name="org.springcontracts.dbc.interceptor.ContractValidationInterceptor">
  </aspect>
  </aspects>
  <weaver>
  <exclude within="org.springframework..*"/>
  <exclude within="org.apache..*"/>
  <exclude within="org.springcontracts..*"/>
  <include within="org.ltw.springcontracts..*"/> <!-- 这里指定你相应的类放置路径。
  <include within="com.testProject..*"/> <!-- 这里指定你相应的类放置路径。
  </weaver>
  </aspectj>
  还需要在运行test的时候为你的run 器设置代理类
  如果你是在eclipse下的话,需要设置。ok现在你就可以run你的junit进行相应的测试了。

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训