//Foo.java
public class Foo {
public void dummy() throw ParseException {
...
} public String bar(int i) {
...
} public boolean isSame(String[] strs) {
...
} public void add(StringBuffer sb, String s) {
...
}
}
偽對象的行為可以按照下面的方式來定義:
//get mock control
MockControl control = MockControl.createControl(Foo.class);
//get mock object
Foo foo = (Foo)control.getMock();
//begin behavior definition
//specify which method invocation's behavior
//to be defined.
foo.bar(10);
//define the behavior -- return "ok" when the
//argument is 10
control.setReturnValue("ok");
...
//end behavior definition
control.replay();
...
MockControl中超過50個方法是行為定義方法。他們可以如下分類。
o setReturnValue()
這些方法被用來定義最后的方法調用應該返回一個值作為參數。這兒有7個使用原始類型作業參數的`setReturnValue()方法,如setReturnValue(int i)或setReturnValue(float f)。setReturnValue(Object obj)被用來滿足那些需要對象作為參數的方法。如果給定的值不匹配方法的返回值,則拋出AssertionFailedError異常。
當然也可以在行為中加入預期調用的次數。這稱為調用次數限制。
MockControl control =
...
Foo foo = (Foo)control.getMock();
...
foo.bar(10);
//define the behavior -- return "ok" when the
//argument is 10. And this method is expected
//to be called just once.
setReturnValue("ok", 1);
...
上面的代碼段定義了bar(10)方法只能被調用一次。如果提供一個范圍又會怎么樣呢?
...
foo.bar(10);
//define the behavior -- return "ok" when the
//argument is 10. And this method is expected
//to be called at least once and at most 3
//times.
setReturnValue("ok", 1, 3);
...
現在bar(10)被限制至少被調用一次最多3次。更方便的是Range已經預定義了一些限制范圍。
...
foo.bar(10);
//define the behavior -- return "ok" when the
//argument is 10. And this method is expected
//to be called at least once.
setReturnValue("ok", Range.ONE_OR_MORE);
...
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/