wiki:demo_04

Version 3 (modified by chenyang, 14 years ago) (diff)

--

单元测试应用示例——测试工具类

工具类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是数据库表的元信息,元信息依赖SimpleJdbcTemplate对象根据表名获取,我们让测试类SqlHelperTest继承之AbstractTransactionalJUnit4SpringContextTests
以获得applicationContext对象的引用,然后注入SimpleJdbcTemplate对象.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class SqlHelperTest extends
                AbstractTransactionalJUnit4SpringContextTests {

        @Autowired
        SimpleJdbcTemplate simpleJdbcTemplate;

        ......
}