moving unit tests from .testsuite -> .jdbc

This commit is contained in:
Chris Beams
2008-12-16 23:29:28 +00:00
parent f2e9abf699
commit ed27e04a0d
31 changed files with 108 additions and 741 deletions

View File

@@ -37,7 +37,7 @@ public abstract class AbstractJdbcTests extends TestCase {
protected DataSource mockDataSource;
protected MockControl ctrlConnection;
protected Connection mockConnection;
/**
* Set to true if the user wants verification, indicated
* by a call to replay(). We need to make this optional,
@@ -82,4 +82,4 @@ public abstract class AbstractJdbcTests extends TestCase {
return this.shouldVerify;
}
}
}

View File

@@ -47,4 +47,4 @@ public class Customer {
return "Customer: id=" + id + "; forename=" + forename;
}
}
}

View File

@@ -26,7 +26,6 @@ import java.sql.Timestamp;
import java.sql.Types;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
@@ -122,18 +121,18 @@ public abstract class AbstractRowMapperTests extends TestCase {
protected void verifyPerson(Person bean) {
verify();
Assert.assertEquals("Bubba", bean.getName());
Assert.assertEquals(22L, bean.getAge());
Assert.assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
Assert.assertEquals(new BigDecimal("1234.56"), bean.getBalance());
assertEquals("Bubba", bean.getName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
protected void verifyConcretePerson(ConcretePerson bean) {
verify();
Assert.assertEquals("Bubba", bean.getName());
Assert.assertEquals(22L, bean.getAge());
Assert.assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
Assert.assertEquals(new BigDecimal("1234.56"), bean.getBalance());
assertEquals("Bubba", bean.getName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
private void verify() {
@@ -143,4 +142,4 @@ public abstract class AbstractRowMapperTests extends TestCase {
stmtControl.verify();
}
}
}

View File

@@ -39,4 +39,4 @@ public class SimpleRowCountCallbackHandler implements RowCallbackHandler {
return count;
}
}
}

View File

@@ -0,0 +1,413 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.namedparam;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.AbstractJdbcTests;
import org.springframework.jdbc.Customer;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
private static final String SELECT_NAMED_PARAMETERS =
"select id, forename from custmr where id = :id and country = :country";
private static final String SELECT_NAMED_PARAMETERS_PARSED =
"select id, forename from custmr where id = ? and country = ?";
private static final String UPDATE_NAMED_PARAMETERS =
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
private static final String UPDATE_NAMED_PARAMETERS_PARSED =
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private MockControl ctrlPreparedStatement;
private PreparedStatement mockPreparedStatement;
private MockControl ctrlResultSet;
private ResultSet mockResultSet;
protected void setUp() throws Exception {
super.setUp();
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
ctrlResultSet = MockControl.createControl(ResultSet.class);
mockResultSet = (ResultSet) ctrlResultSet.getMock();
}
protected void tearDown() throws Exception {
super.tearDown();
if (shouldVerify()) {
ctrlPreparedStatement.verify();
ctrlResultSet.verify();
}
}
protected void replay() {
super.replay();
ctrlPreparedStatement.replay();
ctrlResultSet.replay();
}
public void testNullDataSourceProvidedToCtor() throws Exception {
try {
new NamedParameterJdbcTemplate((DataSource) null);
fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ex) { /* expected */ }
}
public void testNullJdbcTemplateProvidedToCtor() throws Exception {
try {
new NamedParameterJdbcTemplate((JdbcOperations) null);
fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ex) { /* expected */ }
}
public void testExecute() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(2, new Integer(1));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("perfId", new Integer(1));
params.put("priceId", new Integer(1));
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
assertEquals(mockPreparedStatement, ps);
ps.executeUpdate();
return "result";
}
}));
}
public void testExecuteWithTypedParameters() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
assertEquals(mockPreparedStatement, ps);
ps.executeUpdate();
return "result";
}
}));
}
public void testUpdate() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(2, new Integer(1));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("perfId", new Integer(1));
params.put("priceId", new Integer(1));
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
assertEquals(1, rowsAffected);
}
public void testUpdateWithTypedParameters() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
assertEquals(1, rowsAffected);
}
public void testQueryWithResultSetExtractor() throws SQLException {
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt("id");
ctrlResultSet.setReturnValue(1);
mockResultSet.getString("forename");
ctrlResultSet.setReturnValue("rod");
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(2, "UK");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("country", "UK");
Customer cust = (Customer) jt.query(SELECT_NAMED_PARAMETERS, params, new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
rs.next();
Customer cust = new Customer();
cust.setId(rs.getInt(COLUMN_NAMES[0]));
cust.setForename(rs.getString(COLUMN_NAMES[1]));
return cust;
}
});
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
}
public void testQueryWithRowCallbackHandler() throws SQLException {
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt("id");
ctrlResultSet.setReturnValue(1);
mockResultSet.getString("forename");
ctrlResultSet.setReturnValue("rod");
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(2, "UK");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("country", "UK");
final List customers = new LinkedList();
jt.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Customer cust = new Customer();
cust.setId(rs.getInt(COLUMN_NAMES[0]));
cust.setForename(rs.getString(COLUMN_NAMES[1]));
customers.add(cust);
}
});
assertEquals(1, customers.size());
Customer cust = (Customer) customers.get(0);
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
}
public void testQueryWithRowMapper() throws SQLException {
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt("id");
ctrlResultSet.setReturnValue(1);
mockResultSet.getString("forename");
ctrlResultSet.setReturnValue("rod");
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(2, "UK");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("country", "UK");
List customers = jt.query(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
Customer cust = new Customer();
cust.setId(rs.getInt(COLUMN_NAMES[0]));
cust.setForename(rs.getString(COLUMN_NAMES[1]));
return cust;
}
});
assertEquals(1, customers.size());
Customer cust = (Customer) customers.get(0);
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
}
public void testQueryForObjectWithRowMapper() throws SQLException {
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt("id");
ctrlResultSet.setReturnValue(1);
mockResultSet.getString("forename");
ctrlResultSet.setReturnValue("rod");
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(2, "UK");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
Map params = new HashMap();
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
params.put("country", "UK");
Customer cust = (Customer) jt.queryForObject(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
Customer cust = new Customer();
cust.setId(rs.getInt(COLUMN_NAMES[0]));
cust.setForename(rs.getString(COLUMN_NAMES[1]));
return cust;
}
});
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
}
}

View File

@@ -0,0 +1,114 @@
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.core.metadata.CallMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlInOutParameter;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Mock object based tests for CallMetaDataContext.
*
* @author Thomas Risberg
*/
public class CallMetaDataContextTests extends TestCase {
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
private CallMetaDataContext context = new CallMetaDataContext();
protected void setUp() throws Exception {
super.setUp();
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
}
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
}
public void testMatchParameterValuesAndSqlInOutParameters() throws Exception {
final String TABLE = "customers";
final String USER = "me";
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue(USER);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
replay();
List<SqlParameter> parameters = new ArrayList<SqlParameter>();
parameters.add(new SqlParameter("id", Types.NUMERIC));
parameters.add(new SqlInOutParameter("name", Types.NUMERIC));
parameters.add(new SqlOutParameter("customer_no", Types.NUMERIC));
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("id", 1);
parameterSource.addValue("name", "Sven");
parameterSource.addValue("customer_no", "12345XYZ");
context.setProcedureName(TABLE);
context.initializeMetaData(mockDataSource);
context.processParameters(parameters);
Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource);
assertEquals("Wrong number of matched in parameter values", 2, inParameters.size());
assertTrue("in parameter value missing", inParameters.containsKey("id"));
assertTrue("in out parameter value missing", inParameters.containsKey("name"));
assertTrue("out parameter value matched", !inParameters.containsKey("customer_no"));
List<String> names = context.getOutParameterNames();
assertEquals("Wrong number of out parameters", 2, names.size());
List<SqlParameter> callParameters = context.getCallParameters();
assertEquals("Wrong number of call parameters", 3, callParameters.size());
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.simple;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.AbstractRowMapperTests;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.Person;
/**
* @author Thomas Risberg
*/
public class ParameterizedBeanPropertyRowMapperTests extends AbstractRowMapperTests {
private SimpleJdbcTemplate simpleJdbcTemplate;
protected void setUp() throws SQLException {
super.setUp();
simpleJdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);
}
public void testOverridingClassDefinedForMapping() {
ParameterizedBeanPropertyRowMapper<Person> mapper =
ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
try {
((ParameterizedBeanPropertyRowMapper) mapper).setMappedClass(Long.class);
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
// expected
}
try {
mapper.setMappedClass(Person.class);
}
catch (InvalidDataAccessApiUsageException ex) {
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
}
}
public void testStaticQueryWithRowMapper() throws SQLException {
List<Person> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
ParameterizedBeanPropertyRowMapper.newInstance(Person.class));
assertEquals(1, result.size());
Person bean = result.get(0);
verifyPerson(bean);
}
public void testMappingWithInheritance() throws SQLException {
List<ConcretePerson> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
ParameterizedBeanPropertyRowMapper.newInstance(ConcretePerson.class));
assertEquals(1, result.size());
ConcretePerson bean = result.get(0);
verifyConcretePerson(bean);
}
}

View File

@@ -0,0 +1,469 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import javax.sql.DataSource;
import java.sql.*;
/**
* Mock object based tests for SimpleJdbcCall.
*
* @author Thomas Risberg
*/
public class SimpleJdbcCallTests extends TestCase {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
private MockControl ctrlCallable;
private CallableStatement mockCallable;
protected void setUp() throws Exception {
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
ctrlCallable = MockControl.createControl(CallableStatement.class);
mockCallable = (CallableStatement) ctrlCallable.getMock();
}
protected void tearDown() throws Exception {
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
ctrlCallable.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
ctrlCallable.replay();
}
public void testNoSuchStoredProcedure() throws Exception {
final String NO_SUCH_PROC = "x";
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue("me");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
SQLException sex =
new SQLException(
"Syntax error or access violation exception",
"42000");
mockCallable.execute();
ctrlCallable.setThrowable(sex);
mockCallable.close();
ctrlCallable.setVoidCallable();
mockConnection.prepareCall(
"{call " + NO_SUCH_PROC + "()}");
ctrlConnection.setReturnValue(mockCallable);
replay();
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(NO_SUCH_PROC);
try {
sproc.execute();
fail("Shouldn't succeed in running stored procedure which doesn't exist");
} catch (BadSqlGrammarException ex) {
// OK
}
}
public void testUnnamedParameterHandling() throws Exception {
final String MY_PROC = "my_proc";
replay();
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(MY_PROC);
try {
sproc.addDeclaredParameter(new SqlParameter(1));
fail("Shouldn't succeed in adding unnamed parameter");
} catch (InvalidDataAccessApiUsageException ex) {
// OK
}
}
public void testAddInvoiceProcWithoutMetaData() throws Exception {
final int amount = 1103;
final int custid = 3;
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue("me");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockCallable.setObject(1, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 3, 4);
ctrlCallable.setVoidCallable();
mockCallable.registerOutParameter(3, 4);
ctrlCallable.setVoidCallable();
mockCallable.execute();
ctrlCallable.setReturnValue(false);
mockCallable.getUpdateCount();
ctrlCallable.setReturnValue(-1);
mockCallable.getObject(3);
ctrlCallable.setReturnValue(new Long(4));
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
mockConnection.prepareCall(
"{call add_invoice(?, ?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
new SqlParameter("custid", Types.INTEGER),
new SqlOutParameter("newid", Types.INTEGER));
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
assertEquals(4, newId.intValue());
}
public void testAddInvoiceProcWithMetaData() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("PROCEDURE_CAT");
ctrlResultSet.setReturnValue(null);
mockResultSet.getString("PROCEDURE_SCHEM");
ctrlResultSet.setReturnValue(null);
mockResultSet.getString("PROCEDURE_NAME");
ctrlResultSet.setReturnValue("add_invoice");
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("amount");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("custid");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("newid");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("Oracle");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue("ME");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
mockDatabaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
mockCallable.setObject(1, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 3, 4);
ctrlCallable.setVoidCallable();
mockCallable.registerOutParameter(3, 4);
ctrlCallable.setVoidCallable();
mockCallable.execute();
ctrlCallable.setReturnValue(false);
mockCallable.getUpdateCount();
ctrlCallable.setReturnValue(-1);
mockCallable.getObject(3);
ctrlCallable.setReturnValue(new Long(4));
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
mockConnection.prepareCall(
"{call ADD_INVOICE(?, ?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
assertEquals(4, newId.intValue());
ctrlResultSet.verify();
}
public void testAddInvoiceFuncWithoutMetaData() throws Exception {
final int amount = 1103;
final int custid = 3;
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue("me");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockCallable.registerOutParameter(1, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(3, 3, 4);
ctrlCallable.setVoidCallable();
mockCallable.execute();
ctrlCallable.setReturnValue(false);
mockCallable.getUpdateCount();
ctrlCallable.setReturnValue(-1);
mockCallable.getObject(1);
ctrlCallable.setReturnValue(new Long(4));
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
mockConnection.prepareCall(
"{? = call add_invoice(?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
new SqlParameter("amount", Types.INTEGER),
new SqlParameter("custid", Types.INTEGER));
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
assertEquals(4, newId.intValue());
}
public void testAddInvoiceFuncWithMetaData() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("PROCEDURE_CAT");
ctrlResultSet.setReturnValue(null);
mockResultSet.getString("PROCEDURE_SCHEM");
ctrlResultSet.setReturnValue(null);
mockResultSet.getString("PROCEDURE_NAME");
ctrlResultSet.setReturnValue("add_invoice");
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(5);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("amount");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("custid");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
mockResultSet.getInt("DATA_TYPE");
ctrlResultSet.setReturnValue(4);
mockResultSet.getString("TYPE_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getBoolean("NULLABLE");
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("Oracle");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue("ME");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
mockDatabaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
mockCallable.registerOutParameter(1, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(3, 3, 4);
ctrlCallable.setVoidCallable();
mockCallable.execute();
ctrlCallable.setReturnValue(false);
mockCallable.getUpdateCount();
ctrlCallable.setReturnValue(-1);
mockCallable.getObject(1);
ctrlCallable.setReturnValue(new Long(4));
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
mockConnection.prepareCall(
"{? = call ADD_INVOICE(?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
assertEquals(4, newId.intValue());
ctrlResultSet.verify();
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.HashMap;
/**
* Mock object based tests for SimpleJdbcInsert.
*
* @author Thomas Risberg
*/
public class SimpleJdbcInsertTests extends TestCase {
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
protected void setUp() throws Exception {
super.setUp();
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
}
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
}
public void testNoSuchTable() throws Exception {
final String NO_SUCH_TABLE = "x";
final String USER = "me";
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.supportsGetGeneratedKeys();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getDatabaseProductVersion();
ctrlDatabaseMetaData.setReturnValue("1.0");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue(USER);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockDatabaseMetaData.getTables(null, null, NO_SUCH_TABLE, null);
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
ctrlResultSet.replay();
replay();
SimpleJdbcInsert insert = new SimpleJdbcInsert(mockDataSource).withTableName(NO_SUCH_TABLE);
try {
insert.execute(new HashMap());
fail("Shouldn't succeed in inserting into table which doesn't exist");
} catch (InvalidDataAccessApiUsageException ex) {
// OK
}
}
public void testInsert() throws Exception {
replay();
}
}

View File

@@ -0,0 +1,677 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.simple;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.easymock.internal.ArrayMatcher;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
/**
* @author Rod Johnson
* @author Rob Harrop
* @author Juergen Hoeller
* @author Thomas Risberg
*/
public class SimpleJdbcTemplateTests extends TestCase {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
public void testQueryForIntWithoutArgs() {
String sql = "SELECT COUNT(0) FROM BAR";
int expectedResult = 666;
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForInt(sql);
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
assertSame(jo, jth.getJdbcOperations());
int result = jth.queryForInt(sql);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForIntWithArgs() {
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
int expectedResult = 666;
int arg1 = 24;
String arg2 = "foo";
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForInt(sql, new Object[]{arg1, arg2});
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
int result = jth.queryForInt(sql, arg1, arg2);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForIntWithMap() {
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
int expectedResult = 666;
int arg1 = 24;
String arg2 = "foo";
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
Map args = new HashMap(2);
args.put("id", arg1);
args.put("xy", arg2);
npjo.queryForInt(sql, args);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
int result = jth.queryForInt(sql, args);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForIntWitSqlParameterSource() {
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
int expectedResult = 666;
int arg1 = 24;
String arg2 = "foo";
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
SqlParameterSource args = new MapSqlParameterSource().addValue("id", arg1).addValue("xy", arg2);
npjo.queryForInt(sql, args);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
int result = jth.queryForInt(sql, args);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForLongWithoutArgs() {
String sql = "SELECT COUNT(0) FROM BAR";
long expectedResult = 666;
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForLong(sql);
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
long result = jth.queryForLong(sql);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForLongWithArgs() {
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
long expectedResult = 666;
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForLong(sql, new Object[]{arg1, arg2, arg3});
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
long result = jth.queryForLong(sql, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForLongWithMap() {
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
long expectedResult = 666;
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForLong(sql, new Object[]{arg1, arg2, arg3});
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
long result = jth.queryForLong(sql, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithoutArgs() throws Exception {
String sql = "SELECT SYSDATE FROM DUAL";
Date expectedResult = new Date();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, Date.class);
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, Date.class);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithArgs() throws Exception {
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
Date expectedResult = new Date();
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithArgArray() throws Exception {
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
Date expectedResult = new Date();
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Object args = new Object[] {arg1, arg2, arg3};
Date result = jth.queryForObject(sql, Date.class, args);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithMap() throws Exception {
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
Date expectedResult = new Date();
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithRowMapperAndWithoutArgs() throws Exception {
String sql = "SELECT SYSDATE FROM DUAL";
Date expectedResult = new Date();
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
public Date mapRow(ResultSet rs, int rowNum) {
return new Date();
}
};
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, rm);
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, rm);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithRowMapperAndArgs() throws Exception {
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
Date expectedResult = new Date();
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
public Date mapRow(ResultSet rs, int rowNum) {
return new Date();
}
};
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForObjectWithRowMapperAndMap() throws Exception {
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
Date expectedResult = new Date();
double arg1 = 24.7;
String arg2 = "foo";
Object arg3 = new Object();
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
public Date mapRow(ResultSet rs, int rowNum) {
return new Date();
}
};
MockControl mc = MockControl.createControl(JdbcOperations.class);
JdbcOperations jo = (JdbcOperations) mc.getMock();
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
mc.setDefaultMatcher(new ArrayMatcher());
mc.setReturnValue(expectedResult);
mc.replay();
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
assertEquals(expectedResult, result);
mc.verify();
}
public void testQueryForListWithoutArgs() throws Exception {
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{}, Collections.singletonList(new Object()));
}
public void testQueryForListWithArgs() throws Exception {
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{1, 2, 3}, new LinkedList());
}
public void testQueryForListWithMap() throws Exception {
HashMap args = new HashMap(3);
args.put("1", 1);
args.put("2", 2);
args.put("3", 3);
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
}
public void testQueryForListWithSqlParameterSource() throws Exception {
MapSqlParameterSource args = new MapSqlParameterSource();
args.addValue("1", 1);
args.addValue("2", 2);
args.addValue("3", 3);
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
}
public void testQueryForMapWithoutArgs() throws Exception {
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{}, new HashMap());
}
public void testQueryForMapWithArgs() throws Exception {
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{1, 2, 3}, new HashMap());
// TODO test generic type
}
public void testQueryForMapWithMap() throws Exception {
HashMap args = new HashMap(3);
args.put("1", 1);
args.put("2", 2);
args.put("3", 3);
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
}
public void testQueryForMapWithSqlParameterSource() throws Exception {
MapSqlParameterSource args = new MapSqlParameterSource();
args.addValue("1", 1);
args.addValue("2", 2);
args.addValue("3", 3);
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
}
public void testUpdateWithoutArgs() throws Exception {
testDelegation("update", new Object[]{"sql"}, new Object[]{}, 666);
}
public void testUpdateWithArgs() throws Exception {
testDelegation("update", new Object[]{"sql"}, new Object[]{1, 2, 3}, 666);
}
public void testUpdateWithMap() throws Exception {
HashMap args = new HashMap(3);
args.put("1", 1);
args.put("2", 2);
args.put("3", 3);
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
}
public void testUpdateWithSqlParameterSource() throws Exception {
MapSqlParameterSource args = new MapSqlParameterSource();
args.addValue("1", 1);
args.addValue("2", 2);
args.addValue("3", 3);
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
}
private Object testDelegation(String methodName, Object[] typedArgs, Object[] varargs, Object expectedResult) throws Exception {
Class[] unifiedTypes;
Object[] unifiedArgs;
Class[] unifiedTypes2;
Object[] unifiedArgs2;
boolean namedParameters = false;
if (varargs != null && varargs.length > 0) {
// Allow for Map
if (varargs[0].getClass().equals(HashMap.class)) {
unifiedTypes = new Class[typedArgs.length + 1];
unifiedArgs = new Object[typedArgs.length + 1];
for (int i = 0; i < typedArgs.length; i++) {
unifiedTypes[i] = typedArgs[i].getClass();
unifiedArgs[i] = typedArgs[i];
}
unifiedTypes[unifiedTypes.length - 1] = Map.class;
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
unifiedTypes2 = unifiedTypes;
unifiedArgs2 = unifiedArgs;
namedParameters = true;
}
else if (varargs[0].getClass().equals(MapSqlParameterSource.class)) {
unifiedTypes = new Class[typedArgs.length + 1];
unifiedArgs = new Object[typedArgs.length + 1];
for (int i = 0; i < typedArgs.length; i++) {
unifiedTypes[i] = typedArgs[i].getClass();
unifiedArgs[i] = typedArgs[i];
}
unifiedTypes[unifiedTypes.length - 1] = SqlParameterSource.class;
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
unifiedTypes2 = unifiedTypes;
unifiedArgs2 = unifiedArgs;
namedParameters = true;
}
else {
// Allow for varargs.length
unifiedTypes = new Class[typedArgs.length + 1];
unifiedArgs = new Object[typedArgs.length + 1];
for (int i = 0; i < unifiedTypes.length - 1; i++) {
unifiedTypes[i] = typedArgs[i].getClass();
unifiedArgs[i] = typedArgs[i];
}
unifiedTypes[unifiedTypes.length - 1] = Object[].class;
unifiedArgs[unifiedTypes.length - 1] = varargs;
}
unifiedTypes2 = unifiedTypes;
unifiedArgs2 = unifiedArgs;
}
else {
unifiedTypes = new Class[typedArgs.length];
unifiedTypes2 = new Class[typedArgs.length + 1];
unifiedArgs = new Object[typedArgs.length];
unifiedArgs2 = new Object[typedArgs.length + 1];
for (int i = 0; i < typedArgs.length; i++) {
unifiedTypes[i] = unifiedTypes2[i] = typedArgs[i].getClass();
unifiedArgs[i] = unifiedArgs2[i] = typedArgs[i];
}
unifiedTypes2[unifiedTypes2.length - 1] = Object[].class;
unifiedArgs2[unifiedArgs2.length - 1] = new Object[]{};
}
MockControl mc;
JdbcOperations jo = null;
NamedParameterJdbcOperations npjo = null;
Method joMethod = null;
SimpleJdbcTemplate jth = null;
if (namedParameters) {
mc = MockControl.createControl(NamedParameterJdbcOperations.class);
npjo = (NamedParameterJdbcOperations) mc.getMock();
joMethod = NamedParameterJdbcOperations.class.getMethod(methodName, unifiedTypes);
joMethod.invoke(npjo, unifiedArgs);
jth = new SimpleJdbcTemplate(npjo);
}
else {
mc = MockControl.createControl(JdbcOperations.class);
jo = (JdbcOperations) mc.getMock();
joMethod = JdbcOperations.class.getMethod(methodName, unifiedTypes);
joMethod.invoke(jo, unifiedArgs);
jth = new SimpleJdbcTemplate(jo);
}
mc.setDefaultMatcher(new ArrayMatcher());
if (joMethod.getReturnType().isPrimitive()) {
// TODO bit of a hack with autoboxing passing up Integer when the return
// type is an int
mc.setReturnValue(((Integer) expectedResult).intValue());
}
else {
mc.setReturnValue(expectedResult);
}
mc.replay();
Method jthMethod = SimpleJdbcTemplate.class.getMethod(methodName, unifiedTypes2);
Object result = jthMethod.invoke(jth, unifiedArgs2);
assertEquals(expectedResult, result);
mc.verify();
return result;
}
public void testBatchUpdateWithSqlParameterSource() throws Exception {
MockControl ctrlDataSource;
DataSource mockDataSource;
MockControl ctrlConnection;
Connection mockConnection;
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
final SqlParameterSource[] ids = new SqlParameterSource[2];
ids[0] = new MapSqlParameterSource("id", 100);
ids[1] = new MapSqlParameterSource("id", 200);
final int[] rowsAffected = new int[] { 1, 2 };
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
mockPreparedStatement.getConnection();
ctrlPreparedStatement.setReturnValue(mockConnection);
mockPreparedStatement.setObject(1, ((Integer)ids[0].getValue("id")).intValue());
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(1, ((Integer)ids[1].getValue("id")).intValue());
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeBatch();
ctrlPreparedStatement.setReturnValue(rowsAffected);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MySQL");
mockDatabaseMetaData.supportsBatchUpdates();
ctrlDatabaseMetaData.setReturnValue(true);
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
mockConnection.getMetaData();
ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
ctrlPreparedStatement.replay();
ctrlDatabaseMetaData.replay();
ctrlDataSource.replay();
ctrlConnection.replay();
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
ctrlPreparedStatement.verify();
ctrlDatabaseMetaData.verify();
}
public void testBatchUpdateWithListOfObjectArrays() throws Exception {
MockControl ctrlDataSource;
DataSource mockDataSource;
MockControl ctrlConnection;
Connection mockConnection;
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final List<Object[]> ids = new ArrayList<Object[]>();
ids.add(new Object[] {100});
ids.add(new Object[] {200});
final int[] rowsAffected = new int[] { 1, 2 };
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
mockPreparedStatement.getConnection();
ctrlPreparedStatement.setReturnValue(mockConnection);
mockPreparedStatement.setObject(1, ((Integer)ids.get(0)[0]).intValue());
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(1, ((Integer)ids.get(1)[0]).intValue());
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeBatch();
ctrlPreparedStatement.setReturnValue(rowsAffected);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MySQL");
mockDatabaseMetaData.supportsBatchUpdates();
ctrlDatabaseMetaData.setReturnValue(true);
mockConnection.prepareStatement(sql);
ctrlConnection.setReturnValue(mockPreparedStatement);
mockConnection.getMetaData();
ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
ctrlPreparedStatement.replay();
ctrlDatabaseMetaData.replay();
ctrlDataSource.replay();
ctrlConnection.replay();
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
ctrlPreparedStatement.verify();
ctrlDatabaseMetaData.verify();
}
}

View File

@@ -0,0 +1,241 @@
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.springframework.jdbc.core.metadata.TableMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.SqlParameterValue;
import org.easymock.MockControl;
import javax.sql.DataSource;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.sql.Types;
import java.sql.DatabaseMetaData;
import java.sql.Connection;
import java.sql.ResultSet;
/**
* Mock object based tests for TableMetaDataContext.
*
* @author Thomas Risberg
*/
public class TableMetaDataContextTests extends TestCase {
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
private TableMetaDataContext context = new TableMetaDataContext();
protected void setUp() throws Exception {
super.setUp();
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
}
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
}
public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
final String TABLE = "customers";
final String USER = "me";
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
mockMetaDataResultSet.next();
ctrlMetaDataResultSet.setReturnValue(true);
mockMetaDataResultSet.getString("TABLE_CAT");
ctrlMetaDataResultSet.setReturnValue(null);
mockMetaDataResultSet.getString("TABLE_SCHEM");
ctrlMetaDataResultSet.setReturnValue(USER);
mockMetaDataResultSet.getString("TABLE_NAME");
ctrlMetaDataResultSet.setReturnValue(TABLE);
mockMetaDataResultSet.getString("TABLE_TYPE");
ctrlMetaDataResultSet.setReturnValue("TABLE");
mockMetaDataResultSet.next();
ctrlMetaDataResultSet.setReturnValue(false);
mockMetaDataResultSet.close();
ctrlMetaDataResultSet.setVoidCallable();
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.getString("COLUMN_NAME");
ctrlColumnsResultSet.setReturnValue("id");
mockColumnsResultSet.getInt("DATA_TYPE");
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
mockColumnsResultSet.getBoolean("NULLABLE");
ctrlColumnsResultSet.setReturnValue(false);
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.getString("COLUMN_NAME");
ctrlColumnsResultSet.setReturnValue("name");
mockColumnsResultSet.getInt("DATA_TYPE");
ctrlColumnsResultSet.setReturnValue(Types.VARCHAR);
mockColumnsResultSet.getBoolean("NULLABLE");
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.getString("COLUMN_NAME");
ctrlColumnsResultSet.setReturnValue("customersince");
mockColumnsResultSet.getInt("DATA_TYPE");
ctrlColumnsResultSet.setReturnValue(Types.DATE);
mockColumnsResultSet.getBoolean("NULLABLE");
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.getString("COLUMN_NAME");
ctrlColumnsResultSet.setReturnValue("version");
mockColumnsResultSet.getInt("DATA_TYPE");
ctrlColumnsResultSet.setReturnValue(Types.NUMERIC);
mockColumnsResultSet.getBoolean("NULLABLE");
ctrlColumnsResultSet.setReturnValue(false);
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(false);
mockColumnsResultSet.close();
ctrlColumnsResultSet.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.supportsGetGeneratedKeys();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getDatabaseProductVersion();
ctrlDatabaseMetaData.setReturnValue("1.0");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue(USER);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockDatabaseMetaData.getTables(null, null, TABLE, null);
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
ctrlMetaDataResultSet.replay();
ctrlColumnsResultSet.replay();
replay();
MapSqlParameterSource map = new MapSqlParameterSource();
map.addValue("id", 1);
map.addValue("name", "Sven");
map.addValue("customersince", new Date());
map.addValue("version", 0);
map.registerSqlType("customersince", Types.DATE);
map.registerSqlType("version", Types.NUMERIC);
context.setTableName(TABLE);
context.processMetaData(mockDataSource, new ArrayList<String>(), new String[] {});
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
assertEquals("wrong number of parameters: ", 4, values.size());
assertTrue("id not wrapped with type info", values.get(0) instanceof Number);
assertTrue("name not wrapped with type info", values.get(1) instanceof String);
assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue);
assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue);
}
public void testTableWithSingleColumnGeneratedKey() throws Exception {
final String TABLE = "customers";
final String USER = "me";
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
mockMetaDataResultSet.next();
ctrlMetaDataResultSet.setReturnValue(true);
mockMetaDataResultSet.getString("TABLE_CAT");
ctrlMetaDataResultSet.setReturnValue(null);
mockMetaDataResultSet.getString("TABLE_SCHEM");
ctrlMetaDataResultSet.setReturnValue(USER);
mockMetaDataResultSet.getString("TABLE_NAME");
ctrlMetaDataResultSet.setReturnValue(TABLE);
mockMetaDataResultSet.getString("TABLE_TYPE");
ctrlMetaDataResultSet.setReturnValue("TABLE");
mockMetaDataResultSet.next();
ctrlMetaDataResultSet.setReturnValue(false);
mockMetaDataResultSet.close();
ctrlMetaDataResultSet.setVoidCallable();
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(true);
mockColumnsResultSet.getString("COLUMN_NAME");
ctrlColumnsResultSet.setReturnValue("id");
mockColumnsResultSet.getInt("DATA_TYPE");
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
mockColumnsResultSet.getBoolean("NULLABLE");
ctrlColumnsResultSet.setReturnValue(false);
mockColumnsResultSet.next();
ctrlColumnsResultSet.setReturnValue(false);
mockColumnsResultSet.close();
ctrlColumnsResultSet.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.supportsGetGeneratedKeys();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.getDatabaseProductVersion();
ctrlDatabaseMetaData.setReturnValue("1.0");
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue(USER);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
mockDatabaseMetaData.getTables(null, null, TABLE, null);
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
ctrlMetaDataResultSet.replay();
ctrlColumnsResultSet.replay();
replay();
MapSqlParameterSource map = new MapSqlParameterSource();
String[] keyCols = new String[] {"id"};
context.setTableName(TABLE);
context.processMetaData(mockDataSource, new ArrayList<String>(), keyCols);
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
String insertString = context.createInsertString(keyCols);
assertEquals("wrong number of parameters: ", 0, values.size());
assertEquals("empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString);
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource.lookup;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class BeanFactoryDataSourceLookupTests {
private static final String DATASOURCE_BEAN_NAME = "dataSource";
@Test
public void testLookupSunnyDay() {
BeanFactory beanFactory = createMock(BeanFactory.class);
StubDataSource expectedDataSource = new StubDataSource();
expect(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).andReturn(expectedDataSource);
replay(beanFactory);
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.setBeanFactory(beanFactory);
DataSource dataSource = lookup.getDataSource(DATASOURCE_BEAN_NAME);
assertNotNull("A DataSourceLookup implementation must *never* return null from " +
"getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
verify(beanFactory);
}
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
final BeanFactory beanFactory = createMock(BeanFactory.class);
expect(
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)
).andThrow(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
replay(beanFactory);
try {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
lookup.getDataSource(DATASOURCE_BEAN_NAME);
fail("should have thrown DataSourceLookupFailureException");
} catch (DataSourceLookupFailureException ex) { /* expected */ }
verify(beanFactory);
}
@Test(expected=IllegalStateException.class)
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.getDataSource(DATASOURCE_BEAN_NAME);
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource.lookup;
import static org.junit.Assert.*;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.junit.Test;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class JndiDataSourceLookupTests {
private static final String DATA_SOURCE_NAME = "Love is like a stove, burns you when it's hot";
@Test
public void testSunnyDay() throws Exception {
final DataSource expectedDataSource = new StubDataSource();
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
@SuppressWarnings("unchecked")
protected Object lookup(String jndiName, Class requiredType) {
assertEquals(DATA_SOURCE_NAME, jndiName);
return expectedDataSource;
}
};
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
}
@Test(expected=DataSourceLookupFailureException.class)
public void testNoDataSourceAtJndiLocation() throws Exception {
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
@SuppressWarnings("unchecked")
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
assertEquals(DATA_SOURCE_NAME, jndiName);
throw new NamingException();
}
};
lookup.getDataSource(DATA_SOURCE_NAME);
}
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource.lookup;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Test;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class MapDataSourceLookupTests {
private static final String DATA_SOURCE_NAME = "dataSource";
@SuppressWarnings("unchecked")
@Test(expected=UnsupportedOperationException.class)
public void testGetDataSourcesReturnsUnmodifiableMap() throws Exception {
MapDataSourceLookup lookup = new MapDataSourceLookup(new HashMap());
Map dataSources = lookup.getDataSources();
dataSources.put("", "");
}
@Test
public void testLookupSunnyDay() throws Exception {
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
StubDataSource expectedDataSource = new StubDataSource();
dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.setDataSources(dataSources);
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
}
@Test
public void testSettingDataSourceMapToNullIsAnIdempotentOperation() throws Exception {
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
StubDataSource expectedDataSource = new StubDataSource();
dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.setDataSources(dataSources);
lookup.setDataSources(null); // must be idempotent (i.e. the following lookup must still work);
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
}
@Test
public void testAddingDataSourcePermitsOverride() throws Exception {
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
StubDataSource overridenDataSource = new StubDataSource();
StubDataSource expectedDataSource = new StubDataSource();
dataSources.put(DATA_SOURCE_NAME, overridenDataSource);
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.setDataSources(dataSources);
lookup.addDataSource(DATA_SOURCE_NAME, expectedDataSource); // must override existing entry
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
}
@SuppressWarnings("unchecked")
@Test(expected=ClassCastException.class)
public void testGetDataSourceWhereSuppliedMapHasNonDataSourceTypeUnderSpecifiedKey() throws Exception {
Map dataSources = new HashMap();
dataSources.put(DATA_SOURCE_NAME, new Object());
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.setDataSources(dataSources);
lookup.getDataSource(DATA_SOURCE_NAME);
}
@Test(expected=DataSourceLookupFailureException.class)
public void testGetDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() throws Exception {
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.getDataSource(DATA_SOURCE_NAME);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource.lookup;
import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.jdbc.datasource.AbstractDataSource;
/**
* Stub, do-nothing DataSource implementation.
*
* <p>All methods throw {@link UnsupportedOperationException}.
*
* @author Rick Evans
*/
class StubDataSource extends AbstractDataSource {
public Connection getConnection() throws SQLException {
throw new UnsupportedOperationException();
}
public Connection getConnection(String username, String password) throws SQLException {
throw new UnsupportedOperationException();
}
}

View File

@@ -21,6 +21,7 @@ import org.springframework.dao.DataAccessException;
/**
* @author Thomas Risberg
*/
@SuppressWarnings("serial")
public class CustomErrorCodeException extends DataAccessException {
public CustomErrorCodeException(String msg) {
@@ -31,4 +32,4 @@ public class CustomErrorCodeException extends DataAccessException {
super(msg, ex);
}
}
}

View File

@@ -75,4 +75,4 @@ public class SQLExceptionSubclassFactory {
return new SQLRecoverableException(reason, SQLState, vendorCode);
}
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import static org.junit.Assert.*;
import java.sql.SQLException;
import org.junit.Test;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.UncategorizedSQLException;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class SQLStateSQLExceptionTranslatorTests {
private static final String REASON = "The game is afoot!";
private static final String TASK = "Counting sheep... yawn.";
private static final String SQL = "select count(0) from t_sheep where over_fence = ... yawn... 1";
@Test(expected=IllegalArgumentException.class)
public void testTranslateNullException() throws Exception {
new SQLStateSQLExceptionTranslator().translate("", "", null);
}
@Test
public void testTranslateBadSqlGrammar() throws Exception {
doTest("07", BadSqlGrammarException.class);
}
@Test
public void testTranslateDataIntegrityViolation() throws Exception {
doTest("23", DataIntegrityViolationException.class);
}
@Test
public void testTranslateDataAccessResourceFailure() throws Exception {
doTest("53", DataAccessResourceFailureException.class);
}
@Test
public void testTranslateTransientDataAccessResourceFailure() throws Exception {
doTest("S1", TransientDataAccessResourceException.class);
}
@Test
public void testTranslateConcurrencyFailure() throws Exception {
doTest("40", ConcurrencyFailureException.class);
}
@Test
public void testTranslateUncategorized() throws Exception {
doTest("00000000", UncategorizedSQLException.class);
}
private void doTest(String sqlState, Class<?> dataAccessExceptionType) {
SQLException ex = new SQLException(REASON, sqlState);
SQLExceptionTranslator translator = new SQLStateSQLExceptionTranslator();
DataAccessException dax = translator.translate(TASK, SQL, ex);
assertNotNull("Translation must *never* result in a null DataAccessException being returned.", dax);
assertEquals("Wrong DataAccessException type returned as the result of the translation", dataAccessExceptionType, dax.getClass());
assertNotNull("The original SQLException must be preserved in the translated DataAccessException", dax.getCause());
assertSame("The exact same original SQLException must be preserved in the translated DataAccessException", ex, dax.getCause());
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--
Whacky error codes for testing
-->
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="badSqlGrammarCodes"><value>1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
<property name="customTranslations">
<list>
<bean class="org.springframework.jdbc.support.CustomSQLErrorCodesTranslation">
<property name="errorCodes"><value>999</value></property>
<property name="exceptionClass">
<value>org.springframework.jdbc.support.CustomErrorCodeException</value>
</property>
</bean>
</list>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--
Whacky error codes for testing
-->
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="badSqlGrammarCodes"><value>1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
</bean>
</beans>

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--
Whacky error codes for testing
-->
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="badSqlGrammarCodes"><value>1,2,942</value></property>
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
</bean>
<bean id="DB0" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="databaseProductName"><value>*DB0</value></property>
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
</bean>
<bean id="DB1" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="databaseProductName"><value>DB1*</value></property>
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
</bean>
<bean id="DB2" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="databaseProductName"><value>*DB2*</value></property>
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
</bean>
<bean id="DB3" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="databaseProductName"><value>*DB3*</value></property>
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
</bean>
</beans>