歡迎您光臨本站 註冊首頁

Java的DBC介面設計

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

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進行相應的測試了.


[火星人 ] Java的DBC介面設計已經有818次圍觀

http://coctec.com/docs/java/show-post-61777.html