单元测试应用示例——测试工具类
工具类cn.com.pcgames.gamehall2.util.SqlHelper是游戏大厅DAO层辅助工具类.例如:SqlHelper?.buildInsert(List<FieldDesc?> fields, String tablename,String[] excludes);
根据数据库表元信息,表名生成sql插入语句,使用示例代码如cn.com.pcgames.gamehall2.repository.impl.GameDAOImpl
public class GameDAOImpl extends AbstractRepository<Game> implements GameDAO {
private List<FieldDesc> tableFields;
public void setTableFields(List<FieldDesc> tableFields) {
this.tableFields = tableFields;
}
public void init() {
this.tableFields = SqlHelper.listFields(simpleJdbcTemplate, "game");
}
public GameDAOImpl() {
super(Game.class);
}
public long createGame(Game game) {
long gameId = idGenerator.generate("game", "gameId");
game.setGameId(gameId);
//SqlHelper生成插入语句
String sql = SqlHelper.buildInsert(tableFields, "game", null);
Object[] params = SqlHelper.getParameters(game, tableFields, null);
int result = simpleJdbcTemplate.update(sql, params);
return result == 1 ? gameId : 0;
}
......
}
如何单元测试SqlHelper.buildInsert?
测试SqlHelper.buildInsert(List<FieldDesc?> fields, String tablename,String[] excludes);方法,需要准备fields,tablename,excludes这三个参数
- 准备fields
fields是数据库表的元信息,元信息我们可以模拟.由newFieldDescs方法返回
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class SqlHelperTest extends
AbstractTransactionalJUnit4SpringContextTests {
@Autowired
SimpleJdbcTemplate simpleJdbcTemplate;
private List<FieldDesc> newFieldDescs() {
List<FieldDesc> list = new ArrayList<FieldDesc>();
FieldDesc id = new FieldDesc();
id.setField("gameId");
id.setType("int(11)");
FieldDesc createAt = new FieldDesc();
createAt.setField("createAt");
createAt.setType("timestamp");
list.add(id);
list.add(createAt);
return list;
}
......
}
- 准备tablename,我们可以在数据库中创建一张表,用来测试
- excludes用来指定,哪些字段不参与构建sql插入语句,这里可以设置null
测试准备工作,做好了,下面就可以编写测试了
@Test
public void testBuildInsert() {
List<FieldDesc> list = newFieldDescs();
String insert = SqlHelper.buildInsert(list, "game", null);
//断言工具类生成的sql语句,与我们期望的一致
Assert.assertEquals("INSERT INTO game (gameId,createAt) VALUES (?,?)",
insert);
}
![(please configure the [header_logo] section in trac.ini)](http://www1.pconline.com.cn/hr/2009/global/images/logo.gif)