Import ConnectionMother and EasyMock library in your project and create your test class.
For create objects to CallableStatement:
Follow de code, create the connection and use it.
This it's how set up the properties and call the method in the unit test.
/**
* JUnit test showing how to use ConnectionMother
*/
public void testAClassWithConnectionAndCallableStatement() {
ConnectionMother mother = new ConnectionMother();
mother.startNewCallableStatement("sp_name(? ? ? ? ?)");
mother.addInput("1");
mother.addInput("2");
mother.addOutput("3");
mother.addInput("4");
mother.addOutput("5");
Connection connection = mother.getConnection();
ClassUsingCallableStatement classUsed = new ClassUsingCallableStatement(connection);
// Verify if class had called the correct values.
assertEquals("3", classUsed.x);
assertEquals("5", classUsed.y);
// Verify if all expected parameters were supplied.
mother.verify();
}
And how we can see next, our class has a simple structure using the connection and calling procedures:
/**
* This class doesn't make idea that it's working with Mocks.
*/
public class ClassUsingCallableStatement {
String x;
String y;
public ClassUsingCallableStatement(Connection connection) throws SQLException {
CallableStatement statement = connection.prepareCall("sp_name(? ? ? ? ?)");
statement.setString(1, "1");
statement.setString(2, "2");
statement.registerOutParameter(3, Types.VARCHAR);
statement.setString(4, "4");
statement.registerOutParameter(5, Types.VARCHAR);
statement.execute();
x = statement.getString(3);
y = statement.getString(5);
statement.close();
}
}
For request jsut a ResultSet object, then you can create a ResultSetMother (a Factory Pattern (GoF) of MockResultSets) and pass to you method.
public void testWithResultSet() throws SQLException {
ResultSetMother resultSetMother = ConnectionMother.resultSetMother();
resultSetMother.addFieldNames("fieldName");
resultSetMother.addLine("returnValue");
ResultSet resultSet = resultSetMother.getResultSet();
String aValueFromResultSet = myMethodProcessingResultSet(resultSet);
assertEquals("returnValue", aValueFromResultSet);
}
To use PreparedStatement, you need to make different. See:
public void testGettingPreparedStatement() throws SQLException {
// We create a ResultSetMother to set in your procedure
ResultSetMother resultSetMother = ConnectionMother.resultSetMother();
resultSetMother.addFieldNames("coluna1");
resultSetMother.addLine("line1");
Procedure procedure = mother.startNewPreparedStatement("select * from table");
procedure.addResultSet(resultSetMother.getResultSet());
// Just get the connection
Connection connection = mother.getConnection();
// Here is how you use in your class
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
assertEquals("line1", resultSet.getString("coluna1"));
statement.close();
// You can use verify to assert called procedure were correct.
mother.verify();
}