單元測試要寫的量往往比產品程式碼還多,框架卻大同小異,只有類別名與變數名不同。與其複製貼上再逐一改名,不如花幾分鐘寫個產生器,以後隨時能 reuse。
import os, datetime
tplFilePath = 'E://template.java'
path = 'E://'
testObjList = ['Deposit', 'Config', 'FundsFilter', 'MobileOpenAuth',
'MobilePartnerRiskLevel', 'MobilePhoneChargeOrder',
'MobileSmspayValicode', 'MobileSystemParam', 'MobileVd',
'Order', 'OriginalOrder', 'Package', 'Plantform', 'Seq',
'Service', 'TipsDelivery', 'Trustlogin', 'UpdateConfig',
'UpdateHint', 'UserAccount', 'UserDao', 'UserStatus']
for testObj in testObjList:
testObjVarName = testObj[0].lower() + testObj[1:]
filename = 'Ibatis' + testObj + 'DAOTester.java'
author = 'chenxin'
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
tplFile = open(tplFilePath)
gFile = open(path + filename, "w")
for fileLine in tplFile.readlines():
line = (fileLine.replace('${author}', author)
.replace('${now}', now)
.replace('${testObject}', testObj)
.replace('${testObjVarName}', testObjVarName))
gFile.writelines(line)
tplFile.close()
gFile.close()
這裡用的是最樸素的 replace 策略:讀一行、換一輪、寫一行。變數只有四個,不需要引入 Template 也行。
/**
* created since ${now}
*/
package com.alipay.mspcore.common.dal.ibatis;
import java.util.Date;
import junit.framework.Assert;
import com.alipay.mspcore.common.dal.daointerface.${testObject}DAO;
import com.alipay.mspcore.common.dal.dataobject.${testObject};
/**
* @author ${author}
* @version $Id: Ibatis${testObject}DAOTester.java, v 0.1 ${now} ${author} Exp $
*/
public class Ibatis${testObject}DAOTester extends AnnotatedAutowireSofaTestCase {
private ${testObject}DAO get${testObject}DAO() {
${testObject}DAO dao = (${testObject}DAO)
this.getBean("${testObjVarName}DAO", ${testObject}DAO.class, null);
return dao;
}
public void test${testObject}DAO() {
${testObject}DAO configDAO = get${testObject}DAO();
Assert.assertNotNull(configDAO);
}
public void test() {
${testObject}DO ${testObjVarName}DO = new ${testObject}DO();
${testObjVarName}DO.setGmtCreate(new Date());
${testObjVarName}DO.setGmtModified(new Date());
${testObjVarName}DO.setId(10000);
${testObject}DAO ${testObjVarName}DAO = get${testObject}DAO();
long result = ${testObjVarName}DAO.insert(${testObjVarName}DO);
Assert.assertTrue(result > 0);
}
}
/**
* created since 2011-12-30 14:31:38
*/
package com.alipay.mspcore.common.dal.ibatis;
/**
* @author chenxin
* @version $Id: IbatisUpdateHintDAOTester.java, v 0.1 2011-12-30 14:31:38 chenxin Exp $
*/
public class IbatisUpdateHintDAOTester extends AnnotatedAutowireSofaTestCase {
private UpdateHintDAO getUpdateHintDAO() {
UpdateHintDAO dao = (UpdateHintDAO)
this.getBean("updateHintDAO", UpdateHintDAO.class, null);
return dao;
}
/* ... */
}
22 個類別一次搞定。這類腳本值得留一份在手邊:下次換專案,只要改替換表與模板,幾秒鐘就能生出一整批樣板。想再往前一步,可以把清單移到外部 CSV,讓非工程師也能維護要產生的項目。