How to unit test a function that converts a ResultSet into a list using Mockito.

If you have experience using JDBC driver in Java, you understand that when you call a Stored Procedure it will return you a result set.

If you want to convert this into an object, you will have to loop through the result set and explicitly create the list of objects, like so.

package resultSet;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultSetParser {

    public List<Employee> processEmployeeresults(ResultSet resultSet) throws SQLException {
        List<Employee> employeeList = new ArrayList<>();
        while(resultSet.next()){
            Employee employee = new Employee();
            employee.setId(resultSet.getInt("Id"));
            employee.setFirstName(resultSet.getString("FirstName"));
            employee.setLastName(resultSet.getString("LastName"));
            employee.setTitle(resultSet.getString("Title"));
            employee.setBirthdate(resultSet.getString("BirthDate"));

            employeeList.add(employee);
        }
        return employeeList;
    }
}

Mockito is a very useful test framework in this instance. We will mock the ResultSet, call the function, and verify a few properties match.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.util.Assert;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RunWith(MockitoJUnitRunner.class)
public class ResultSetParserTest {

    @Mock
    ResultSet resultSet;

    @Test
    public void testEmployeeResultSet(){
        try {
            createEmployeeResultSet();
            ResultSetParser parser = new ResultSetParser();
            List<Employee> employeeList = parser.processEmployeeresults(resultSet);
            //Grab the first Result Set
            Employee employee = employeeList.get(0);

            Assert.notEmpty(employeeList, "Employees were not parsed.");
            Assert.isTrue(employee.getId() == 1, "Employee Id is not equal to 1");
        } catch (SQLException e) {

        }
    }

    private void createEmployeeResultSet() throws SQLException {
        Mockito.when(resultSet.next()).thenReturn(true).thenReturn(false);
        Mockito.when(resultSet.getInt("Id"));
        Mockito.when(resultSet.getString("FirstName"));
        Mockito.when(resultSet.getString("LastName"));
        Mockito.when(resultSet.getString("Title"));
        Mockito.when(resultSet.getString("BirthDate"));
    }
}

There you have it, an easy solution for mocking and testing result sets. The resultSet.next().thenReturn(true).thenReturn(false); essentially opens the ResultSet for one iteration, so there will only be one record in the ResultSet.