I have code where I populate Resultset
with CallableStatement.executeQuery()
. I have mocked ResultSet
and CallableStatement
but in order to test the method i have to populate ResultSet
.
Here is the code from the method I am testing
ResultSet rset = cs.executeQuery(); while (rset.next()) { IndexVolatilityImpl tsImpl = new IndexVolatilityImpl(); tsImpl.setTradeDate(rset.getString("trade_date")); tsImpl.setTradeTime(rset.getString("trade_time")); tsImpl.setExprDate(rset.getString("expr_date")); tsImpl.setSymbol(rset.getString("symbol")); tsImpl.setTradePrice(rset.getDouble("trade_price")); tsImpl.setContractMonth(rset.getString("contract_month")); tsImpl.setMilliSecs(rset.getString("trade_time_thou")); colIndexVolatilityImpl.add(tsImpl);
I have mocked the CallableStatement and ResultSet now since they are mocked my rset comes up empty. I would like to populate Resultset and doing it as below
resultSetMock = Mockito.mock(ResultSet.class); Mockito.when(resultSetMock.getString("trade_date")).thenReturn("03/10/2011"); Mockito.when(resultSetMock.getString("trade_time")).thenReturn("12:24:56"); Mockito.when(resultSetMock.getString("expr_date")).thenReturn("03/19/2011"); Mockito.when(resultSetMock.getString("symbol")).thenReturn("VIX1"); Mockito.when(resultSetMock.getDouble("trade_price")).thenReturn(Double.valueOf("20.96")); Mockito.when(resultSetMock.getString("contract_month")).thenReturn("1"); Mockito.when(resultSetMock.getString("trade_time_thou")).thenReturn("165"); Mockito.doReturn(resultSetMock).when(callableStatementMock).executeQuery();
But rset
is null
.
Generating a ResultSetPreparedStatement pstmt = dbConnection. prepareStatement("select * from employees"); ResultSet rs = pstmt. executeQuery(); The ResultSet object maintains a cursor that points to the current row of the result set.
The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.
You should also mock the next()
method to have it return true the first time it's called, as mockito will return false
by default.
Mockito.when(resultSetMock.next()).thenReturn(true).thenReturn(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With