這里該到模板方法(Template Method)模式發揮威力的時候了。我們將使用模板方法來繼續重構前面的案例。讓我們先來定義一個方法:
/**
* @author tao.youzt
*/
public class TestBizUrlDAO extends AbstractDependencyInjectionSpringContextTests {
private BizUrlDAO bizUrlDAO;
@Override
protected String[] getConfigLocations() {
return new String[]{"godzilla-dao.xml","godzilla-db.xml"};
}
protected void setupEnv(){
bizUrlDAO.delete("www.easyjf.com");
}
protected void cleanEnv(){
bizUrlDAO.delete("www.easyjf.com");
}
public void testTemp(){
//do test logic in this method
execute();
}
protected void execute(){
setupEnv();
doTestLogic();
setupEnv();
}
}
相比之前的方法,我們這里已經有了一些進步,定義了一個execute方法,在該方法開始和結束分別執行初始化和清除邏輯,然后由doTestLogic()方法實現測試邏輯。實際測試方法中只要執行execute方法,并傳入測試邏輯就可以了。瞧,不經意間我們已經實現了模板方法模式——把通用的邏輯封轉起來,變化的部分由具體方法提供。怎么,不相信么?呵呵,設計模式其實并不復雜,就是前人解決通用問題的一些最佳實踐總結而已。
此時你可能會說,TeseCase類已經提供了setUp()和tearDown()方法來做這件事情,我也想到了,哈哈!但這并不和本文產生沖突!
問題似乎越來越清晰,但我們遭遇了一條無法跨越的鴻溝——如何才能把測試邏輯傳遞到execute方法中呢?單靠傳統的編程方法已經無法解決這個問題,因此我們必須尋找其他途徑。
可能此時此刻你已經想到,本文另一個重要概念——回調方法模式還沒有用到,是不是該使用該模式了?沒錯,就是它了!我先把代碼給出,然后再詳細解釋。
我們提供了一個抽象類TestExecutor,并定義一個抽象的execute方法,然后為測試類的execute方法傳入一個TestExecutor的實例,并調用該實例的execute方法。最后,我們的測試方法中只需要new一個TestExecutor,并在execute方法中實現測試邏輯,便可以按照預期的方式執行:準備測試環境-執行測試邏輯-清除測試數據。這便是一個典型的回調方法模式的應用!
模板方法和回調函數模式說起來挺懸,其實也就這么簡單,明白了吧:)
三、如何為每個測試方法單獨提供環境方法呢?
通過前面的講解,相信大家對模板方法和回調函數模式都已經掌握了,這里直接給出相關代碼:
/**
* DAL層測試支持類.
*
*
* 除非特殊情況,所有DAO都要繼承此類.
*
* @author tao.youzt
*/
public abstract class GodzillaDalTestSupport extends AbstractDependencyInjectionSpringContextTests {
/*
* @see org.springframework.test.AbstractDependencyInjectionSpringContextTests#getConfigLocations()
*/
@Override
protected final String[] getConfigLocations() {
String[] configLocations = null;
String[] customConfigLocations = getCustomConfigLocations();
if (customConfigLocations != null && customConfigLocations.length > 0) {
configLocations = new String[customConfigLocations.length + 2];
configLocations[0] = "classpath:godzilla/dal/godzilla-db-test.xml";
configLocations[1] = "classpath:godzilla/dal/godzilla-dao.xml";
for (int i = 2; i < configLocations.length; i++) {
configLocations[i] = customConfigLocations[i - 2];
}
return configLocations;
} else {
return new String[] { "classpath:godzilla/dal/godzilla-db-test.xml",
"classpath:godzilla/dal/godzilla-dao.xml" };
}
}
/**
* 子類可以覆蓋該方法加載個性化配置.
*
* @return
*/
protected String[] getCustomConfigLocations() {
return null;
}
/**
* 準備測試環境.
*/
protected void setupEnv() {
}
/**
* 清除測試數據.
*/
protected void cleanEvn() {
}
/**
* 測試用例執行器.
*/
protected abstract class TestExecutor {
/**
* 準備測試環境
*/
public void setupEnv() {
}
/**
* 執行測試用例.
*/
public abstract void execute();
/**
* 清除測試數據.
*/
public void cleanEnv() {
}
}
/**
* 執行一個測試用例.
*
* @param executor
*/
protected final void execute(final TestExecutor executor) {
execute(IgnoralType.NONE, executor);
}
/**
文章來源于領測軟件測試網 http://www.kjueaiud.com/