2013-04-04 89 views
1

當我嘗試單元測試擴展StoredProcedure下面的類我得到一個NullPointerException行:return (Map) execute(csc, new CallableStatementCallback()JDBCTemplate類。我嘲笑在execute方法中傳遞的bean,DataSource和sql。單元測試java類擴展存儲過程與EasyMock

public class MyStoredProc extends StoredProcedure { 
    /** 
    * Constructor - sets SQLParameters for the stored procedure. 
    * 
    * @param ds - DataSource 
    */ 
    public MyStoredProc(DataSource dataSource, String sql) { 
     super(dataSource, sql); 
     declareParameter(new SqlOutParameter("return",Types.NUMERIC)); 
     declareParameter(new SqlParameter("BATCH_ID",Types.NUMERIC)); 
     declareParameter(new SqlParameter("PROCESS_TYPE",Types.VARCHAR)); 

     complie(); 
    } 

    public BigDecimal execute(MyBean bean){ 
     BigDecimal returnValue = BigDecimal.valueOf(-1); 

     Map in = new HashMap(); 

     in.put("BATCH_ID", bean.getBatchID()); 
     in.put("PROCESS_TYPE", bean.getProcessType()); 

     Object obj = execute(in); 
     if (obj != null) { 
      Object output = ((HashMap) obj).get("return"); 

      if(output instanceof BigDecimal) { 
       returnValue = (BigDecimal)output; 
      } 
     } 
     return bigDec; 
    } 
} 

測試用例:P.S - 當我調試這個測試的情況下,模擬的StoredProcedure未在all.Instead使用的實際執行時使用。

public class MyStoredProcTest { 
private MyStoredProc mysp; 
private DataSource dataSource; 
private String sql; 
@Before 
public void setUp() { 
    dataSource = EasyMock.createMock(DataSource.class); 
    sql = "Testing"; 
    mysp = new MyStoredProc(dataSource, sql); 
} 

@Test 
public void testExecute() { 

    StoredProcedure storedProcedure = EasyMock 
      .createMock(StoredProcedure.class); 
    HashMap map = new HashMap(); 
    map.put("return", BigDecimal.ONE); 
    expect(storedProcedure.execute(EasyMock.anyObject(Map.class))).andReturn(map); 

    Connection con = EasyMock.createMock(Connection.class); 
    expect(dataSource.getConnection()).andReturn(con); 
    MyBean bean = EasyMock.createMock(MyBean.class); 


    expect(bean.getBatchID()).andReturn(BigDecimal.valueOf(.0001)) 
      .anyTimes(); 
    expect(bean.getProcessType()).andReturn("Process Type").anyTimes(); 

    replay(bean, dataSource, storedProcedure, con); 
    BigDecimal returnValue = null; 
    try { 
     returnValue = mysp.execute(bean); 
    } catch (Exception e) { 
     System.out.println("exception" + e.getStackTrace());// the Null pointer from JDBCTemplate is caught here. 
    } 
    Assert.assertEquals(BigDecimal.valueOf(-1), returnValue); 
} 
+0

你可以發佈測試嗎? – 2013-04-04 20:55:19

+0

測試用例發佈 – ShilR 2013-04-05 15:23:12

回答

0

你的一些嘲笑沒有被使用,因爲你沒有重播它們。您應該修改replay(bean)replay(bean, datasource, storedProcedure)

另一方面,map不需要被模擬。當您預計致電storedProcedure.execute(...)時,您可以返回預填充的map

+0

謝謝jradakov ...我仍然收到相同的錯誤。我添加了重播,創建了一個地圖實例,而不是根據您的建議嘲笑它,並添加了連接模擬(因爲它給了我一個意外的getConnection調用) – ShilR 2013-04-05 16:36:29

+0

我忘了添加「con」重播...做了這個,現在得到一個不同的錯誤...將嘗試解決它,併發布如果需要任何幫助 – ShilR 2013-04-05 16:40:48