1

return (Map) execute(csc, new CallableStatementCallback()StoredProcedure を拡張する次のクラスを単体テストしようとすると、次の行で NullPointerException が発生しJDBCTemplateます。executeメソッド、DataSource、および sql で渡される Bean をモックしました。

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; 
    }
}

テスト ケース: PS - このテスト ケースをデバッグすると、StoredProcedure モックはまったく使用されません。代わりに、実際の実装が使用されます。

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);
}
4

1 に答える 1

1

モックの一部は、再生していないため使用されていません。に変更する必要がありreplay(bean)ますreplay(bean, datasource, storedProcedure)

別の注意として、map嘲笑する必要はありません。への呼び出しが予想されるstoredProcedure.execute(...)場合は、事前入力された を返すことができますmap

于 2013-04-05T15:48:22.987 に答える