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

@@ -1,85 +0,0 @@
/*
* AbstractJdbcTests.java
*
* Copyright (C) 2002 by Interprise Software. All rights reserved.
*/
/*
* Copyright 2002-2005 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;
import java.sql.Connection;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
/**
* @author Trevor D. Cook
*/
public abstract class AbstractJdbcTests extends TestCase {
protected MockControl ctrlDataSource;
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,
* otherwise we setUp() will always result in verification failures
*/
private boolean shouldVerify;
protected void setUp() throws Exception {
this.shouldVerify = false;
super.setUp();
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);
}
protected void replay() {
ctrlDataSource.replay();
ctrlConnection.replay();
this.shouldVerify = true;
}
protected void tearDown() throws Exception {
super.tearDown();
// we shouldn't verify unless the user called replay()
if (shouldVerify()) {
ctrlDataSource.verify();
//ctrlConnection.verify();
}
}
protected boolean shouldVerify() {
return this.shouldVerify;
}
}

View File

@@ -1,50 +0,0 @@
/*
* 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;
/**
* @author Juergen Hoeller
*/
public class Customer {
private int id;
private String forename;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String toString() {
return "Customer: id=" + id + "; forename=" + forename;
}
}

View File

@@ -1,145 +0,0 @@
/*
* 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;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.Person;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
/**
* Mock object based abstract class for RowMapper tests.
* Initializes mock objects and verifies results.
*
* @author Thomas Risberg
*/
public abstract class AbstractRowMapperTests extends TestCase {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
protected MockControl conControl;
protected Connection con;
protected MockControl rsmdControl;
protected ResultSetMetaData rsmd;
protected MockControl rsControl;
protected ResultSet rs;
protected MockControl stmtControl;
protected Statement stmt;
protected JdbcTemplate jdbcTemplate;
protected void setUp() throws SQLException {
conControl = MockControl.createControl(Connection.class);
con = (Connection) conControl.getMock();
con.isClosed();
conControl.setDefaultReturnValue(false);
rsmdControl = MockControl.createControl(ResultSetMetaData.class);
rsmd = (ResultSetMetaData)rsmdControl.getMock();
rsmd.getColumnCount();
rsmdControl.setReturnValue(4, 1);
rsmd.getColumnLabel(1);
rsmdControl.setReturnValue("name", 1);
rsmd.getColumnLabel(2);
rsmdControl.setReturnValue("age", 1);
rsmd.getColumnLabel(3);
rsmdControl.setReturnValue("birth_date", 1);
rsmd.getColumnLabel(4);
rsmdControl.setReturnValue("balance", 1);
rsmdControl.replay();
rsControl = MockControl.createControl(ResultSet.class);
rs = (ResultSet) rsControl.getMock();
rs.getMetaData();
rsControl.setReturnValue(rsmd, 1);
rs.next();
rsControl.setReturnValue(true, 1);
rs.getString(1);
rsControl.setReturnValue("Bubba", 1);
rs.wasNull();
rsControl.setReturnValue(false, 1);
rs.getLong(2);
rsControl.setReturnValue(22, 1);
rs.getTimestamp(3);
rsControl.setReturnValue(new Timestamp(1221222L), 1);
rs.getBigDecimal(4);
rsControl.setReturnValue(new BigDecimal("1234.56"), 1);
rs.next();
rsControl.setReturnValue(false, 1);
rs.close();
rsControl.setVoidCallable(1);
rsControl.replay();
stmtControl = MockControl.createControl(Statement.class);
stmt = (Statement) stmtControl.getMock();
con.createStatement();
conControl.setReturnValue(stmt, 1);
stmt.executeQuery("select name, age, birth_date, balance from people");
stmtControl.setReturnValue(rs, 1);
if (debugEnabled) {
stmt.getWarnings();
stmtControl.setReturnValue(null, 1);
}
stmt.close();
stmtControl.setVoidCallable(1);
conControl.replay();
stmtControl.replay();
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
}
protected void verifyPerson(Person bean) {
verify();
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();
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() {
conControl.verify();
rsControl.verify();
rsmdControl.verify();
stmtControl.verify();
}
}

View File

@@ -1,42 +0,0 @@
/*
* 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.core;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Simple row count callback handler for testing purposes.
* Does not call any JDBC methods on the given ResultSet.
*
* @author Juergen Hoeller
* @since 2.0
*/
public class SimpleRowCountCallbackHandler implements RowCallbackHandler {
private int count;
public void processRow(ResultSet rs) throws SQLException {
count++;
}
public int getCount() {
return count;
}
}

View File

@@ -1,415 +0,0 @@
/*
* 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;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
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 {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new NamedParameterJdbcTemplate((DataSource) null);
}
}.runTest();
}
public void testNullJdbcTemplateProvidedToCtor() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new NamedParameterJdbcTemplate((JdbcOperations) null);
}
}.runTest();
}
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

@@ -1,114 +0,0 @@
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

@@ -1,73 +0,0 @@
/*
* 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

@@ -1,469 +0,0 @@
/*
* 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

@@ -1,118 +0,0 @@
/*
* 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

@@ -1,677 +0,0 @@
/*
* 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

@@ -1,241 +0,0 @@
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

@@ -1,57 +0,0 @@
/*
* 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.test;
import java.util.Date;
/**
* @author Thomas Risberg
*/
public abstract class AbstractPerson {
private String name;
private long age;
private java.util.Date birth_date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
public Date getBirth_date() {
return birth_date;
}
public void setBirth_date(Date birth_date) {
this.birth_date = birth_date;
}
}

View File

@@ -1,37 +0,0 @@
/*
* 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.test;
import java.math.BigDecimal;
/**
* @author Thomas Risberg
*/
public class ConcretePerson extends AbstractPerson {
private BigDecimal balance;
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}

View File

@@ -1,35 +0,0 @@
/*
* 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.test;
/**
* @author Juergen Hoeller
*/
public class ExtendedPerson extends ConcretePerson {
private Object someField;
public Object getSomeField() {
return someField;
}
public void setSomeField(Object someField) {
this.someField = someField;
}
}

View File

@@ -1,67 +0,0 @@
/*
* 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.test;
import java.math.BigDecimal;
/**
* @author Thomas Risberg
*/
public class Person {
private String name;
private long age;
private java.util.Date birth_date;
private BigDecimal balance;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
public java.util.Date getBirth_date() {
return birth_date;
}
public void setBirth_date(java.util.Date birth_date) {
this.birth_date = birth_date;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balanace) {
this.balance = balanace;
}
}

View File

@@ -1,84 +0,0 @@
/*
* 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 javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class BeanFactoryDataSourceLookupTests extends TestCase {
private static final String DATASOURCE_BEAN_NAME = "dataSource";
public void testLookupSunnyDay() throws Exception {
MockControl mockBeanFactory = MockControl.createControl(BeanFactory.class);
BeanFactory beanFactory = (BeanFactory) mockBeanFactory.getMock();
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class);
StubDataSource expectedDataSource = new StubDataSource();
mockBeanFactory.setReturnValue(expectedDataSource);
mockBeanFactory.replay();
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);
mockBeanFactory.verify();
}
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
MockControl mockBeanFactory = MockControl.createControl(BeanFactory.class);
final BeanFactory beanFactory = (BeanFactory) mockBeanFactory.getMock();
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class);
mockBeanFactory.setThrowable(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
mockBeanFactory.replay();
new AssertThrows(DataSourceLookupFailureException.class) {
public void test() throws Exception {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
lookup.getDataSource(DATASOURCE_BEAN_NAME);
}
}.runTest();
mockBeanFactory.verify();
}
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception {
new AssertThrows(IllegalStateException.class) {
public void test() throws Exception {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.getDataSource(DATASOURCE_BEAN_NAME);
}
}.runTest();
}
}

View File

@@ -1,61 +0,0 @@
/*
* 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 javax.naming.NamingException;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
*/
public final class JndiDataSourceLookupTests extends TestCase {
private static final String DATA_SOURCE_NAME = "Love is like a stove, burns you when it's hot";
public void testSunnyDay() throws Exception {
final DataSource expectedDataSource = new StubDataSource();
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
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);
}
public void testNoDataSourceAtJndiLocation() throws Exception {
new AssertThrows(DataSourceLookupFailureException.class) {
public void test() throws Exception {
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
assertEquals(DATA_SOURCE_NAME, jndiName);
throw new NamingException();
}
};
lookup.getDataSource(DATA_SOURCE_NAME);
}
}.runTest();
}
}

View File

@@ -1,103 +0,0 @@
/*
* 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 java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
*/
public final class MapDataSourceLookupTests extends TestCase {
private static final String DATA_SOURCE_NAME = "dataSource";
public void testGetDataSourcesReturnsUnmodifiableMap() throws Exception {
new AssertThrows(UnsupportedOperationException.class, "The Map returned from getDataSources() *must* be unmodifiable") {
public void test() throws Exception {
MapDataSourceLookup lookup = new MapDataSourceLookup(new HashMap());
Map dataSources = lookup.getDataSources();
dataSources.put("", "");
}
}.runTest();
}
public void testLookupSunnyDay() throws Exception {
Map dataSources = new HashMap();
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);
}
public void testSettingDataSourceMapToNullIsAnIdempotentOperation() throws Exception {
Map dataSources = new HashMap();
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);
}
public void testAddingDataSourcePermitsOverride() throws Exception {
Map dataSources = new HashMap();
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);
}
public void testGetDataSourceWhereSuppliedMapHasNonDataSourceTypeUnderSpecifiedKey() throws Exception {
new AssertThrows(ClassCastException.class) {
public void test() 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);
}
}.runTest();
}
public void testGetDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() throws Exception {
new AssertThrows(DataSourceLookupFailureException.class) {
public void test() throws Exception {
MapDataSourceLookup lookup = new MapDataSourceLookup();
lookup.getDataSource(DATA_SOURCE_NAME);
}
}.runTest();
}
}

View File

@@ -1,41 +0,0 @@
/*
* 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

@@ -1,34 +0,0 @@
/*
* Copyright 2002-2005 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 org.springframework.dao.DataAccessException;
/**
* @author Thomas Risberg
*/
public class CustomErrorCodeException extends DataAccessException {
public CustomErrorCodeException(String msg) {
super(msg);
}
public CustomErrorCodeException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -1,78 +0,0 @@
/*
* 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 java.sql.SQLDataException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLInvalidAuthorizationSpecException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLRecoverableException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTimeoutException;
import java.sql.SQLTransactionRollbackException;
import java.sql.SQLTransientConnectionException;
/**
* Class to generate Java 6 SQLException subclasses for testing purposes.
*
* @author Thomas Risberg
*/
public class SQLExceptionSubclassFactory {
public static SQLException newSQLDataException(String reason, String SQLState, int vendorCode) {
return new SQLDataException(reason, SQLState, vendorCode);
}
public static SQLException newSQLFeatureNotSupportedException(String reason, String SQLState, int vendorCode) {
return new SQLFeatureNotSupportedException(reason, SQLState, vendorCode);
}
public static SQLException newSQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode) {
return new SQLIntegrityConstraintViolationException(reason, SQLState, vendorCode);
}
public static SQLException newSQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode) {
return new SQLInvalidAuthorizationSpecException(reason, SQLState, vendorCode);
}
public static SQLException newSQLNonTransientConnectionException(String reason, String SQLState, int vendorCode) {
return new SQLNonTransientConnectionException(reason, SQLState, vendorCode);
}
public static SQLException newSQLSyntaxErrorException(String reason, String SQLState, int vendorCode) {
return new SQLSyntaxErrorException(reason, SQLState, vendorCode);
}
public static SQLException newSQLTransactionRollbackException(String reason, String SQLState, int vendorCode) {
return new SQLTransactionRollbackException(reason, SQLState, vendorCode);
}
public static SQLException newSQLTransientConnectionException(String reason, String SQLState, int vendorCode) {
return new SQLTransientConnectionException(reason, SQLState, vendorCode);
}
public static SQLException newSQLTimeoutException(String reason, String SQLState, int vendorCode) {
return new SQLTimeoutException(reason, SQLState, vendorCode);
}
public static SQLException newSQLRecoverableException(String reason, String SQLState, int vendorCode) {
return new SQLRecoverableException(reason, SQLState, vendorCode);
}
}

View File

@@ -1,88 +0,0 @@
/*
* 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 java.sql.SQLException;
import junit.framework.TestCase;
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;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class SQLStateSQLExceptionTranslatorTests extends TestCase {
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";
public void testTranslateNullException() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new SQLStateSQLExceptionTranslator().translate("", "", null);
}
}.runTest();
}
public void testTranslateBadSqlGrammar() throws Exception {
doTest("07", BadSqlGrammarException.class);
}
public void testTranslateDataIntegrityViolation() throws Exception {
doTest("23", DataIntegrityViolationException.class);
}
public void testTranslateDataAccessResourceFailure() throws Exception {
doTest("53", DataAccessResourceFailureException.class);
}
public void testTranslateTransientDataAccessResourceFailure() throws Exception {
doTest("S1", TransientDataAccessResourceException.class);
}
public void testTranslateConcurrencyFailure() throws Exception {
doTest("40", ConcurrencyFailureException.class);
}
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

@@ -1,24 +0,0 @@
<?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

@@ -1,14 +0,0 @@
<?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

@@ -1,38 +0,0 @@
<?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>