在單元測試的策略中偽對象被廣泛使用
EasyMock是一個在這方面很有名的工具
Mocquer是一個類似的工具
Mocquer介紹
Mocquer基於Dunamis項目
MockControl是Mocquer項目中最重要的類
·public void replay();
·public void verify();
·public void reset();
偽對象在他的生命周期中有三種狀態
Figure
剛開始
·public static MockControl createNiceControl(
·public static MockControl createControl(
·public static MockControl createStrictControl(
Mocquer提供了三種MockControl
下面是每一個工廠方法的兩個不同版本
public static MockControl createXXXControl(Class clazz); public static MockControl createXXXControl(Class clazz
如果類是作為接口來模擬的或者他有一個公共或保護的缺省構造函數
例如
public class ClassWithNoDefaultConstructor {
public ClassWithNoDefaultConstructor(int i) {
}
}
·偽對象獲取方法
public Object getMock();
每一個MockControl包含一個生成的偽對象的引用
//get mock control
MockControl control = MockControl
//Get the mock object from mock control
Foo foo = (Foo) control
·行為定義方法
public void setReturnValue(
public void setThrowable(Throwable throwable);
public void setVoidCallable();
public void setDefaultReturnValue(
public void setDefaultThrowable(Throwable throwable);
public void setDefaultVoidCallable();
public void setMatcher(ArgumentsMatcher matcher);
public void setDefaultMatcher(ArgumentsMatcher matcher);
MockControl允許開發人員定義偽對象的每一個方法的行為
//Foo
public class Foo {
public void dummy() throw ParseException {
} public String bar(int i) {
} public boolean isSame(String[] strs) {
} public void add(StringBuffer sb
}
}
偽對象的行為可以按照下面的方式來定義
//get mock control
MockControl control = MockControl
//get mock object
Foo foo = (Foo)control
//begin behavior definition
//specify which method invocation
//to be defined
foo
//define the behavior
//argument is
control
//end behavior definition
control
MockControl中超過
o setReturnValue()
這些方法被用來定義最後的方法調用應該返回一個值作為參數
當然也可以在行為中加入預期調用的次數
MockControl control =
Foo foo = (Foo)control
foo
//define the behavior
//argument is
//to be called just once
setReturnValue(
上面的代碼段定義了bar(
foo
//define the behavior
//argument is
//to be called at least once and at most
//times
setReturnValue(
現在bar(
foo
//define the behavior
//argument is
//to be called at least once
setReturnValue(
Range
這兒還有一個特定的設置返回值的方法
foo
//define the behavior
//bar(int) despite the argument value
setDefaultReturnValue(
o setThrowable
setThrowable(Throwable throwable)被用來定義方法調用異常拋出的行為
try {
foo
} catch (Exception e) {
//skip
}
//define the behavior
//when call dummy()
//to be called exactly once
control
o setVoidCallable()
setVoidCallable()被用於沒有返回值的方法
try {
foo
} catch (Exception e) {
//skip
}
//define the behavior
//when calling dummy()
//to be called at least once
control
o
From:http://tw.wingwit.com/Article/program/Java/ky/201311/27968.html