Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock resultset and populate it using Mockito in Java

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.

like image 971
Tejas Shah Avatar asked Jun 07 '11 15:06

Tejas Shah


People also ask

How do you create a ResultSet in Java?

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.

Can we mock interface using Mockito?

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.


1 Answers

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); 
like image 155
proactif Avatar answered Sep 28 '22 05:09

proactif