返回列表 发帖

单元测试spring中的jdbcTemplate调用存储过程详解

准备过程
  1. //建表
  2. create table TEST_USERS     
  3. (     
  4.   USER_ID  VARCHAR2(10) not null,     
  5.   NAME     VARCHAR2(10) not null,     
  6.   PASSWORD VARCHAR2(20) not null     
  7. )   

  8. 准备如下数据测试
  9. USER_ID=test1    name=aa    password=aa     
  10. USER_ID=test2    name=bb    password=bb     
  11. USER_ID=test3    name=cc    password=cc   


  12. // 创建存储过程
  13. create or replace procedure display_users_proc(results_out out SYS_REFCURSOR,
  14.                                                           userId      in test_users.user_id%type) is
  15. begin
  16.   if userId is not null then
  17.     open results_out for
  18.       select * from test_users where user_id like userId || '%';
  19.   else
  20.     open results_out for
  21.       select * from test_users;
  22.   end if;
  23. end display_users_proc;
复制代码
  1. public class ProcCallableStatementCreator implements CallableStatementCreator {
  2.     private String storedProc;   
  3.     private String params;   
  4.         
  5.    
  6.     /**   
  7.      * Constructs a callable statement.   
  8.      * @param storedProc                  The stored procedure's name.   
  9.      * @param params                      Input parameters.   
  10.      * @param outResultCount              count of output result set.   
  11.      */   
  12.     public ProcCallableStatementCreator(String storedProc, String params) {   
  13.         this.params = params;   
  14.         this.storedProc = storedProc;   
  15.     }   
  16.         
  17.     /**   
  18.      * Returns a callable statement   
  19.      * @param conn          Connection to use to create statement   
  20.      * @return cs           A callable statement   
  21.      */   
  22.     public CallableStatement createCallableStatement(Connection conn) {   
  23.         StringBuffer storedProcName = new StringBuffer("call ");   
  24.         storedProcName.append(storedProc + "(");   
  25.         //set output parameters   
  26.         storedProcName.append("?");   
  27.         storedProcName.append(", ");   
  28.             
  29.         //set input parameters   
  30.         storedProcName.append("?");   
  31.         storedProcName.append(")");   
  32.         CallableStatement cs = null;   
  33.         try {   
  34.             // set the first parameter is OracleTyep.CURSOR for oracel stored procedure   
  35.             cs = conn.prepareCall(storedProcName.toString());   
  36.             cs.registerOutParameter (1, OracleTypes.CURSOR);   
  37.            // set the sencond paramter   
  38.             cs.setObject(2, params);   
  39.         }
  40.         catch (SQLException e)
  41.         {   
  42.             throw new RuntimeException("createCallableStatement method Error : SQLException " + e.getMessage());   
  43.         }   
  44.         return cs;   
  45.     }   

  46. }
复制代码
  1. public class ProcCallableStatementCallback implements CallableStatementCallback {
  2.     /**   
  3.      * Constructs a ProcCallableStatementCallback.   
  4.      */   
  5.     public ProcCallableStatementCallback() {   
  6.     }   
  7.     /**   
  8.      * Returns a List(Map) collection.   
  9.      * @param cs                       object that can create a CallableStatement given a Connection   
  10.      * @return resultsList             a result object returned by the action, or null   
  11.      */   
  12.     public Object doInCallableStatement(CallableStatement cs)
  13.     {   
  14.         List<Map> resultsMap =  new ArrayList<Map>();   
  15.         try
  16.         {   
  17.             cs.execute();     
  18.             ResultSet rs = (ResultSet) cs.getObject(1);   
  19.             while (rs.next())
  20.             {   
  21.                 Map<String, String> rowMap = new HashMap<String, String>();   
  22.                 rowMap.put("userId", rs.getString("USER_ID"));   
  23.                 rowMap.put("name", rs.getString("NAME"));   
  24.                 rowMap.put("password", rs.getString("PASSWORD"));   
  25.                 resultsMap.add(rowMap);   
  26.             }      
  27.             rs.close();   
  28.         }catch(SQLException e)
  29.         {   
  30.             throw new RuntimeException("doInCallableStatement method error : SQLException " + e.getMessage());   
  31.         }   
  32.         return resultsMap;   
  33.    }
  34. }
复制代码
  1. public class SpringStoredProce extends JdbcDaoSupport{
  2.     @SuppressWarnings("unchecked")
  3. public List<Map> execute(String storedProc, String params){   
  4.         List<Map> resultList = null;   
  5.         try
  6.         {   
  7.             final DataSource ds = getDataSource();   
  8.             final JdbcTemplate template = new JdbcTemplate(ds);   
  9.             resultList = (List<Map>)template.execute(new ProcCallableStatementCreator(storedProc, params), new ProcCallableStatementCallback());   
  10.         }catch(DataAccessException e)
  11.         {   
  12.             throw new RuntimeException("execute method error : DataAccessException " + e.getMessage());   
  13.         }   
  14.          return resultList;   
  15.     }
  16. }
复制代码
  1. public class SpringStoredProceTest {
  2.    
  3.     private SpringStoredProce springStoredProce;     
  4.    
  5.     /**   
  6.      * @throws java.lang.Exception   
  7.      */     
  8.     @Before     
  9.     public void setUp() throws Exception {     
  10.        springStoredProce = new SpringStoredProce();     
  11.     }     
  12.    
  13.     /**   
  14.      * @throws java.lang.Exception   
  15.      */     
  16.     @After     
  17.     public void tearDown() throws Exception {     
  18.        springStoredProce = null;     
  19.     }     
  20.    
  21.     /**   
  22.      * Test method   
  23.      */     
  24.     @Test     
  25.     public void testExecute() {     
  26.        final String storedProcName = "display_users_proc";     
  27.        final String param = "test";     
  28.        List<Map> resultList = springStoredProce.execute(storedProcName, param);     
  29.        assertNotNull(resultList);     
  30.        assertTrue(resultList.size() > 0);     
  31.        for (int i = 0; i < resultList.size(); i++)
  32.        {     
  33.           Map rowMap = resultList.get(i);     
  34.           final String userId = rowMap.get("userId").toString();     
  35.           final String name = rowMap.get("name").toString();     
  36.           final String password = rowMap.get("password").toString();     
  37.           System.out.println("USER_ID=" + userId + "\t name=" + name + "\t password=" + password);     
  38.        }     
  39.             
  40.     }     
  41. }
复制代码
  1. 单元测试 最后运行结果 (注意准备插入几条记录进去测试)
  2. [code]
  3. USER_ID=test1    name=aa    password=aa     
  4. USER_ID=test2    name=bb    password=bb     
  5. USER_ID=test3    name=cc    password=cc   
复制代码

[ 本帖最后由 heyitang 于 2010-5-26 16:50 编辑 ]
倚楼听风雨,笑看江湖路。。。

返回列表