Replace EasyMock with Mockito in test sources

Issue: SPR-10126
This commit is contained in:
Phillip Webb
2012-12-19 14:45:29 -08:00
committed by Chris Beams
parent cbf6991d47
commit d66c733ef4
82 changed files with 4828 additions and 10460 deletions

View File

@@ -0,0 +1,67 @@
/*
* 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.build.test.hamcrest;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
* Additional hamcrest matchers.
*
* @author Phillip Webb
*/
public class Matchers {
/**
* Create a matcher that wrapps the specified matcher and tests against the
* {@link Throwable#getCause() cause} of an exception. If the item tested
* is {@code null} not a {@link Throwable} the wrapped matcher will be called
* with a {@code null} item.
*
* <p>Often useful when working with JUnit {@link ExpectedException}
* {@link Rule @Rule}s, for example:
* <pre>
* thrown.expect(DataAccessException.class);
* thrown.except(exceptionCause(isA(SQLException.class)));
* </pre>
*
* @param matcher the matcher to wrap (must not be null)
* @return a matcher that tests using the exception cause
*/
@SuppressWarnings("unchecked")
public static <T> Matcher<T> exceptionCause(final Matcher<T> matcher) {
return (Matcher<T>) new BaseMatcher<Object>() {
@Override
public boolean matches(Object item) {
Throwable cause = null;
if(item != null && item instanceof Throwable) {
cause = ((Throwable)item).getCause();
}
return matcher.matches(cause);
}
@Override
public void describeTo(Description description) {
description.appendText("exception cause ").appendDescriptionOf(matcher);
}
};
}
}

View File

@@ -1,87 +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;
@Override
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;
}
@Override
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

@@ -16,6 +16,12 @@
package org.springframework.jdbc.core;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -23,9 +29,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
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;
@@ -39,254 +42,16 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
*
* @author Thomas Risberg
*/
public abstract class AbstractRowMapperTests extends TestCase {
public abstract class AbstractRowMapperTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
protected MockControl conControl;
protected Connection con;
protected MockControl conControl2;
protected Connection con2;
protected MockControl conControl3;
protected Connection con3;
protected MockControl rsmdControl;
protected ResultSetMetaData rsmd;
protected MockControl rsControl;
protected ResultSet rs;
protected MockControl stmtControl;
protected Statement stmt;
protected JdbcTemplate jdbcTemplate;
protected MockControl rsmdControl2;
protected ResultSetMetaData rsmd2;
protected MockControl rsControl2;
protected ResultSet rs2;
protected MockControl stmtControl2;
protected Statement stmt2;
protected JdbcTemplate jdbcTemplate2;
protected MockControl rsmdControl3;
protected ResultSetMetaData rsmd3;
protected MockControl rsControl3;
protected ResultSet rs3;
protected MockControl stmtControl3;
protected Statement stmt3;
protected JdbcTemplate jdbcTemplate3;
@Override
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();
conControl2 = MockControl.createControl(Connection.class);
con2 = (Connection) conControl2.getMock();
con2.isClosed();
conControl2.setDefaultReturnValue(false);
rsmdControl2 = MockControl.createControl(ResultSetMetaData.class);
rsmd2 = (ResultSetMetaData)rsmdControl2.getMock();
rsmd2.getColumnCount();
rsmdControl2.setReturnValue(4, 2);
rsmd2.getColumnLabel(1);
rsmdControl2.setReturnValue("name", 2);
rsmd2.getColumnLabel(2);
rsmdControl2.setReturnValue("age", 2);
rsmd2.getColumnLabel(3);
rsmdControl2.setReturnValue("birth_date", 1);
rsmd2.getColumnLabel(4);
rsmdControl2.setReturnValue("balance", 1);
rsmdControl2.replay();
rsControl2 = MockControl.createControl(ResultSet.class);
rs2 = (ResultSet) rsControl2.getMock();
rs2.getMetaData();
rsControl2.setReturnValue(rsmd2, 2);
rs2.next();
rsControl2.setReturnValue(true, 2);
rs2.getString(1);
rsControl2.setReturnValue("Bubba", 2);
rs2.wasNull();
rsControl2.setReturnValue(true, 2);
rs2.getLong(2);
rsControl2.setReturnValue(0, 2);
rs2.getTimestamp(3);
rsControl2.setReturnValue(new Timestamp(1221222L), 1);
rs2.getBigDecimal(4);
rsControl2.setReturnValue(new BigDecimal("1234.56"), 1);
rs2.next();
rsControl2.setReturnValue(false, 1);
rs2.close();
rsControl2.setVoidCallable(2);
rsControl2.replay();
stmtControl2 = MockControl.createControl(Statement.class);
stmt2 = (Statement) stmtControl2.getMock();
con2.createStatement();
conControl2.setReturnValue(stmt2, 2);
stmt2.executeQuery("select name, null as age, birth_date, balance from people");
stmtControl2.setReturnValue(rs2, 2);
if (debugEnabled) {
stmt2.getWarnings();
stmtControl2.setReturnValue(null, 2);
}
stmt2.close();
stmtControl2.setVoidCallable(2);
conControl2.replay();
stmtControl2.replay();
conControl3 = MockControl.createControl(Connection.class);
con3 = (Connection) conControl3.getMock();
con3.isClosed();
conControl3.setDefaultReturnValue(false);
rsmdControl3 = MockControl.createControl(ResultSetMetaData.class);
rsmd3 = (ResultSetMetaData)rsmdControl3.getMock();
rsmd3.getColumnCount();
rsmdControl3.setReturnValue(4, 1);
rsmd3.getColumnLabel(1);
rsmdControl3.setReturnValue("Last Name", 1);
rsmd3.getColumnLabel(2);
rsmdControl3.setReturnValue("age", 1);
rsmd3.getColumnLabel(3);
rsmdControl3.setReturnValue("birth_date", 1);
rsmd3.getColumnLabel(4);
rsmdControl3.setReturnValue("balance", 1);
rsmdControl3.replay();
rsControl3 = MockControl.createControl(ResultSet.class);
rs3 = (ResultSet) rsControl3.getMock();
rs3.getMetaData();
rsControl3.setReturnValue(rsmd3, 1);
rs3.next();
rsControl3.setReturnValue(true, 1);
rs3.getString(1);
rsControl3.setReturnValue("Gagarin", 1);
rs3.wasNull();
rsControl3.setReturnValue(false, 1);
rs3.getLong(2);
rsControl3.setReturnValue(22, 1);
rs3.getTimestamp(3);
rsControl3.setReturnValue(new Timestamp(1221222L), 1);
rs3.getBigDecimal(4);
rsControl3.setReturnValue(new BigDecimal("1234.56"), 1);
rs3.next();
rsControl3.setReturnValue(false, 1);
rs3.close();
rsControl3.setVoidCallable(1);
rsControl3.replay();
stmtControl3 = MockControl.createControl(Statement.class);
stmt3 = (Statement) stmtControl3.getMock();
con3.createStatement();
conControl3.setReturnValue(stmt3, 1);
stmt3.executeQuery("select last_name as \"Last Name\", age, birth_date, balance from people");
stmtControl3.setReturnValue(rs3, 1);
if (debugEnabled) {
stmt3.getWarnings();
stmtControl3.setReturnValue(null, 1);
}
stmt3.close();
stmtControl3.setVoidCallable(1);
conControl3.replay();
stmtControl3.replay();
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
jdbcTemplate2 = new JdbcTemplate();
jdbcTemplate2.setDataSource(new SingleConnectionDataSource(con2, false));
jdbcTemplate2.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate2.afterPropertiesSet();
jdbcTemplate3 = new JdbcTemplate();
jdbcTemplate3.setDataSource(new SingleConnectionDataSource(con3, false));
jdbcTemplate3.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate3.afterPropertiesSet();
}
protected void verifyPerson(Person bean) {
verify();
protected void verifyPerson(Person bean) throws Exception {
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 verifyPersonWithZeroAge(Person bean) {
conControl2.verify();
rsControl2.verify();
rsmdControl2.verify();
stmtControl2.verify();
assertEquals("Bubba", bean.getName());
assertEquals(0L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
protected void verifyConcretePerson(ConcretePerson bean) {
verify();
protected void verifyConcretePerson(ConcretePerson bean) throws Exception {
assertEquals("Bubba", bean.getName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
@@ -294,21 +59,68 @@ public abstract class AbstractRowMapperTests extends TestCase {
}
protected void verifySpacePerson(SpacePerson bean) {
conControl3.verify();
rsControl3.verify();
rsmdControl3.verify();
stmtControl3.verify();
assertEquals("Gagarin", bean.getLastName());
assertEquals("Bubba", bean.getLastName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirthDate());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
private void verify() {
conControl.verify();
rsControl.verify();
rsmdControl.verify();
stmtControl.verify();
}
protected static enum MockType {ONE,TWO,THREE};
protected static class Mock {
private Connection connection;
private ResultSetMetaData resultSetMetaData;
private ResultSet resultSet;
private Statement statement;
private JdbcTemplate jdbcTemplate;
public Mock() throws Exception {
this(MockType.ONE);
}
public Mock(MockType type)
throws Exception {
connection = mock(Connection.class);
statement = mock(Statement.class);
resultSet = mock(ResultSet.class);
resultSetMetaData = mock(ResultSetMetaData.class);
given(connection.createStatement()).willReturn(statement);
given(statement.executeQuery(anyString())).willReturn(resultSet);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getString(1)).willReturn("Bubba");
given(resultSet.getLong(2)).willReturn(22L);
given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);
given(resultSetMetaData.getColumnCount()).willReturn(4);
given(resultSetMetaData.getColumnLabel(1)).willReturn(
type == MockType.THREE ? "Last Name" : "name");
given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void verifyClosed() throws Exception {
verify(resultSet).close();
verify(statement).close();
}
}
}

View File

@@ -1,112 +0,0 @@
package org.springframework.jdbc.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
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.jdbc.core.namedparam.SqlParameterSource;
/**
* @author Thomas Risberg
*/
public abstract class BatchUpdateTestHelper {
public static void prepareBatchUpdateMocks(String sqlToUse, Object ids, int[] sqlTypes,
int[] rowsAffected,
MockControl ctrlDataSource, DataSource mockDataSource, MockControl ctrlConnection, Connection mockConnection,
MockControl ctrlPreparedStatement,
PreparedStatement mockPreparedStatement, MockControl ctrlDatabaseMetaData, DatabaseMetaData mockDatabaseMetaData)
throws SQLException {
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
mockPreparedStatement.getConnection();
ctrlPreparedStatement.setReturnValue(mockConnection);
int idLength = 0;
if (ids instanceof SqlParameterSource[]) {
idLength = ((SqlParameterSource[])ids).length;
}
else if (ids instanceof Map[]) {
idLength = ((Map[])ids).length;
}
else {
idLength = ((List)ids).size();
}
for (int i = 0; i < idLength; i++) {
if (ids instanceof SqlParameterSource[]) {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"), sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"));
}
}
else if (ids instanceof Map[]) {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"), sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"));
}
}
else {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0], sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0]);
}
}
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
}
mockPreparedStatement.executeBatch();
ctrlPreparedStatement.setReturnValue(rowsAffected);
if (LogFactory.getLog(JdbcTemplate.class).isDebugEnabled()) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MySQL");
mockDatabaseMetaData.supportsBatchUpdates();
ctrlDatabaseMetaData.setReturnValue(true);
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
mockConnection.getMetaData();
ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
}
public static void replayBatchUpdateMocks(MockControl ctrlDataSource,
MockControl ctrlConnection,
MockControl ctrlPreparedStatement,
MockControl ctrlDatabaseMetaData) {
ctrlPreparedStatement.replay();
ctrlDatabaseMetaData.replay();
ctrlDataSource.replay();
ctrlConnection.replay();
}
public static void verifyBatchUpdateMocks(MockControl ctrlPreparedStatement, MockControl ctrlDatabaseMetaData) {
ctrlPreparedStatement.verify();
ctrlDatabaseMetaData.verify();
}
}

View File

@@ -16,15 +16,19 @@
package org.springframework.jdbc.core;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.ExtendedPerson;
import org.springframework.jdbc.core.test.Person;
import org.springframework.jdbc.core.test.SpacePerson;
import org.springframework.beans.TypeMismatchException;
/**
* @author Thomas Risberg
@@ -32,89 +36,94 @@ import org.springframework.beans.TypeMismatchException;
*/
public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
public void testOverridingClassDefinedForMapping() {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testOverridingDifferentClassDefinedForMapping() {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
try {
mapper.setMappedClass(Long.class);
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
}
try {
mapper.setMappedClass(Person.class);
}
catch (InvalidDataAccessApiUsageException ex) {
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
}
thrown.expect(InvalidDataAccessApiUsageException.class);
mapper.setMappedClass(Long.class);
}
public void testStaticQueryWithRowMapper() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(Person.class));
assertEquals(1, result.size());
Person bean = (Person) result.get(0);
verifyPerson(bean);
@Test
public void testOverridingSameClassDefinedForMapping() {
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
mapper.setMappedClass(Person.class);
}
public void testMappingWithInheritance() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ConcretePerson.class));
@Test
public void testStaticQueryWithRowMapper() throws Exception {
Mock mock = new Mock();
List<Person> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<Person>(Person.class));
assertEquals(1, result.size());
ConcretePerson bean = (ConcretePerson) result.get(0);
verifyPerson(result.get(0));
mock.verifyClosed();
}
@Test
public void testMappingWithInheritance() throws Exception {
Mock mock = new Mock();
List<ConcretePerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ConcretePerson>(ConcretePerson.class));
assertEquals(1, result.size());
verifyConcretePerson(result.get(0));
mock.verifyClosed();
}
@Test
public void testMappingWithNoUnpopulatedFieldsFound() throws Exception {
Mock mock = new Mock();
List<ConcretePerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ConcretePerson>(ConcretePerson.class, true));
assertEquals(1, result.size());
verifyConcretePerson(result.get(0));
mock.verifyClosed();
}
@Test
public void testMappingWithUnpopulatedFieldsNotChecked() throws Exception {
Mock mock = new Mock();
List<ExtendedPerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ExtendedPerson>(ExtendedPerson.class));
assertEquals(1, result.size());
ExtendedPerson bean = result.get(0);
verifyConcretePerson(bean);
mock.verifyClosed();
}
public void testMappingWithNoUnpopulatedFieldsFound() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ConcretePerson.class, true));
@Test
public void testMappingWithUnpopulatedFieldsNotAccepted() throws Exception {
Mock mock = new Mock();
thrown.expect(InvalidDataAccessApiUsageException.class);
mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ExtendedPerson>(ExtendedPerson.class, true));
}
@Test
public void testMappingNullValue() throws Exception {
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
Mock mock = new Mock(MockType.TWO);
thrown.expect(TypeMismatchException.class);
mock.getJdbcTemplate().query(
"select name, null as age, birth_date, balance from people", mapper);
}
@Test
public void testQueryWithSpaceInColumnName() throws Exception {
Mock mock = new Mock(MockType.THREE);
List<SpacePerson> result = mock.getJdbcTemplate().query(
"select last_name as \"Last Name\", age, birth_date, balance from people",
new BeanPropertyRowMapper<SpacePerson>(SpacePerson.class));
assertEquals(1, result.size());
ConcretePerson bean = (ConcretePerson) result.get(0);
verifyConcretePerson(bean);
verifySpacePerson(result.get(0));
mock.verifyClosed();
}
public void testMappingWithUnpopulatedFieldsNotChecked() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ExtendedPerson.class));
assertEquals(1, result.size());
ExtendedPerson bean = (ExtendedPerson) result.get(0);
verifyConcretePerson(bean);
}
public void testMappingWithUnpopulatedFieldsNotAccepted() throws SQLException {
try {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ExtendedPerson.class, true));
fail("Should have thrown InvalidDataAccessApiUsageException because of missing field");
}
catch (InvalidDataAccessApiUsageException ex) {
// expected
}
}
public void testMappingNullValue() throws SQLException {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
try {
List result1 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
mapper);
fail("Should have thrown TypeMismatchException because of null value");
}
catch (TypeMismatchException ex) {
// expected
}
mapper.setPrimitivesDefaultedForNullValue(true);
List result2 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
mapper);
assertEquals(1, result2.size());
Person bean = (Person) result2.get(0);
verifyPersonWithZeroAge(bean);
}
public void testQueryWithSpaceInColumnName() throws SQLException {
List result = jdbcTemplate3.query("select last_name as \"Last Name\", age, birth_date, balance from people",
new BeanPropertyRowMapper(SpacePerson.class));
assertEquals(1, result.size());
SpacePerson bean = (SpacePerson) result.get(0);
verifySpacePerson(bean);
}
}

View File

@@ -16,6 +16,11 @@
package org.springframework.jdbc.core;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -25,9 +30,10 @@ import java.sql.Types;
import java.util.List;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
@@ -38,213 +44,104 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
*/
public class RowMapperTests extends TestCase {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private Connection connection;
private Statement statement;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private MockControl conControl;
private Connection con;
private MockControl rsControl;
private ResultSet rs;
private JdbcTemplate jdbcTemplate;
private List result;
private JdbcTemplate template;
@Override
protected void setUp() throws SQLException {
conControl = MockControl.createControl(Connection.class);
con = (Connection) conControl.getMock();
con.isClosed();
conControl.setDefaultReturnValue(false);
private List<TestBean> result;
rsControl = MockControl.createControl(ResultSet.class);
rs = (ResultSet) rsControl.getMock();
rs.next();
rsControl.setReturnValue(true, 1);
rs.getString(1);
rsControl.setReturnValue("tb1", 1);
rs.getInt(2);
rsControl.setReturnValue(1, 1);
rs.next();
rsControl.setReturnValue(true, 1);
rs.getString(1);
rsControl.setReturnValue("tb2", 1);
rs.getInt(2);
rsControl.setReturnValue(2, 1);
rs.next();
rsControl.setReturnValue(false, 1);
rs.close();
rsControl.setVoidCallable(1);
rsControl.replay();
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
@Before
public void setUp() throws SQLException {
connection = mock(Connection.class);
statement = mock(Statement.class);
preparedStatement = mock(PreparedStatement.class);
resultSet = mock(ResultSet.class);
given(connection.createStatement()).willReturn(statement);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(statement.executeQuery(anyString())).willReturn(resultSet);
given(preparedStatement.executeQuery()).willReturn(resultSet);
given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getString(1)).willReturn("tb1", "tb2");
given(resultSet.getInt(2)).willReturn(1, 2);
template = new JdbcTemplate();
template.setDataSource(new SingleConnectionDataSource(connection, false));
template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
template.afterPropertiesSet();
}
public void testStaticQueryWithRowMapper() throws SQLException {
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
con.createStatement();
conControl.setReturnValue(stmt, 1);
stmt.executeQuery("some SQL");
stmtControl.setReturnValue(rs, 1);
if (debugEnabled) {
stmt.getWarnings();
stmtControl.setReturnValue(null, 1);
}
stmt.close();
stmtControl.setVoidCallable(1);
conControl.replay();
stmtControl.replay();
result = jdbcTemplate.query("some SQL", new TestRowMapper());
stmtControl.verify();
verify();
@After
public void verifyClosed() throws Exception {
verify(resultSet).close();
verify(connection).close();
}
public void testPreparedStatementCreatorWithRowMapper() throws SQLException {
MockControl psControl = MockControl.createControl(PreparedStatement.class);
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.executeQuery();
psControl.setReturnValue(rs, 1);
if (debugEnabled) {
ps.getWarnings();
psControl.setReturnValue(null, 1);
}
ps.close();
psControl.setVoidCallable(1);
conControl.replay();
psControl.replay();
result = jdbcTemplate.query(
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
return ps;
}
}, new TestRowMapper());
psControl.verify();
verify();
}
public void testPreparedStatementSetterWithRowMapper() throws SQLException {
MockControl psControl = MockControl.createControl(PreparedStatement.class);
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
con.prepareStatement("some SQL");
conControl.setReturnValue(ps, 1);
ps.setString(1, "test");
psControl.setVoidCallable(1);
ps.executeQuery();
psControl.setReturnValue(rs, 1);
if (debugEnabled) {
ps.getWarnings();
psControl.setReturnValue(null, 1);
}
ps.close();
psControl.setVoidCallable(1);
conControl.replay();
psControl.replay();
result = jdbcTemplate.query(
"some SQL",
new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, "test");
}
}, new TestRowMapper());
psControl.verify();
verify();
}
public void testQueryWithArgsAndRowMapper() throws SQLException {
MockControl psControl = MockControl.createControl(PreparedStatement.class);
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
con.prepareStatement("some SQL");
conControl.setReturnValue(ps, 1);
ps.setString(1, "test1");
ps.setString(2, "test2");
psControl.setVoidCallable(1);
ps.executeQuery();
psControl.setReturnValue(rs, 1);
if (debugEnabled) {
ps.getWarnings();
psControl.setReturnValue(null, 1);
}
ps.close();
psControl.setVoidCallable(1);
conControl.replay();
psControl.replay();
result = jdbcTemplate.query(
"some SQL",
new Object[] {"test1", "test2"},
new TestRowMapper());
psControl.verify();
verify();
}
public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException {
MockControl psControl = MockControl.createControl(PreparedStatement.class);
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
con.prepareStatement("some SQL");
conControl.setReturnValue(ps, 1);
ps.setString(1, "test1");
ps.setString(2, "test2");
psControl.setVoidCallable(1);
ps.executeQuery();
psControl.setReturnValue(rs, 1);
if (debugEnabled) {
ps.getWarnings();
psControl.setReturnValue(null, 1);
}
ps.close();
psControl.setVoidCallable(1);
conControl.replay();
psControl.replay();
result = jdbcTemplate.query(
"some SQL",
new Object[] {"test1", "test2"},
new int[] {Types.VARCHAR, Types.VARCHAR},
new TestRowMapper());
psControl.verify();
verify();
}
protected void verify() {
conControl.verify();
rsControl.verify();
@After
public void verifyResults() {
assertTrue(result != null);
assertEquals(2, result.size());
TestBean tb1 = (TestBean) result.get(0);
TestBean tb2 = (TestBean) result.get(1);
assertEquals("tb1", tb1.getName());
assertEquals(1, tb1.getAge());
assertEquals("tb2", tb2.getName());
assertEquals(2, tb2.getAge());
assertEquals("tb1", result.get(0).getName());
assertEquals("tb2", result.get(1).getName());
assertEquals(1, result.get(0).getAge());
assertEquals(2, result.get(1).getAge());
}
@Test
public void testStaticQueryWithRowMapper() throws SQLException {
result = template.query("some SQL", new TestRowMapper());
verify(statement).close();
}
private static class TestRowMapper implements RowMapper {
@Test
public void testPreparedStatementCreatorWithRowMapper() throws SQLException {
result = template.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
return preparedStatement;
}
}, new TestRowMapper());
verify(preparedStatement).close();
}
@Test
public void testPreparedStatementSetterWithRowMapper() throws SQLException {
result = template.query("some SQL", new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, "test");
}
}, new TestRowMapper());
verify(preparedStatement).setString(1, "test");
verify(preparedStatement).close();
}
@Test
public void testQueryWithArgsAndRowMapper() throws SQLException {
result = template.query("some SQL",
new Object[] { "test1", "test2" },
new TestRowMapper());
preparedStatement.setString(1, "test1");
preparedStatement.setString(2, "test2");
preparedStatement.close();
}
@Test
public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException {
result = template.query("some SQL",
new Object[] { "test1", "test2" },
new int[] { Types.VARCHAR, Types.VARCHAR },
new TestRowMapper());
verify(preparedStatement).setString(1, "test1");
verify(preparedStatement).setString(2, "test2");
verify(preparedStatement).close();
}
private static class TestRowMapper implements RowMapper<TestBean> {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
public TestBean mapRow(ResultSet rs, int rowNum) throws SQLException {
return new TestBean(rs.getString(1), rs.getInt(2));
}
}

View File

@@ -16,6 +16,10 @@
package org.springframework.jdbc.core;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
@@ -23,203 +27,156 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.GregorianCalendar;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Before;
import org.junit.Test;
/**
* @author Juergen Hoeller
* @since 31.08.2004
*/
public class StatementCreatorUtilsTests extends TestCase {
public class StatementCreatorUtilsTests {
private MockControl psControl;
private PreparedStatement ps;
private PreparedStatement preparedStatement;
@Override
protected void setUp() {
psControl = MockControl.createControl(PreparedStatement.class);
ps = (PreparedStatement) psControl.getMock();
@Before
public void setUp() {
preparedStatement = mock(PreparedStatement.class);
}
@Override
protected void tearDown() {
psControl.verify();
@Test public void testSetParameterValueWithNullAndType() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, null);
verify(preparedStatement).setNull(1, Types.VARCHAR);
}
public void testSetParameterValueWithNullAndType() throws SQLException {
ps.setNull(1, Types.VARCHAR);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, null);
@Test public void testSetParameterValueWithNullAndTypeName() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, "mytype", null);
verify(preparedStatement).setNull(1, Types.VARCHAR, "mytype");
}
public void testSetParameterValueWithNullAndTypeName() throws SQLException {
ps.setNull(1, Types.VARCHAR, "mytype");
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, "mytype", null);
}
public void testSetParameterValueWithNullAndUnknownType() throws SQLException {
ps.setNull(1, Types.NULL);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
@Test public void testSetParameterValueWithNullAndUnknownType() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
verify(preparedStatement).setNull(1, Types.NULL);
}
@Test
public void testSetParameterValueWithNullAndUnknownTypeOnInformix() throws SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
ps.getConnection();
psControl.setReturnValue(con, 1);
con.getMetaData();
conControl.setReturnValue(metaData, 1);
metaData.getDatabaseProductName();
metaDataControl.setReturnValue("Informix Dynamic Server");
metaData.getDriverName();
metaDataControl.setReturnValue("Informix Driver");
ps.setObject(1, null);
psControl.setVoidCallable(1);
psControl.replay();
conControl.replay();
metaDataControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
conControl.verify();
metaDataControl.verify();
Connection con = mock(Connection.class);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
given(preparedStatement.getConnection()).willReturn(con);
given(con.getMetaData()).willReturn(metaData);
given(metaData.getDatabaseProductName()).willReturn("Informix Dynamic Server");
given(metaData.getDriverName()).willReturn("Informix Driver");
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
verify(metaData).getDatabaseProductName();
verify(metaData).getDriverName();
verify(preparedStatement).setObject(1, null);
}
public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
ps.getConnection();
psControl.setReturnValue(con, 1);
con.getMetaData();
conControl.setReturnValue(metaData, 1);
metaData.getDatabaseProductName();
metaDataControl.setReturnValue("Apache Derby");
metaData.getDriverName();
metaDataControl.setReturnValue("Apache Derby Embedded Driver");
ps.setNull(1, Types.VARCHAR);
psControl.setVoidCallable(1);
psControl.replay();
conControl.replay();
metaDataControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
conControl.verify();
metaDataControl.verify();
@Test public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
Connection con = mock(Connection.class);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
given(preparedStatement.getConnection()).willReturn(con);
given(con.getMetaData()).willReturn(metaData);
given(metaData.getDatabaseProductName()).willReturn("Apache Derby");
given(metaData.getDriverName()).willReturn("Apache Derby Embedded Driver");
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
verify(metaData).getDatabaseProductName();
verify(metaData).getDriverName();
verify(preparedStatement).setNull(1, Types.VARCHAR);
}
@Test
public void testSetParameterValueWithString() throws SQLException {
ps.setString(1, "test");
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, "test");
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, "test");
verify(preparedStatement).setString(1, "test");
}
@Test
public void testSetParameterValueWithStringAndSpecialType() throws SQLException {
ps.setObject(1, "test", Types.CHAR);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.CHAR, null, "test");
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.CHAR, null, "test");
verify(preparedStatement).setObject(1, "test", Types.CHAR);
}
public void testSetParameterValueWithStringAndUnknownType() throws SQLException {
ps.setString(1, "test");
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, "test");
@Test public void testSetParameterValueWithStringAndUnknownType() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, "test");
verify(preparedStatement).setString(1, "test");
}
@Test
public void testSetParameterValueWithSqlDate() throws SQLException {
java.sql.Date date = new java.sql.Date(1000);
ps.setDate(1, date);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
verify(preparedStatement).setDate(1, date);
}
@Test
public void testSetParameterValueWithDateAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000);
ps.setDate(1, new java.sql.Date(1000));
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
verify(preparedStatement).setDate(1, new java.sql.Date(1000));
}
@Test
public void testSetParameterValueWithDateAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar();
ps.setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, cal);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, cal);
verify(preparedStatement).setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
}
@Test
public void testSetParameterValueWithSqlTime() throws SQLException {
java.sql.Time time = new java.sql.Time(1000);
ps.setTime(1, time);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, time);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, time);
verify(preparedStatement).setTime(1, time);
}
@Test
public void testSetParameterValueWithTimeAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000);
ps.setTime(1, new java.sql.Time(1000));
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, date);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, date);
verify(preparedStatement).setTime(1, new java.sql.Time(1000));
}
@Test
public void testSetParameterValueWithTimeAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar();
ps.setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, cal);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, cal);
verify(preparedStatement).setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
}
@Test
public void testSetParameterValueWithSqlTimestamp() throws SQLException {
java.sql.Timestamp timestamp = new java.sql.Timestamp(1000);
ps.setTimestamp(1, timestamp);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, timestamp);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, timestamp);
verify(preparedStatement).setTimestamp(1, timestamp);
}
@Test
public void testSetParameterValueWithTimestampAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000);
ps.setTimestamp(1, new java.sql.Timestamp(1000));
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, date);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, date);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
}
@Test
public void testSetParameterValueWithTimestampAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar();
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, cal);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, cal);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
}
@Test
public void testSetParameterValueWithDateAndUnknownType() throws SQLException {
java.util.Date date = new java.util.Date(1000);
ps.setTimestamp(1, new java.sql.Timestamp(1000));
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
}
@Test
public void testSetParameterValueWithCalendarAndUnknownType() throws SQLException {
java.util.Calendar cal = new GregorianCalendar();
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
psControl.setVoidCallable(1);
psControl.replay();
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, cal);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, cal);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
}
}

View File

@@ -16,41 +16,49 @@
package org.springframework.jdbc.core.namedparam;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import javax.sql.DataSource;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
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.JdbcTemplate;
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.jdbc.core.BatchUpdateTestHelper;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
public class NamedParameterJdbcTemplateTests {
private static final String SELECT_NAMED_PARAMETERS =
"select id, forename from custmr where id = :id and country = :country";
@@ -64,255 +72,166 @@ public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockControl ctrlPreparedStatement;
private PreparedStatement mockPreparedStatement;
private MockControl ctrlResultSet;
private ResultSet mockResultSet;
private Connection connection;
private DataSource dataSource;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private DatabaseMetaData databaseMetaData;
private Map<String, Object> params = new HashMap<String, Object>();
private NamedParameterJdbcTemplate namedParameterTemplate;
@Override
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();
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
dataSource = mock(DataSource.class);
preparedStatement = mock(PreparedStatement.class);
resultSet = mock(ResultSet.class);
namedParameterTemplate = new NamedParameterJdbcTemplate(dataSource);
databaseMetaData = mock(DatabaseMetaData.class);
given(dataSource.getConnection()).willReturn(connection);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(preparedStatement.getConnection()).willReturn(connection);
given(preparedStatement.executeQuery()).willReturn(resultSet);
given(databaseMetaData.getDatabaseProductName()).willReturn("MySQL");
given(databaseMetaData.supportsBatchUpdates()).willReturn(true);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
if (shouldVerify()) {
ctrlPreparedStatement.verify();
ctrlResultSet.verify();
}
}
@Override
protected void replay() {
super.replay();
ctrlPreparedStatement.replay();
ctrlResultSet.replay();
}
@Test
public void testNullDataSourceProvidedToCtor() throws Exception {
try {
new NamedParameterJdbcTemplate((DataSource) null);
fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ex) { /* expected */ }
thrown.expect(IllegalArgumentException.class);
new NamedParameterJdbcTemplate((DataSource) null);
}
@Test
public void testNullJdbcTemplateProvidedToCtor() throws Exception {
try {
new NamedParameterJdbcTemplate((JdbcOperations) null);
fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ex) { /* expected */ }
thrown.expect(IllegalArgumentException.class);
new NamedParameterJdbcTemplate((JdbcOperations) null);
}
@Test
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();
given(preparedStatement.executeUpdate()).willReturn(1);
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
params.put("perfId", 1);
params.put("priceId", 1);
Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
new PreparedStatementCallback<Object>() {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException {
assertEquals(preparedStatement, ps);
ps.executeUpdate();
return "result";
}
});
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() {
@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
assertEquals(mockPreparedStatement, ps);
ps.executeUpdate();
return "result";
}
}));
assertEquals("result", result);
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1);
verify(preparedStatement).setObject(2, 1);
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(preparedStatement.executeUpdate()).willReturn(1);
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
new PreparedStatementCallback<Object>() {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException {
assertEquals(preparedStatement, ps);
ps.executeUpdate();
return "result";
}
});
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() {
@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
assertEquals(mockPreparedStatement, ps);
ps.executeUpdate();
return "result";
}
}));
assertEquals("result", result);
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setObject(2, 1, Types.INTEGER);
verify(preparedStatement).close();
verify(connection).close();
}
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();
@Test public void testUpdate() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1);
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
params.put("perfId", 1);
params.put("priceId", 1);
int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);
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);
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1);
verify(preparedStatement).setObject(2, 1);
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(preparedStatement.executeUpdate()).willReturn(1);
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);
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);
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setObject(2, 1, Types.INTEGER);
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod");
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("id", new SqlParameterValue(Types.DECIMAL, 1));
params.put("country", "UK");
Customer cust = (Customer) jt.query(SELECT_NAMED_PARAMETERS, params, new ResultSetExtractor() {
@Override
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;
}
});
Customer cust = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
new ResultSetExtractor<Customer>() {
@Override
public Customer 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"));
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setString(2, "UK");
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod");
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("id", new SqlParameterValue(Types.DECIMAL, 1));
params.put("country", "UK");
final List customers = new LinkedList();
jt.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
final List<Customer> customers = new LinkedList<Customer>();
namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
Customer cust = new Customer();
@@ -321,218 +240,148 @@ public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
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"));
assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setString(2, "UK");
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod");
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("id", new SqlParameterValue(Types.DECIMAL, 1));
params.put("country", "UK");
List customers = jt.query(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
@Override
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;
}
});
List<Customer> customers = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
new RowMapper<Customer>() {
@Override
public Customer 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"));
assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setString(2, "UK");
verify(preparedStatement).close();
verify(connection).close();
}
@Test
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();
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod");
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("id", new SqlParameterValue(Types.DECIMAL, 1));
params.put("country", "UK");
Customer cust = (Customer) jt.queryForObject(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
@Override
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;
}
});
Customer cust = namedParameterTemplate.queryForObject(SELECT_NAMED_PARAMETERS, params,
new RowMapper<Customer>() {
@Override
public Customer 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"));
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
verify(preparedStatement).setString(2, "UK");
verify(preparedStatement).close();
verify(connection).close();
}
@Test
public void testBatchUpdateWithPlainMap() throws Exception {
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
final Map[] ids = new Map[2];
@SuppressWarnings("unchecked")
final Map<String, Integer>[] ids = new Map[2];
ids[0] = Collections.singletonMap("id", 100);
ids[1] = Collections.singletonMap("id", 200);
final int[] rowsAffected = new int[] { 1, 2 };
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
given(connection.getMetaData()).willReturn(databaseMetaData);
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
JdbcTemplate template = new JdbcTemplate(dataSource, false);
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
verify(preparedStatement).setObject(1, 100);
verify(preparedStatement).setObject(1, 200);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement, atLeastOnce()).close();
verify(connection, atLeastOnce()).close();
}
@Test
public void testBatchUpdateWithSqlParameterSource() throws Exception {
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 ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
given(connection.getMetaData()).willReturn(databaseMetaData);
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
JdbcTemplate template = new JdbcTemplate(dataSource, false);
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
verify(preparedStatement).setObject(1, 100);
verify(preparedStatement).setObject(1, 200);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement, atLeastOnce()).close();
verify(connection, atLeastOnce()).close();
}
@Test
public void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception {
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().addValue("id", 100, Types.NUMERIC);
ids[1] = new MapSqlParameterSource().addValue("id", 200, Types.NUMERIC);
final int[] sqlTypes = new int[] {Types.NUMERIC};
final int[] rowsAffected = new int[] { 1, 2 };
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
given(connection.getMetaData()).willReturn(databaseMetaData);
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
JdbcTemplate template = new JdbcTemplate(dataSource, false);
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
verify(preparedStatement).setObject(1, 100, Types.NUMERIC);
verify(preparedStatement).setObject(1, 200, Types.NUMERIC);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement, atLeastOnce()).close();
verify(connection, atLeastOnce()).close();
}
}

View File

@@ -16,6 +16,14 @@
package org.springframework.jdbc.core.namedparam;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@ -27,576 +35,261 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.easymock.MockControl;
import javax.sql.DataSource;
import org.springframework.jdbc.AbstractJdbcTests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.RowMapper;
/**
* @author Thomas Risberg
* @author Phillip Webb
*/
public class NamedParameterQueryTests extends AbstractJdbcTests {
public class NamedParameterQueryTests {
private MockControl ctrlPreparedStatement;
private PreparedStatement mockPreparedStatement;
private MockControl ctrlResultSet;
private ResultSet mockResultSet;
private MockControl ctrlResultSetMetaData;
private ResultSetMetaData mockResultSetMetaData;
private DataSource dataSource;
@Override
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();
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private ResultSetMetaData resultSetMetaData;
private NamedParameterJdbcTemplate template;
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
dataSource = mock(DataSource.class);
preparedStatement = mock(PreparedStatement.class);
resultSet = mock(ResultSet.class);
resultSetMetaData = mock(ResultSetMetaData.class);
template = new NamedParameterJdbcTemplate(dataSource);
given(dataSource.getConnection()).willReturn(connection);
given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("age");
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(preparedStatement.executeQuery()).willReturn(resultSet);
}
@Override
protected void replay() {
super.replay();
ctrlPreparedStatement.replay();
ctrlResultSet.replay();
ctrlResultSetMetaData.replay();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
if (false && shouldVerify()) {
ctrlPreparedStatement.verify();
ctrlResultSet.verify();
ctrlResultSetMetaData.verify();
}
@After
public void verifyClose() throws Exception {
verify(preparedStatement).close();
verify(resultSet).close();
verify(connection).close();
}
@Test
public void testQueryForListWithParamMap() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1, 2);
mockResultSetMetaData.getColumnLabel(1);
ctrlResultSetMetaData.setReturnValue("age", 2);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData, 2);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getObject(1);
ctrlResultSet.setReturnValue(new Integer(11));
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getObject(1);
ctrlResultSet.setReturnValue(new Integer(12));
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getObject(1)).willReturn(11, 12);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
List<Map<String, Object>> li = template.queryForList(
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
List li = template.queryForList(sql, parms);
assertEquals("All rows returned", 2, li.size());
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
assertEquals("Second row is Integer", 12, ((Integer)((Map)li.get(1)).get("age")).intValue());
assertEquals("First row is Integer", 11,
((Integer) ((Map) li.get(0)).get("age")).intValue());
assertEquals("Second row is Integer", 12,
((Integer) ((Map) li.get(1)).get("age")).intValue());
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForListWithParamMapAndEmptyResult() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
ctrlResultSet = MockControl.createControl(ResultSet.class);
mockResultSet = (ResultSet) ctrlResultSet.getMock();
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.next()).willReturn(false);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
List<Map<String, Object>> li = template.queryForList(
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
List li = template.queryForList(sql, parms);
assertEquals("All rows returned", 0, li.size());
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForListWithParamMapAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSetMetaData.getColumnLabel(1);
ctrlResultSetMetaData.setReturnValue("age", 1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getObject(1);
ctrlResultSet.setReturnValue(new Integer(11));
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
List<Map<String, Object>> li = template.queryForList(
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
List li = template.queryForList(sql, parms);
assertEquals("All rows returned", 1, li.size());
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
assertEquals("First row is Integer", 11,
((Integer) ((Map) li.get(0)).get("age")).intValue());
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3);
}
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(11);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
@Test
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn()
throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(11);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
List<Integer> li = template.queryForList("SELECT AGE FROM CUSTMR WHERE ID < :id",
parms, Integer.class);
List li = template.queryForList(sql, parms, Integer.class);
assertEquals("All rows returned", 1, li.size());
assertEquals("First row is Integer", 11, ((Integer) li.get(0)).intValue());
assertEquals("First row is Integer", 11, li.get(0).intValue());
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForMapWithParamMapAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSetMetaData.getColumnLabel(1);
ctrlResultSetMetaData.setReturnValue("age", 1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getObject(1);
ctrlResultSet.setReturnValue(new Integer(11));
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
Map map = template.queryForMap("SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
Map map = template.queryForMap(sql, parms);
assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue());
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForObjectWithParamMapAndRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
parms, new RowMapper<Object>() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getInt(1);
}
});
Object o = template.queryForObject(sql, parms, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Integer(rs.getInt(1));
}
});
assertTrue("Correct result type", o instanceof Integer);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForObjectWithMapAndInteger() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("id", 3);
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
parms, Integer.class);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
Map parms = new HashMap();
parms.put("id", new Integer(3));
Object o = template.queryForObject(sql, parms, Integer.class);
assertTrue("Correct result type", o instanceof Integer);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForObjectWithParamMapAndInteger() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
parms, Integer.class);
Object o = template.queryForObject(sql, parms, Integer.class);
assertTrue("Correct result type", o instanceof Integer);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForObjectWithParamMapAndList() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID IN (:ids)";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID IN (?, ?)";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(2, new Integer(4));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("ids", Arrays.asList(new Object[] {new Integer(3), new Integer(4)}));
parms.addValue("ids", Arrays.asList(new Object[] { 3, 4 }));
Object o = template.queryForObject(sql, parms, Integer.class);
assertTrue("Correct result type", o instanceof Integer);
verify(connection).prepareStatement(sqlToUse);
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForObjectWithParamMapAndListOfExpressionLists() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(2, "Rod");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(3, new Integer(4));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setString(4, "Juergen");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
MapSqlParameterSource parms = new MapSqlParameterSource();
List l1 = new ArrayList();
l1.add(new Object[] {new Integer(3), "Rod"});
l1.add(new Object[] {new Integer(4), "Juergen"});
List<Object[]> l1 = new ArrayList<Object[]>();
l1.add(new Object[] { 3, "Rod" });
l1.add(new Object[] { 4, "Juergen" });
parms.addValue("multiExpressionList", l1);
Object o = template.queryForObject(
"SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)",
parms, Integer.class);
Object o = template.queryForObject(sql, parms, Integer.class);
assertTrue("Correct result type", o instanceof Integer);
verify(connection).prepareStatement(
"SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForIntWithParamMap() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getInt(1);
ctrlResultSet.setReturnValue(22.0d);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(3));
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22);
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("id", new Integer(3));
parms.addValue("id", 3);
int i = template.queryForInt("SELECT AGE FROM CUSTMR WHERE ID = :id", parms);
int i = template.queryForInt(sql, parms);
assertEquals("Return of an int", 22, i);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
verify(preparedStatement).setObject(1, 3);
}
@Test
public void testQueryForLongWithParamBean() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L);
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
BeanPropertySqlParameterSource parms = new BeanPropertySqlParameterSource(
new ParameterBean(3));
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getLong(1);
ctrlResultSet.setReturnValue(87.0d);
mockResultSet.wasNull();
ctrlResultSet.setReturnValue(false);
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
long l = template.queryForLong("SELECT AGE FROM CUSTMR WHERE ID = :id", parms);
mockPreparedStatement.setObject(1, new Integer(3), Types.INTEGER);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeQuery();
ctrlPreparedStatement.setReturnValue(mockResultSet);
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
BeanPropertySqlParameterSource parms = new BeanPropertySqlParameterSource(new ParameterBean(3));
long l = template.queryForLong(sql, parms);
assertEquals("Return of a long", 87, l);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
verify(preparedStatement).setObject(1, 3, Types.INTEGER);
}
private static class ParameterBean {
static class ParameterBean {
private int id;

View File

@@ -1,14 +1,11 @@
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Types;
@@ -16,74 +13,51 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.SqlInOutParameter;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.metadata.CallMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
/**
* 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;
public class CallMetaDataContextTests {
private DataSource dataSource;
private Connection connection;
private DatabaseMetaData databaseMetaData;
private CallMetaDataContext context = new CallMetaDataContext();
@Override
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);
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
databaseMetaData = mock(DatabaseMetaData.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
@After
public void verifyClosed() throws Exception {
verify(connection).close();
}
@Test
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();
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getUserName()).willReturn(USER);
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
List<SqlParameter> parameters = new ArrayList<SqlParameter>();
parameters.add(new SqlParameter("id", Types.NUMERIC));
@@ -96,7 +70,7 @@ public class CallMetaDataContextTests extends TestCase {
parameterSource.addValue("customer_no", "12345XYZ");
context.setProcedureName(TABLE);
context.initializeMetaData(mockDataSource);
context.initializeMetaData(dataSource);
context.processParameters(parameters);
Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource);
@@ -110,7 +84,6 @@ public class CallMetaDataContextTests extends TestCase {
List<SqlParameter> callParameters = context.getCallParameters();
assertEquals("Wrong number of call parameters", 3, callParameters.size());
}
}

View File

@@ -16,9 +16,13 @@
package org.springframework.jdbc.core.simple;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.AbstractRowMapperTests;
import org.springframework.jdbc.core.test.ConcretePerson;
@@ -29,46 +33,43 @@ import org.springframework.jdbc.core.test.Person;
*/
public class ParameterizedBeanPropertyRowMapperTests extends AbstractRowMapperTests {
private SimpleJdbcTemplate simpleJdbcTemplate;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
protected void setUp() throws SQLException {
super.setUp();
simpleJdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testOverridingDifferentClassDefinedForMapping() {
ParameterizedBeanPropertyRowMapper mapper = ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
thrown.expect(InvalidDataAccessApiUsageException.class);
mapper.setMappedClass(Long.class);
}
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");
}
@Test
public void testOverridingSameClassDefinedForMapping() {
ParameterizedBeanPropertyRowMapper<Person> mapper = ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
mapper.setMappedClass(Person.class);
}
public void testStaticQueryWithRowMapper() throws SQLException {
List<Person> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
@Test
public void testStaticQueryWithRowMapper() throws Exception {
Mock mock = new Mock();
List<Person> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
ParameterizedBeanPropertyRowMapper.newInstance(Person.class));
assertEquals(1, result.size());
Person bean = result.get(0);
verifyPerson(bean);
verifyPerson(result.get(0));
mock.verifyClosed();
}
public void testMappingWithInheritance() throws SQLException {
List<ConcretePerson> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
@Test
public void testMappingWithInheritance() throws Exception {
Mock mock = new Mock();
List<ConcretePerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
ParameterizedBeanPropertyRowMapper.newInstance(ConcretePerson.class));
assertEquals(1, result.size());
ConcretePerson bean = result.get(0);
verifyConcretePerson(bean);
verifyConcretePerson(result.get(0));
mock.verifyClosed();
}
}

View File

@@ -16,469 +16,274 @@
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.build.test.hamcrest.Matchers.exceptionCause;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
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 {
public class SimpleJdbcCallTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
private MockControl ctrlCallable;
private CallableStatement mockCallable;
private Connection connection;
private DatabaseMetaData databaseMetaData;
private DataSource dataSource;
private CallableStatement callableStatement;
@Override
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();
}
@Override
protected void tearDown() throws Exception {
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
ctrlCallable.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
ctrlCallable.replay();
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
databaseMetaData = mock(DatabaseMetaData.class);
dataSource = mock(DataSource.class);
callableStatement = mock(CallableStatement.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection);
}
@Test
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);
SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getUserName()).willReturn("me");
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
given(callableStatement.execute()).willThrow(sqlException);
given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
thrown.expect(BadSqlGrammarException.class);
thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
sproc.execute();
fail("Shouldn't succeed in running stored procedure which doesn't exist");
} catch (BadSqlGrammarException ex) {
// OK
}
finally {
verify(callableStatement).close();
verify(connection, atLeastOnce()).close();
}
}
@Test
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
}
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC);
// Shouldn't succeed in adding unnamed parameter
thrown.expect(InvalidDataAccessApiUsageException.class);
sproc.addDeclaredParameter(new SqlParameter(1));
}
@Test
public void testAddInvoiceProcWithoutMetaDataUsingMapParamSource() throws Exception {
final int amount = 1103;
final int custid = 3;
initializeAddInvoiceWithoutMetaData(false);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).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));
new SqlOutParameter("newid",
Types.INTEGER));
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource().
addValue("amount", 1103).
addValue("custid", 3));
assertEquals(4, newId.intValue());
verifyAddInvoiceWithoutMetaData(false);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceProcWithoutMetaDataUsingArrayParams() throws Exception {
final int amount = 1103;
final int custid = 3;
initializeAddInvoiceWithoutMetaData(false);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).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, amount, custid);
new SqlOutParameter("newid",
Types.INTEGER));
Number newId = adder.executeObject(Number.class, 1103, 3);
assertEquals(4, newId.intValue());
verifyAddInvoiceWithoutMetaData(false);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceProcWithMetaDataUsingMapParamSource() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
initializeAddInvoiceWithMetaData(false);
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
.addValue("amount", 1103)
.addValue("custid", 3));
assertEquals(4, newId.intValue());
ctrlResultSet.verify();
verifyAddInvoiceWithMetaData(false);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceProcWithMetaDataUsingArrayParams() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
Number newId = adder.executeObject(Number.class, amount, custid);
initializeAddInvoiceWithMetaData(false);
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
Number newId = adder.executeObject(Number.class, 1103, 3);
assertEquals(4, newId.intValue());
ctrlResultSet.verify();
verifyAddInvoiceWithMetaData(false);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceFuncWithoutMetaDataUsingMapParamSource() throws Exception {
final int amount = 1103;
final int custid = 3;
initializeAddInvoiceWithoutMetaData(true);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).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));
.addValue("amount", 1103)
.addValue("custid", 3));
assertEquals(4, newId.intValue());
verifyAddInvoiceWithoutMetaData(true);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceFuncWithoutMetaDataUsingArrayParams() throws Exception {
final int amount = 1103;
final int custid = 3;
initializeAddInvoiceWithoutMetaData(true);
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).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, amount, custid);
Number newId = adder.executeFunction(Number.class, 1103, 3);
assertEquals(4, newId.intValue());
verifyAddInvoiceWithoutMetaData(true);
verify(connection, atLeastOnce()).close();
}
@Test
public void testAddInvoiceFuncWithMetaDataUsingMapParamSource() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
initializeAddInvoiceWithMetaData(true);
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
.addValue("amount", amount)
.addValue("custid", custid));
.addValue("amount", 1103)
.addValue("custid", 3));
assertEquals(4, newId.intValue());
verifyAddInvoiceWithMetaData(true);
verify(connection, atLeastOnce()).close();
ctrlResultSet.verify();
}
public void testAddInvoiceFuncWithMetaDataUsingArrayParams() throws Exception {
final int amount = 1103;
final int custid = 3;
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
ctrlResultSet.replay();
replay();
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
Number newId = adder.executeFunction(Number.class, amount, custid);
@Test public void testAddInvoiceFuncWithMetaDataUsingArrayParams() throws Exception {
initializeAddInvoiceWithMetaData(true);
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
Number newId = adder.executeFunction(Number.class, 1103, 3);
assertEquals(4, newId.intValue());
verifyAddInvoiceWithMetaData(true);
verify(connection, atLeastOnce()).close();
ctrlResultSet.verify();
}
private void initializeAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException {
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);
private void initializeAddInvoiceWithoutMetaData(boolean isFunction)
throws SQLException {
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getUserName()).willReturn("me");
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
if (isFunction) {
mockCallable.registerOutParameter(1, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(3, 3, 4);
ctrlCallable.setVoidCallable();
given(callableStatement.getObject(1)).willReturn(4L);
given(connection.prepareCall("{? = call add_invoice(?, ?)}")
).willReturn(callableStatement);
}
else {
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);
if (isFunction) {
mockCallable.getObject(1);
}
else {
mockCallable.getObject(3);
}
ctrlCallable.setReturnValue(new Long(4));
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
if (isFunction) {
mockConnection.prepareCall(
"{? = call add_invoice(?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
}
else {
mockConnection.prepareCall(
"{call add_invoice(?, ?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
given(callableStatement.getObject(3)).willReturn(4L);
given(connection.prepareCall("{call add_invoice(?, ?, ?)}")
).willReturn(callableStatement);
}
}
private MockControl initializeAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
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);
private void verifyAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException {
if (isFunction) {
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue(null);
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(5);
verify(callableStatement).registerOutParameter(1, 4);
verify(callableStatement).setObject(2, 1103, 4);
verify(callableStatement).setObject(3, 3, 4);
}
else {
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("amount");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
verify(callableStatement).setObject(1, 1103, 4);
verify(callableStatement).setObject(2, 3, 4);
verify(callableStatement).registerOutParameter(3, 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(true);
if (isFunction) {
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("amount");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
}
else {
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);
if (isFunction) {
mockResultSet.getString("COLUMN_NAME");
ctrlResultSet.setReturnValue("custid");
mockResultSet.getInt("COLUMN_TYPE");
ctrlResultSet.setReturnValue(1);
}
else {
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);
if (isFunction) {
mockCallable.registerOutParameter(1, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(2, 1103, 4);
ctrlCallable.setVoidCallable();
mockCallable.setObject(3, 3, 4);
ctrlCallable.setVoidCallable();
}
else {
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);
if (isFunction) {
mockCallable.getObject(1);
ctrlCallable.setReturnValue(new Long(4));
}
else {
mockCallable.getObject(3);
ctrlCallable.setReturnValue(new Long(4));
}
if (debugEnabled) {
mockCallable.getWarnings();
ctrlCallable.setReturnValue(null);
}
mockCallable.close();
ctrlCallable.setVoidCallable();
if (isFunction) {
mockConnection.prepareCall(
"{? = call ADD_INVOICE(?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
}
else {
mockConnection.prepareCall(
"{call ADD_INVOICE(?, ?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
}
return ctrlResultSet;
verify(callableStatement).close();
}
private void initializeAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
ResultSet proceduresResultSet = mock(ResultSet.class);
ResultSet procedureColumnsResultSet = mock(ResultSet.class);
given(databaseMetaData.getDatabaseProductName()).willReturn("Oracle");
given(databaseMetaData.getUserName()).willReturn("ME");
given(databaseMetaData.storesUpperCaseIdentifiers()).willReturn(true);
given(databaseMetaData.getProcedures("", "ME", "ADD_INVOICE")).willReturn(proceduresResultSet);
given(databaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null)).willReturn(procedureColumnsResultSet);
given(proceduresResultSet.next()).willReturn(true, false);
given(proceduresResultSet.getString("PROCEDURE_NAME")).willReturn("add_invoice");
given(procedureColumnsResultSet.next()).willReturn(true, true, true, false);
given(procedureColumnsResultSet.getInt("DATA_TYPE")).willReturn(4);
if (isFunction) {
given(procedureColumnsResultSet.getString("COLUMN_NAME")).willReturn(null,"amount", "custid");
given(procedureColumnsResultSet.getInt("COLUMN_TYPE")).willReturn(5, 1, 1);
given(connection.prepareCall("{? = call ADD_INVOICE(?, ?)}")).willReturn(callableStatement);
given(callableStatement.getObject(1)).willReturn(4L);
}
else {
given(procedureColumnsResultSet.getString("COLUMN_NAME")).willReturn("amount", "custid", "newid");
given(procedureColumnsResultSet.getInt("COLUMN_TYPE")).willReturn(1, 1, 4);
given(connection.prepareCall("{call ADD_INVOICE(?, ?, ?)}")).willReturn(callableStatement);
given(callableStatement.getObject(3)).willReturn(4L);
}
given(callableStatement.getUpdateCount()).willReturn(-1);
}
private void verifyAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
ResultSet proceduresResultSet = databaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
ResultSet procedureColumnsResultSet = databaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
if (isFunction) {
verify(callableStatement).registerOutParameter(1, 4);
verify(callableStatement).setObject(2, 1103, 4);
verify(callableStatement).setObject(3, 3, 4);
}
else {
verify(callableStatement).setObject(1, 1103, 4);
verify(callableStatement).setObject(2, 3, 4);
verify(callableStatement).registerOutParameter(3, 4);
}
verify(callableStatement).close();
verify(proceduresResultSet).close();
verify(procedureColumnsResultSet).close();
}
}

View File

@@ -16,105 +16,71 @@
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.HashMap;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
/**
* Mock object based tests for SimpleJdbcInsert.
*
* @author Thomas Risberg
*/
public class SimpleJdbcInsertTests extends TestCase {
public class SimpleJdbcInsertTests {
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
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);
private Connection connection;
private DatabaseMetaData databaseMetaData;
private DataSource dataSource;
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
databaseMetaData = mock(DatabaseMetaData.class);
dataSource = mock(DataSource.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
@After
public void verifyClosed() throws Exception {
verify(connection).close();
}
@Test
public void testNoSuchTable() throws Exception {
final String NO_SUCH_TABLE = "x";
final String USER = "me";
ResultSet resultSet = mock(ResultSet.class);
given(resultSet.next()).willReturn(false);
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getDatabaseProductVersion()).willReturn("1.0");
given(databaseMetaData.getUserName()).willReturn("me");
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
given(databaseMetaData.getTables(null, null, "x", null)).willReturn(resultSet);
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);
SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource).withTableName("x");
// Shouldn't succeed in inserting into table which doesn't exist
thrown.expect(InvalidDataAccessApiUsageException.class);
try {
insert.execute(new HashMap());
fail("Shouldn't succeed in inserting into table which doesn't exist");
} catch (InvalidDataAccessApiUsageException ex) {
// OK
insert.execute(new HashMap<String, Object>());
}
finally {
verify(resultSet).close();
}
}
public void testInsert() throws Exception {
replay();
}
}

View File

@@ -16,27 +16,32 @@
package org.springframework.jdbc.core.simple;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
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.apache.commons.logging.LogFactory;
import org.easymock.MockControl;
import org.easymock.internal.ArrayMatcher;
import org.springframework.jdbc.core.BatchUpdateTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
@@ -49,567 +54,321 @@ import org.springframework.jdbc.core.namedparam.SqlParameterSource;
* @author Juergen Hoeller
* @author Thomas Risberg
*/
public class SimpleJdbcTemplateTests extends TestCase {
public class SimpleJdbcTemplateTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private static final String SQL = "sql";
private static final Object[] ARGS_ARRAY = { 24.7, "foo", new Object() };
private static final Map<String, Object> ARGS_MAP;
private static final MapSqlParameterSource ARGS_SOURCE;
static {
ARGS_MAP = new HashMap<String, Object>(3);
ARGS_SOURCE = new MapSqlParameterSource();
for (int i = 0; i < ARGS_ARRAY.length; i++) {
ARGS_MAP.put(String.valueOf(i), ARGS_ARRAY[i]);
ARGS_SOURCE.addValue(String.valueOf(i), ARGS_ARRAY[i]);
}
}
private JdbcOperations operations;
private NamedParameterJdbcOperations namedParameterOperations;
private SimpleJdbcTemplate template;
private SimpleJdbcTemplate namedParameterTemplate;
@Before
public void setup() {
this.operations = mock(JdbcOperations.class);
this.namedParameterOperations = mock(NamedParameterJdbcOperations.class);
this.template = new SimpleJdbcTemplate(operations);
this.namedParameterTemplate = new SimpleJdbcTemplate(namedParameterOperations);
}
@Test
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();
given(operations.queryForInt(SQL)).willReturn(666);
int result = template.queryForInt(SQL);
assertEquals(666, result);
}
@Test
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();
given(operations.queryForInt(SQL, new Object[] { 24, "foo" })).willReturn(666);
int result = template.queryForInt(SQL, 24, "foo");
assertEquals(666, result);
}
@Test
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<String, Object> args = new HashMap<String, Object>(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();
args.put("id", 24);
args.put("xy", "foo");
given(namedParameterOperations.queryForInt(SQL, args)).willReturn(666);
int result = namedParameterTemplate.queryForInt(SQL, args);
assertEquals(666, result);
}
@Test
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();
SqlParameterSource args = new MapSqlParameterSource().addValue("id", 24).addValue("xy", "foo");
given(namedParameterOperations.queryForInt(SQL, args)).willReturn(666);
int result = namedParameterTemplate.queryForInt(SQL, args);
assertEquals(666, result);
}
@Test
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();
given(operations.queryForLong(SQL)).willReturn((long) 666);
long result = template.queryForLong(SQL);
assertEquals(666, result);
}
@Test
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);
given(operations.queryForLong(SQL, ARGS_ARRAY)).willReturn(expectedResult);
long result = template.queryForLong(SQL, ARGS_ARRAY);
assertEquals(expectedResult, result);
mc.verify();
}
@Test
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();
given(operations.queryForObject(SQL, Date.class)).willReturn(expectedResult);
Date result = template.queryForObject(SQL, Date.class);
assertSame(expectedResult, result);
}
@Test
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();
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
).willReturn(expectedResult);
Date result = template.queryForObject(SQL, Date.class,ARGS_ARRAY);
assertSame(expectedResult, result);
}
@Test
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();
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
).willReturn(expectedResult);
Date result = template.queryForObject(SQL, Date.class, ARGS_ARRAY);
assertSame(expectedResult, result);
}
@Test
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();
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
).willReturn(expectedResult);
Date result = template.queryForObject(SQL, Date.class, ARGS_ARRAY);
assertSame(expectedResult, result);
}
@Test
public void testQueryForObjectWithRowMapperAndWithoutArgs() throws Exception {
String sql = "SELECT SYSDATE FROM DUAL";
Date expectedResult = new Date();
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
@Override
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();
given(operations.queryForObject(SQL, rm)).willReturn(expectedResult);
Date result = template.queryForObject(SQL, rm);
assertSame(expectedResult, result);
}
@Test
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>() {
@Override
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();
given(operations.queryForObject(SQL, ARGS_ARRAY, rm)
).willReturn(expectedResult);
Date result = template.queryForObject(SQL, rm, ARGS_ARRAY);
assertSame(expectedResult, result);
}
@Test
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>() {
@Override
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();
given(operations.queryForObject(sql, ARGS_ARRAY, rm)
).willReturn(expectedResult);
Date result = template.queryForObject(sql, rm, ARGS_ARRAY);
assertSame(expectedResult, result);
}
@Test
public void testQueryForListWithoutArgs() throws Exception {
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{}, Collections.singletonList(new Object()));
List<Map<String, Object>> expectedResult = mockListMapResult();
given(operations.queryForList(SQL)).willReturn(expectedResult);
List<Map<String, Object>> result = template.queryForList(SQL);
assertSame(expectedResult, result);
}
@Test
public void testQueryForListWithArgs() throws Exception {
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{1, 2, 3}, new LinkedList());
List<Map<String, Object>> expectedResult = mockListMapResult();
given(operations.queryForList(SQL, 1, 2, 3)).willReturn(expectedResult);
List<Map<String, Object>> result = template.queryForList(SQL, 1,2,3);
assertSame(expectedResult, result);
}
@Test
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());
List<Map<String, Object>> expectedResult = mockListMapResult();
given(namedParameterOperations.queryForList(SQL, ARGS_MAP)).willReturn(expectedResult);
List<Map<String, Object>> result = namedParameterTemplate.queryForList(SQL, ARGS_MAP);
assertSame(expectedResult, result);
}
@Test
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());
List<Map<String, Object>> expectedResult = mockListMapResult();
given(namedParameterOperations.queryForList(SQL, ARGS_SOURCE)).willReturn(expectedResult);
List<Map<String, Object>> result = namedParameterTemplate.queryForList(SQL, ARGS_SOURCE);
assertSame(expectedResult, result);
}
@Test
public void testQueryForMapWithoutArgs() throws Exception {
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{}, new HashMap());
Map<String, Object> expectedResult = new HashMap<String, Object>();
given(operations.queryForMap(SQL)).willReturn(expectedResult);
Map<String, Object> result = template.queryForMap(SQL);
assertSame(expectedResult, result);
}
@Test
public void testQueryForMapWithArgs() throws Exception {
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{1, 2, 3}, new HashMap());
// TODO test generic type
Map<String, Object> expectedResult = new HashMap<String, Object>();
given(operations.queryForMap(SQL, 1, 2, 3)).willReturn(expectedResult);
Map<String, Object> result = template.queryForMap(SQL, 1,2,3);
assertSame(expectedResult, result);
}
@Test
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());
Map<String, Object> expectedResult = new HashMap<String, Object>();
given(namedParameterOperations.queryForMap(SQL, ARGS_MAP)).willReturn(expectedResult);
Map<String, Object> result = namedParameterTemplate.queryForMap(SQL, ARGS_MAP);
assertSame(expectedResult, result);
}
@Test
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());
Map<String, Object> expectedResult = new HashMap<String, Object>();
given(namedParameterOperations.queryForMap(SQL, ARGS_SOURCE)).willReturn(expectedResult);
Map<String, Object> result = namedParameterTemplate.queryForMap(SQL, ARGS_SOURCE);
assertSame(expectedResult, result);
}
@Test
public void testUpdateWithoutArgs() throws Exception {
testDelegation("update", new Object[]{"sql"}, new Object[]{}, 666);
given(operations.update(SQL)).willReturn(666);
int result = template.update(SQL);
assertEquals(666, result);
}
@Test
public void testUpdateWithArgs() throws Exception {
testDelegation("update", new Object[]{"sql"}, new Object[]{1, 2, 3}, 666);
given(operations.update(SQL, 1, 2, 3)).willReturn(666);
int result = template.update(SQL, 1, 2, 3);
assertEquals(666, result);
}
@Test
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);
given(namedParameterOperations.update(SQL, ARGS_MAP)).willReturn(666);
int result = namedParameterTemplate.update(SQL, ARGS_MAP);
assertEquals(666, result);
}
@Test
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;
given(namedParameterOperations.update(SQL, ARGS_SOURCE)).willReturn(666);
int result = namedParameterTemplate.update(SQL, ARGS_SOURCE);
assertEquals(666, result);
}
@Test
public void testBatchUpdateWithSqlParameterSource() throws Exception {
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
PreparedStatement preparedStatement = setupBatchOperation();
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 ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
int[] actualRowsAffected = template.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
assertEquals(1, actualRowsAffected[0]);
assertEquals(2, actualRowsAffected[1]);
verify(preparedStatement).setObject(1, 100);
verify(preparedStatement).setObject(1, 200);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement).close();
}
@Test
public void testBatchUpdateWithListOfObjectArrays() throws Exception {
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 ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
PreparedStatement preparedStatement = setupBatchOperation();
List<Object[]> ids = new ArrayList<Object[]>();
ids.add(new Object[] { 100 });
ids.add(new Object[] { 200 });
int[] actualRowsAffected = template.batchUpdate(SQL, ids);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
assertEquals(1, actualRowsAffected[0]);
assertEquals(2, actualRowsAffected[1]);
verify(preparedStatement).setObject(1, 100);
verify(preparedStatement).setObject(1, 200);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement).close();
}
@Test
public void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception {
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[] sqlTypes = new int[] {Types.NUMERIC};
final int[] rowsAffected = new int[] { 1, 2 };
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
mockDatabaseMetaData);
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids, sqlTypes);
int[] sqlTypes = new int[] { Types.NUMERIC };
PreparedStatement preparedStatement = setupBatchOperation();
List<Object[]> ids = new ArrayList<Object[]>();
ids.add(new Object[] { 100 });
ids.add(new Object[] { 200 });
int[] actualRowsAffected = template.batchUpdate(SQL, ids, sqlTypes);
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
assertEquals(rowsAffected[0], actualRowsAffected[0]);
assertEquals(rowsAffected[1], actualRowsAffected[1]);
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
assertEquals(1, actualRowsAffected[0]);
assertEquals(2, actualRowsAffected[1]);
verify(preparedStatement).setObject(1, 100, Types.NUMERIC);
verify(preparedStatement).setObject(1, 200, Types.NUMERIC);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement).close();
}
private PreparedStatement setupBatchOperation() throws SQLException {
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
given(dataSource.getConnection()).willReturn(connection);
given(preparedStatement.getConnection()).willReturn(connection);
given(preparedStatement.executeBatch()).willReturn(new int[] { 1, 2 });
given(databaseMetaData.getDatabaseProductName()).willReturn("MySQL");
given(databaseMetaData.supportsBatchUpdates()).willReturn(true);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(connection.getMetaData()).willReturn(databaseMetaData);
template = new SimpleJdbcTemplate(new JdbcTemplate(dataSource, false));
return preparedStatement;
}
private List<Map<String, Object>> mockListMapResult() {
return new LinkedList<Map<String, Object>>();
}
}

View File

@@ -1,151 +1,81 @@
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 static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
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;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.metadata.TableMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
/**
* 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;
public class TableMetaDataContextTests {
private Connection connection;
private DataSource dataSource;
private DatabaseMetaData databaseMetaData;
private TableMetaDataContext context = new TableMetaDataContext();
@Override
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);
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
dataSource = mock(DataSource.class);
databaseMetaData = mock(DatabaseMetaData.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
public void verifyClosed() throws Exception {
verify(connection).close();
}
@Test
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();
ResultSet metaDataResultSet = mock(ResultSet.class);
given(metaDataResultSet.next()).willReturn(true, false);
given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");
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();
ResultSet columnsResultSet = mock(ResultSet.class);
given(columnsResultSet.next()).willReturn(
true, true, true, true, false);
given(columnsResultSet.getString("COLUMN_NAME")).willReturn(
"id", "name", "customersince", "version");
given(columnsResultSet.getInt("DATA_TYPE")).willReturn(
Types.INTEGER, Types.VARCHAR, Types.DATE, Types.NUMERIC);
given(columnsResultSet.getBoolean("NULLABLE")).willReturn(
false, true, true, false);
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();
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
given(databaseMetaData.getUserName()).willReturn(USER);
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);
MapSqlParameterSource map = new MapSqlParameterSource();
map.addValue("id", 1);
@@ -156,88 +86,59 @@ public class TableMetaDataContextTests extends TestCase {
map.registerSqlType("version", Types.NUMERIC);
context.setTableName(TABLE);
context.processMetaData(mockDataSource, new ArrayList<String>(), new String[] {});
context.processMetaData(dataSource, 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);
assertTrue("date wrapped with type info",
values.get(2) instanceof SqlParameterValue);
assertTrue("version wrapped with type info",
values.get(3) instanceof SqlParameterValue);
verify(metaDataResultSet, atLeastOnce()).next();
verify(columnsResultSet, atLeastOnce()).next();
verify(metaDataResultSet).close();
verify(columnsResultSet).close();
}
@Test
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();
ResultSet metaDataResultSet = mock(ResultSet.class);
given(metaDataResultSet.next()).willReturn(true, false);
given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");
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();
ResultSet columnsResultSet = mock(ResultSet.class);
given(columnsResultSet.next()).willReturn(true, false);
given(columnsResultSet.getString("COLUMN_NAME")).willReturn("id");
given(columnsResultSet.getInt("DATA_TYPE")).willReturn(Types.INTEGER);
given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false);
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();
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
given(databaseMetaData.getUserName()).willReturn(USER);
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);
MapSqlParameterSource map = new MapSqlParameterSource();
String[] keyCols = new String[] {"id"};
String[] keyCols = new String[] { "id" };
context.setTableName(TABLE);
context.processMetaData(mockDataSource, new ArrayList<String>(), keyCols);
context.processMetaData(dataSource, 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);
verify(metaDataResultSet, atLeastOnce()).next();
verify(columnsResultSet, atLeastOnce()).next();
verify(metaDataResultSet).close();
verify(columnsResultSet).close();
}
}

View File

@@ -16,72 +16,53 @@
package org.springframework.jdbc.core.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.jdbc.AbstractJdbcTests;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Rod Johnson
*/
public class JdbcBeanDefinitionReaderTests extends AbstractJdbcTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
public class JdbcBeanDefinitionReaderTests {
@Test
public void testValid() throws Exception {
String sql = "SELECT NAME AS NAME, PROPERTY AS PROPERTY, VALUE AS VALUE FROM T";
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
ctrlResultSet.expectAndReturn(mockResultSet.next(), true, 2);
ctrlResultSet.expectAndReturn(mockResultSet.next(), false);
Connection connection = mock(Connection.class);
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
// first row
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "(class)");
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "org.springframework.beans.TestBean");
ResultSet resultSet = mock(ResultSet.class);
given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getString(1)).willReturn("one", "one");
given(resultSet.getString(2)).willReturn("(class)", "age");
given(resultSet.getString(3)).willReturn("org.springframework.beans.TestBean", "53");
// second row
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "age");
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "53");
mockResultSet.close();
ctrlResultSet.setVoidCallable();
MockControl ctrlStatement = MockControl.createControl(Statement.class);
Statement mockStatement = (Statement) ctrlStatement.getMock();
ctrlStatement.expectAndReturn(mockStatement.executeQuery(sql), mockResultSet);
if (debugEnabled) {
ctrlStatement.expectAndReturn(mockStatement.getWarnings(), null);
}
mockStatement.close();
ctrlStatement.setVoidCallable();
mockConnection.createStatement();
ctrlConnection.setReturnValue(mockStatement);
ctrlResultSet.replay();
ctrlStatement.replay();
replay();
Statement statement = mock(Statement.class);
given(statement.executeQuery(sql)).willReturn(resultSet);
given(connection.createStatement()).willReturn(statement);
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
JdbcBeanDefinitionReader reader = new JdbcBeanDefinitionReader(bf);
reader.setDataSource(mockDataSource);
reader.setDataSource(dataSource);
reader.loadBeanDefinitions(sql);
assertEquals("Incorrect number of bean definitions", 1, bf.getBeanDefinitionCount());
TestBean tb = (TestBean) bf.getBean("one");
assertEquals("Age in TestBean was wrong.", 53, tb.getAge());
ctrlResultSet.verify();
ctrlStatement.verify();
verify(resultSet).close();
verify(statement).close();
}
}

View File

@@ -16,26 +16,27 @@
package org.springframework.jdbc.core.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Juergen Hoeller
* @since 30.07.2003
*/
public class JdbcDaoSupportTests extends TestCase {
public class JdbcDaoSupportTests {
@Test
public void testJdbcDaoSupportWithDataSource() throws Exception {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
final List test = new ArrayList();
DataSource ds = mock(DataSource.class);
final List<String> test = new ArrayList<String>();
JdbcDaoSupport dao = new JdbcDaoSupport() {
@Override
protected void initDao() {
@@ -49,9 +50,10 @@ public class JdbcDaoSupportTests extends TestCase {
assertEquals("initDao called", test.size(), 1);
}
@Test
public void testJdbcDaoSupportWithJdbcTemplate() throws Exception {
JdbcTemplate template = new JdbcTemplate();
final List test = new ArrayList();
final List<String> test = new ArrayList<String>();
JdbcDaoSupport dao = new JdbcDaoSupport() {
@Override
protected void initDao() {

View File

@@ -16,14 +16,20 @@
package org.springframework.jdbc.core.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.LobRetrievalFailureException;
@@ -33,32 +39,19 @@ import org.springframework.jdbc.support.lob.LobHandler;
/**
* @author Alef Arendsen
*/
public class LobSupportTests extends TestCase {
public class LobSupportTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testCreatingPreparedStatementCallback() throws SQLException {
// - return value should match
// - lob creator should be closed
// - set return value should be called
// - execute update should be called
LobHandler handler = mock(LobHandler.class);
LobCreator creator = mock(LobCreator.class);
PreparedStatement ps = mock(PreparedStatement.class);
MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
LobHandler handler = (LobHandler)lobHandlerControl.getMock();
MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
LobCreator creator = (LobCreator)lobCreatorControl.getMock();
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement)psControl.getMock();
handler.getLobCreator();
lobHandlerControl.setReturnValue(creator);
ps.executeUpdate();
psControl.setReturnValue(3);
creator.close();
lobHandlerControl.replay();
lobCreatorControl.replay();
psControl.replay();
given(handler.getLobCreator()).willReturn(creator);
given(ps.executeUpdate()).willReturn(3);
class SetValuesCalled {
boolean b = false;
@@ -66,9 +59,8 @@ public class LobSupportTests extends TestCase {
final SetValuesCalled svc = new SetValuesCalled();
AbstractLobCreatingPreparedStatementCallback psc =
new AbstractLobCreatingPreparedStatementCallback(handler) {
AbstractLobCreatingPreparedStatementCallback psc = new AbstractLobCreatingPreparedStatementCallback(
handler) {
@Override
protected void setValues(PreparedStatement ps, LobCreator lobCreator)
throws SQLException, DataAccessException {
@@ -77,85 +69,62 @@ public class LobSupportTests extends TestCase {
};
assertEquals(new Integer(3), psc.doInPreparedStatement(ps));
lobHandlerControl.verify();
lobCreatorControl.verify();
psControl.verify();
assertTrue(svc.b);
verify(creator).close();
verify(handler).getLobCreator();
verify(ps).executeUpdate();
}
@Test
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
MockControl rsetControl = MockControl.createControl(ResultSet.class);
ResultSet rset = (ResultSet)rsetControl.getMock();
rset.next();
rsetControl.setReturnValue(false);
rsetControl.replay();
ResultSet rset = mock(ResultSet.class);
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
lobRse.extractData(rset);
fail("IncorrectResultSizeDataAccessException should have been thrown");
} catch (IncorrectResultSizeDataAccessException e) {
// expected
}
finally {
verify(rset).next();
}
}
@Test
public void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException {
MockControl rsetControl = MockControl.createControl(ResultSet.class);
ResultSet rset = (ResultSet)rsetControl.getMock();
rset.next();
rsetControl.setReturnValue(true);
// see if it's called
rset.clearWarnings();
rset.next();
rsetControl.setReturnValue(false);
rsetControl.replay();
ResultSet rset = mock(ResultSet.class);
given(rset.next()).willReturn(true, false);
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
lobRse.extractData(rset);
rsetControl.verify();
verify(rset).clearWarnings();
}
public void testAbstractLobStreamingResultSetExtractorMultipleRows() throws SQLException {
MockControl rsetControl = MockControl.createControl(ResultSet.class);
ResultSet rset = (ResultSet)rsetControl.getMock();
rset.next();
rsetControl.setReturnValue(true);
// see if it's called
rset.clearWarnings();
rset.next();
rsetControl.setReturnValue(true);
rsetControl.replay();
@Test
public void testAbstractLobStreamingResultSetExtractorMultipleRows()
throws SQLException {
ResultSet rset = mock(ResultSet.class);
given(rset.next()).willReturn(true, true, false);
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
lobRse.extractData(rset);
fail("IncorrectResultSizeDataAccessException should have been thrown");
} catch (IncorrectResultSizeDataAccessException e) {
// expected
}
rsetControl.verify();
finally {
verify(rset).clearWarnings();
}
}
public void testAbstractLobStreamingResultSetExtractorCorrectException() throws SQLException {
MockControl rsetControl = MockControl.createControl(ResultSet.class);
ResultSet rset = (ResultSet)rsetControl.getMock();
rset.next();
rsetControl.setReturnValue(true);
rsetControl.replay();
@Test
public void testAbstractLobStreamingResultSetExtractorCorrectException()
throws SQLException {
ResultSet rset = mock(ResultSet.class);
given(rset.next()).willReturn(true);
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(true);
try {
lobRse.extractData(rset);
fail("LobRetrievalFailureException should have been thrown");
} catch (LobRetrievalFailureException e) {
// expected
}
rsetControl.verify();
thrown.expect(LobRetrievalFailureException.class);
lobRse.extractData(rset);
}
private AbstractLobStreamingResultSetExtractor getResultSetExtractor(final boolean ex) {
AbstractLobStreamingResultSetExtractor lobRse = new AbstractLobStreamingResultSetExtractor() {
@Override
protected void streamData(ResultSet rs) throws SQLException, IOException {
if (ex) {

View File

@@ -15,18 +15,28 @@
*/
package org.springframework.jdbc.core.support;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
@@ -46,179 +56,96 @@ import org.springframework.jdbc.support.lob.LobHandler;
*
* @author Alef Arendsen
*/
public class SqlLobValueTests extends TestCase {
public class SqlLobValueTests {
private MockControl psControl;
private PreparedStatement ps;
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockControl lobHandlerControl;
private PreparedStatement preparedStatement;
private LobHandler handler;
private MockControl lobCreatorControl;
private LobCreator creator;
@Override
@Captor
private ArgumentCaptor<InputStream> inputStreamCaptor;
@Before
public void setUp() {
// create preparedstatement
psControl = MockControl.createControl(PreparedStatement.class);
ps = (PreparedStatement) psControl.getMock();
// create handler controler
lobHandlerControl = MockControl.createControl(LobHandler.class);
handler = (LobHandler) lobHandlerControl.getMock();
// create creator control
lobCreatorControl = MockControl.createControl(LobCreator.class);
creator = (LobCreator) lobCreatorControl.getMock();
// set initial state
handler.getLobCreator();
lobHandlerControl.setReturnValue(creator);
}
private void replay() {
psControl.replay();
lobHandlerControl.replay();
lobCreatorControl.replay();
MockitoAnnotations.initMocks(this);
preparedStatement = mock(PreparedStatement.class);
handler = mock(LobHandler.class);
creator = mock(LobCreator.class);
given(handler.getLobCreator()).willReturn(creator);
}
@Test
public void test1() throws SQLException {
byte[] testBytes = "Bla".getBytes();
creator.setBlobAsBytes(ps, 1, testBytes);
replay();
SqlLobValue lob = new SqlLobValue(testBytes, handler);
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lobHandlerControl.verify();
lobCreatorControl.verify();
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
verify(creator).setBlobAsBytes(preparedStatement, 1, testBytes);
}
@Test
public void test2() throws SQLException {
String testString = "Bla";
creator.setBlobAsBytes(ps, 1, testString.getBytes());
// set a matcher to match the byte array!
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
@Override
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[2];
byte[] two = (byte[]) arg1[2];
return Arrays.equals(one, two);
}
@Override
public String toString(Object[] arg0) {
return "bla";
}
});
replay();
SqlLobValue lob = new SqlLobValue(testString, handler);
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lobHandlerControl.verify();
lobCreatorControl.verify();
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
verify(creator).setBlobAsBytes(preparedStatement, 1, testString.getBytes());
}
public void test3()
throws SQLException {
Date testContent = new Date();
SqlLobValue lob =
new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
try {
lob.setTypeValue(ps, 1, Types.BLOB, "test");
fail("IllegalArgumentException should have been thrown");
}
catch (IllegalArgumentException e) {
// expected
}
@Test
public void test3() throws SQLException {
SqlLobValue lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
}
@Test
public void test4() throws SQLException {
String testContent = "Bla";
creator.setClobAsString(ps, 1, testContent);
replay();
SqlLobValue lob = new SqlLobValue(testContent, handler);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lobHandlerControl.verify();
lobCreatorControl.verify();
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
verify(creator).setClobAsString(preparedStatement, 1, testContent);
}
public void test5() throws SQLException {
@Test
public void test5() throws Exception {
byte[] testContent = "Bla".getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
creator.setClobAsAsciiStream(ps, 1, bais, 3);
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
@Override
public boolean matches(Object[] arg0, Object[] arg1) {
// for now, match always
return true;
}
@Override
public String toString(Object[] arg0) {
return null;
}
});
replay();
SqlLobValue lob = new SqlLobValue(new ByteArrayInputStream(testContent), 3, handler);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lobHandlerControl.verify();
lobCreatorControl.verify();
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
verify(creator).setClobAsAsciiStream(eq(preparedStatement), eq(1), inputStreamCaptor.capture(), eq(3));
byte[] bytes = new byte[3];
inputStreamCaptor.getValue().read(bytes );
assertThat(bytes, equalTo(testContent));
}
public void test6()throws SQLException {
@Test
public void test6() throws SQLException {
byte[] testContent = "Bla".getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
InputStreamReader reader = new InputStreamReader(bais);
creator.setClobAsCharacterStream(ps, 1, reader, 3);
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
@Override
public boolean matches(Object[] arg0, Object[] arg1) {
// for now, match always
return true;
}
@Override
public String toString(Object[] arg0) {
return null;
}
});
replay();
SqlLobValue lob = new SqlLobValue(reader, 3, handler);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lobHandlerControl.verify();
lobCreatorControl.verify();
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
verify(creator).setClobAsCharacterStream(eq(preparedStatement), eq(1), eq(reader), eq(3));
}
@Test
public void test7() throws SQLException {
Date testContent = new Date();
SqlLobValue lob = new SqlLobValue("bla".getBytes());
try {
lob.setTypeValue(ps, 1, Types.CLOB, "test");
fail("IllegalArgumentException should have been thrown");
}
catch (IllegalArgumentException e) {
// expected
}
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
}
@Test
public void testOtherConstructors() throws SQLException {
// a bit BS, but we need to test them, as long as they don't throw exceptions
SqlLobValue lob = new SqlLobValue("bla");
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
try {
lob = new SqlLobValue("bla".getBytes());
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
fail("IllegalArgumentException should have been thrown");
}
catch (IllegalArgumentException e) {
@@ -226,27 +153,27 @@ public class SqlLobValueTests extends TestCase {
}
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
lob = new SqlLobValue(new InputStreamReader(
new ByteArrayInputStream("bla".getBytes())), 3);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream(
"bla".getBytes())), 3);
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
// same for BLOB
lob = new SqlLobValue("bla");
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
lob = new SqlLobValue("bla".getBytes());
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
lob = new SqlLobValue(new InputStreamReader(
new ByteArrayInputStream("bla".getBytes())), 3);
lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream(
"bla".getBytes())), 3);
try {
lob.setTypeValue(ps, 1, Types.BLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
fail("IllegalArgumentException should have been thrown");
}
catch (IllegalArgumentException e) {
@@ -254,28 +181,20 @@ public class SqlLobValueTests extends TestCase {
}
}
public void testCorrectCleanup() throws SQLException {
creator.setClobAsString(ps, 1, "Bla");
creator.close();
replay();
@Test
public void testCorrectCleanup() throws SQLException {
SqlLobValue lob = new SqlLobValue("Bla", handler);
lob.setTypeValue(ps, 1, Types.CLOB, "test");
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
lob.cleanup();
lobCreatorControl.verify();
verify(creator).setClobAsString(preparedStatement, 1, "Bla");
verify(creator).close();
}
@Test
public void testOtherSqlType() throws SQLException {
replay();
SqlLobValue lob = new SqlLobValue("Bla", handler);
try {
lob.setTypeValue(ps, 1, Types.SMALLINT, "test");
fail("IllegalArgumentException should have been thrown");
}
catch (IllegalArgumentException e) {
// expected
}
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test");
}
}

View File

@@ -16,6 +16,19 @@
package org.springframework.jdbc.datasource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
@@ -23,15 +36,16 @@ import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookup;
import org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter;
@@ -49,66 +63,73 @@ import org.springframework.transaction.support.TransactionTemplate;
* @author Juergen Hoeller
* @since 17.10.2005
*/
public class DataSourceJtaTransactionTests extends TestCase {
public class DataSourceJtaTransactionTests {
private Connection connection;
private DataSource dataSource;
private UserTransaction userTransaction;
private TransactionManager transactionManager;
private Transaction transaction;
@Before
public void setup() throws Exception {
connection =mock(Connection.class);
dataSource = mock(DataSource.class);
userTransaction = mock(UserTransaction.class);
transactionManager = mock(TransactionManager.class);
transaction = mock(Transaction.class);
given(dataSource.getConnection()).willReturn(connection);
}
@After
public void verifyTransactionSynchronizationManagerState() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
@Test
public void testJtaTransactionCommit() throws Exception {
doTestJtaTransaction(false);
}
@Test
public void testJtaTransactionRollback() throws Exception {
doTestJtaTransaction(true);
}
private void doTestJtaTransaction(final boolean rollback) throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
ut.begin();
utControl.setVoidCallable(1);
if (rollback) {
ut.rollback();
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,Status.STATUS_ACTIVE);
}
else {
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
ut.commit();
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
utControl.setVoidCallable(1);
utControl.replay();
MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
dsControl.replay();
JtaTransactionManager ptm = new JtaTransactionManager(ut);
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
TransactionTemplate tt = new TransactionTemplate(ptm);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(ds);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
DataSourceUtils.releaseConnection(c, ds);
Connection c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
c = DataSourceUtils.getConnection(ds);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
DataSourceUtils.releaseConnection(c, ds);
c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
if (rollback) {
status.setRollbackOnly();
@@ -116,49 +137,61 @@ public class DataSourceJtaTransactionTests extends TestCase {
}
});
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
dsControl.verify();
conControl.verify();
utControl.verify();
verify(userTransaction).begin();
if (rollback) {
verify(userTransaction).rollback();
}
verify(connection).close();
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false);
}
@Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true);
}
@@ -167,57 +200,22 @@ public class DataSourceJtaTransactionTests extends TestCase {
final boolean rollback, final boolean openOuterConnection, final boolean accessAfterResume,
final boolean useTransactionAwareDataSource) throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.begin();
utControl.setVoidCallable(1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 16);
tm.suspend();
tmControl.setReturnValue(tx, 5);
ut.begin();
utControl.setVoidCallable(5);
ut.commit();
utControl.setVoidCallable(5);
tm.resume(tx);
tmControl.setVoidCallable(5);
given(transactionManager.suspend()).willReturn(transaction);
if (rollback) {
ut.rollback();
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE);
}
else {
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
ut.commit();
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
utControl.setVoidCallable(1);
utControl.replay();
tmControl.replay();
final MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
final MockControl conControl = MockControl.createControl(Connection.class);
final Connection con = (Connection) conControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(true, 1);
if (!openOuterConnection) {
con.close();
conControl.setVoidCallable(1);
}
conControl.replay();
dsControl.replay();
given(connection.isReadOnly()).willReturn(true);
final DataSource dsToUse = useTransactionAwareDataSource ?
new TransactionAwareDataSourceProxy(ds) : ds;
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
final TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
@@ -255,19 +253,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue("Is new transaction", status.isNewTransaction());
try {
dsControl.verify();
conControl.verify();
dsControl.reset();
conControl.reset();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(true, 1);
con.close();
conControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
Connection c = DataSourceUtils.getConnection(dsToUse);
c.isReadOnly();
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
@@ -290,21 +275,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
if (accessAfterResume) {
try {
if (!openOuterConnection) {
dsControl.verify();
dsControl.reset();
ds.getConnection();
dsControl.setReturnValue(con, 1);
dsControl.replay();
}
conControl.verify();
conControl.reset();
con.isReadOnly();
conControl.setReturnValue(true, 1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
if (!openOuterConnection) {
c = DataSourceUtils.getConnection(dsToUse);
}
@@ -322,15 +292,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
else {
if (openOuterConnection) {
try {
conControl.verify();
conControl.reset();
con.close();
conControl.setVoidCallable(1);
conControl.replay();
}
catch (SQLException ex) {
}
DataSourceUtils.releaseConnection(c, dsToUse);
}
}
@@ -339,24 +300,38 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
dsControl.verify();
conControl.verify();
utControl.verify();
tmControl.verify();
verify(userTransaction, times(6)).begin();
verify(transactionManager, times(5)).resume(transaction);
if(rollback) {
verify(userTransaction, times(5)).commit();
verify(userTransaction).rollback();
} else {
verify(userTransaction, times(6)).commit();
}
if(accessAfterResume && !openOuterConnection) {
verify(connection, times(7)).close();
}
else {
verify(connection, times(6)).close();
}
}
@Test
public void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true);
}
@@ -364,57 +339,28 @@ public class DataSourceJtaTransactionTests extends TestCase {
private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(
final boolean requiresNew, boolean notSupported) throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
if (notSupported) {
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
tm.suspend();
tmControl.setReturnValue(tx, 1);
given(userTransaction.getStatus()).willReturn(
Status.STATUS_ACTIVE,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
given(transactionManager.suspend()).willReturn(transaction);
}
else {
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
}
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.begin();
utControl.setVoidCallable(1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
ut.commit();
utControl.setVoidCallable(1);
if (notSupported) {
tm.resume(tx);
tmControl.setVoidCallable(1);
}
utControl.replay();
tmControl.replay();
txControl.replay();
final MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
final MockControl con1Control = MockControl.createControl(Connection.class);
final Connection con1 = (Connection) con1Control.getMock();
final MockControl con2Control = MockControl.createControl(Connection.class);
final Connection con2 = (Connection) con2Control.getMock();
ds.getConnection();
dsControl.setReturnValue(con1, 1);
ds.getConnection();
dsControl.setReturnValue(con2, 1);
con2.close();
con2Control.setVoidCallable(1);
con1.close();
con1Control.setVoidCallable(1);
dsControl.replay();
con1Control.replay();
con2Control.replay();
final DataSource dataSource = mock(DataSource.class);
final Connection connection1 = mock(Connection.class);
final Connection connection2 = mock(Connection.class);
given(dataSource.getConnection()).willReturn(connection1, connection2);
final JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(notSupported ?
TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS);
@@ -426,8 +372,8 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(con1, DataSourceUtils.getConnection(ds));
assertSame(con1, DataSourceUtils.getConnection(ds));
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
TransactionTemplate tt2 = new TransactionTemplate(ptm);
tt2.setPropagationBehavior(requiresNew ?
@@ -438,55 +384,63 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(con2, DataSourceUtils.getConnection(ds));
assertSame(con2, DataSourceUtils.getConnection(ds));
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
}
});
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
assertSame(con1, DataSourceUtils.getConnection(ds));
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
}
});
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
utControl.verify();
tmControl.verify();
txControl.verify();
dsControl.verify();
con1Control.verify();
con2Control.verify();
verify(userTransaction).begin();
verify(userTransaction).commit();
if (notSupported) {
verify(transactionManager).resume(transaction);
}
verify(connection2).close();
verify(connection1).close();
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true);
}
@Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true);
}
@@ -494,57 +448,27 @@ public class DataSourceJtaTransactionTests extends TestCase {
private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
final boolean openOuterConnection, final boolean useTransactionAwareDataSource) throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
MockControl tmControl = MockControl.createControl(TransactionManager.class);
TransactionManager tm = (TransactionManager) tmControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.begin();
utControl.setVoidCallable(1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
if (suspendException) {
tm.suspend();
tmControl.setThrowable(new SystemException(), 1);
given(transactionManager.suspend()).willThrow(new SystemException());
}
else {
tm.suspend();
tmControl.setReturnValue(tx, 1);
ut.begin();
utControl.setThrowable(new SystemException(), 1);
tm.resume(tx);
tmControl.setVoidCallable(1);
given(transactionManager.suspend()).willReturn(transaction);
willThrow(new SystemException()).given(userTransaction).begin();
}
ut.rollback();
utControl.setVoidCallable(1);
utControl.replay();
tmControl.replay();
final MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
final MockControl conControl = MockControl.createControl(Connection.class);
final Connection con = (Connection) conControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(true, 1);
if (!openOuterConnection || useTransactionAwareDataSource) {
con.close();
conControl.setVoidCallable(1);
}
conControl.replay();
dsControl.replay();
given(connection.isReadOnly()).willReturn(true);
final DataSource dsToUse = useTransactionAwareDataSource ?
new TransactionAwareDataSourceProxy(ds) : ds;
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
if (dsToUse instanceof TransactionAwareDataSourceProxy) {
((TransactionAwareDataSourceProxy) dsToUse).setReobtainTransactionalConnections(true);
}
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
final TransactionTemplate tt = new TransactionTemplate(ptm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
@@ -581,50 +505,19 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is new transaction", status.isNewTransaction());
try {
dsControl.verify();
conControl.verify();
dsControl.reset();
conControl.reset();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.close();
conControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
}
catch (SQLException ex) {
}
c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
}
finally {
if (openOuterConnection) {
try {
dsControl.verify();
dsControl.reset();
conControl.verify();
conControl.reset();
if (useTransactionAwareDataSource) {
ds.getConnection();
dsControl.setReturnValue(con, 1);
}
con.isReadOnly();
conControl.setReturnValue(true, 1);
con.close();
conControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
c.isReadOnly();
DataSourceUtils.releaseConnection(c, dsToUse);
}
@@ -643,26 +536,30 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
dsControl.verify();
conControl.verify();
utControl.verify();
tmControl.verify();
verify(userTransaction).begin();
if(suspendException) {
verify(userTransaction).rollback();
}
if (suspendException) {
verify(connection, atLeastOnce()).close();
}
else {
verify(connection, never()).close();
}
}
@Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
@SuppressWarnings("serial")
JtaTransactionManager ptm = new JtaTransactionManager(ut) {
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {
@Override
protected void doRegisterAfterCompletionWithJtaTransaction(
JtaTransactionObject txObject, final List synchronizations) {
JtaTransactionObject txObject,
final List<TransactionSynchronization> synchronizations)
throws RollbackException, SystemException {
Thread async = new Thread() {
@Override
public void run() {
@@ -679,24 +576,11 @@ public class DataSourceJtaTransactionTests extends TestCase {
}
};
TransactionTemplate tt = new TransactionTemplate(ptm);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
for (int i = 0; i < 3; i++) {
utControl.reset();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
utControl.replay();
dsControl.reset();
conControl.reset();
ds.getConnection();
dsControl.setReturnValue(con, 1);
con.close();
conControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
final boolean releaseCon = (i != 1);
tt.execute(new TransactionCallbackWithoutResult() {
@@ -705,76 +589,44 @@ public class DataSourceJtaTransactionTests extends TestCase {
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Is existing transaction", !status.isNewTransaction());
Connection c = DataSourceUtils.getConnection(ds);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
DataSourceUtils.releaseConnection(c, ds);
Connection c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
DataSourceUtils.releaseConnection(c, dataSource);
c = DataSourceUtils.getConnection(ds);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
c = DataSourceUtils.getConnection(dataSource);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
if (releaseCon) {
DataSourceUtils.releaseConnection(c, ds);
DataSourceUtils.releaseConnection(c, dataSource);
}
}
});
if (!releaseCon) {
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(ds));
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(dataSource));
}
else {
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
}
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
conControl.verify();
dsControl.verify();
utControl.verify();
}
verify(connection, times(3)).close();
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
ut.begin();
utControl.setVoidCallable(1);
ut.commit();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
ut.begin();
utControl.setVoidCallable(1);
ut.commit();
utControl.setVoidCallable(1);
utControl.replay();
MockControl ds1Control = MockControl.createControl(DataSource.class);
final DataSource ds1 = (DataSource) ds1Control.getMock();
MockControl con1Control = MockControl.createControl(Connection.class);
final Connection con1 = (Connection) con1Control.getMock();
ds1.getConnection();
ds1Control.setReturnValue(con1, 1);
con1.close();
con1Control.setVoidCallable(1);
ds1.getConnection();
ds1Control.setReturnValue(con1, 1);
con1.setReadOnly(true);
con1Control.setVoidCallable(1);
con1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
con1Control.setVoidCallable(1);
con1.close();
con1Control.setVoidCallable(1);
con1Control.replay();
ds1Control.replay();
given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE,
Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE,
Status.STATUS_ACTIVE);
final IsolationLevelDataSourceAdapter dsToUse = new IsolationLevelDataSourceAdapter();
dsToUse.setTargetDataSource(ds1);
dsToUse.setTargetDataSource(dataSource);
dsToUse.afterPropertiesSet();
JtaTransactionManager ptm = new JtaTransactionManager(ut);
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
ptm.setAllowCustomIsolationLevels(true);
TransactionTemplate tt = new TransactionTemplate(ptm);
@@ -783,7 +635,7 @@ public class DataSourceJtaTransactionTests extends TestCase {
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(con1, c);
assertSame(connection, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
@@ -795,84 +647,57 @@ public class DataSourceJtaTransactionTests extends TestCase {
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(con1, c);
assertSame(connection, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
ds1Control.verify();
con1Control.verify();
utControl.verify();
verify(userTransaction, times(2)).begin();
verify(userTransaction, times(2)).commit();
verify(connection).setReadOnly(true);
verify(connection).setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
verify(connection, times(2)).close();
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(false);
}
@Test
public void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(true);
}
private void doTestJtaTransactionWithIsolationLevelDataSourceRouter(boolean dataSourceLookup) throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
ut.begin();
utControl.setVoidCallable(1);
ut.commit();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.getStatus();
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
ut.begin();
utControl.setVoidCallable(1);
ut.commit();
utControl.setVoidCallable(1);
utControl.replay();
given( userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
MockControl ds1Control = MockControl.createControl(DataSource.class);
final DataSource ds1 = (DataSource) ds1Control.getMock();
MockControl con1Control = MockControl.createControl(Connection.class);
final Connection con1 = (Connection) con1Control.getMock();
ds1.getConnection();
ds1Control.setReturnValue(con1, 1);
con1.close();
con1Control.setVoidCallable(1);
con1Control.replay();
ds1Control.replay();
final DataSource dataSource1 = mock(DataSource.class);
final Connection connection1 = mock(Connection.class);
given(dataSource1.getConnection()).willReturn(connection1);
MockControl ds2Control = MockControl.createControl(DataSource.class);
final DataSource ds2 = (DataSource) ds2Control.getMock();
MockControl con2Control = MockControl.createControl(Connection.class);
final Connection con2 = (Connection) con2Control.getMock();
ds2.getConnection();
ds2Control.setReturnValue(con2, 1);
con2.close();
con2Control.setVoidCallable(1);
con2Control.replay();
ds2Control.replay();
final DataSource dataSource2 = mock(DataSource.class);
final Connection connection2 = mock(Connection.class);
given(dataSource2.getConnection()).willReturn(connection2);
final IsolationLevelDataSourceRouter dsToUse = new IsolationLevelDataSourceRouter();
Map targetDataSources = new HashMap();
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
if (dataSourceLookup) {
targetDataSources.put("ISOLATION_REPEATABLE_READ", "ds2");
dsToUse.setDefaultTargetDataSource("ds1");
StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
beanFactory.addBean("ds1", ds1);
beanFactory.addBean("ds2", ds2);
beanFactory.addBean("ds1", dataSource1);
beanFactory.addBean("ds2", dataSource2);
dsToUse.setDataSourceLookup(new BeanFactoryDataSourceLookup(beanFactory));
}
else {
targetDataSources.put("ISOLATION_REPEATABLE_READ", ds2);
dsToUse.setDefaultTargetDataSource(ds1);
targetDataSources.put("ISOLATION_REPEATABLE_READ", dataSource2);
dsToUse.setDefaultTargetDataSource(dataSource1);
}
dsToUse.setTargetDataSources(targetDataSources);
dsToUse.afterPropertiesSet();
JtaTransactionManager ptm = new JtaTransactionManager(ut);
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
ptm.setAllowCustomIsolationLevels(true);
TransactionTemplate tt = new TransactionTemplate(ptm);
@@ -881,7 +706,7 @@ public class DataSourceJtaTransactionTests extends TestCase {
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(con1, c);
assertSame(connection1, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
@@ -892,26 +717,14 @@ public class DataSourceJtaTransactionTests extends TestCase {
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
Connection c = DataSourceUtils.getConnection(dsToUse);
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
assertSame(con2, c);
assertSame(connection2, c);
DataSourceUtils.releaseConnection(c, dsToUse);
}
});
ds1Control.verify();
con1Control.verify();
ds2Control.verify();
con2Control.verify();
utControl.verify();
verify(userTransaction, times(2)).begin();
verify(userTransaction, times(2)).commit();
verify(connection1).close();
verify(connection2).close();
}
@Override
protected void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
}

View File

@@ -18,6 +18,9 @@ package org.springframework.jdbc.datasource;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
@@ -25,7 +28,6 @@ import java.sql.Connection;
import javax.sql.DataSource;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
@@ -42,100 +44,78 @@ public class DelegatingDataSourceTest {
@Before
public void setup() {
this.delegate = EasyMock.createMock(DataSource.class);
this.delegate = mock(DataSource.class);
this.dataSource = new DelegatingDataSource(delegate);
}
@Test
public void shouldDelegateGetConnection() throws Exception {
Connection connection = EasyMock.createMock(Connection.class);
EasyMock.expect(delegate.getConnection()).andReturn(connection);
EasyMock.replay(delegate);
Connection connection = mock(Connection.class);
given(delegate.getConnection()).willReturn(connection);
assertThat(dataSource.getConnection(), is(connection));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateGetConnectionWithUsernameAndPassword() throws Exception {
Connection connection = EasyMock.createMock(Connection.class);
Connection connection = mock(Connection.class);
String username = "username";
String password = "password";
EasyMock.expect(delegate.getConnection(username, password)).andReturn(connection);
EasyMock.replay(delegate);
given(delegate.getConnection(username, password)).willReturn(connection);
assertThat(dataSource.getConnection(username, password), is(connection));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateGetLogWriter() throws Exception {
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
EasyMock.expect(delegate.getLogWriter()).andReturn(writer);
EasyMock.replay(delegate);
given(delegate.getLogWriter()).willReturn(writer);
assertThat(dataSource.getLogWriter(), is(writer));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateSetLogWriter() throws Exception {
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
delegate.setLogWriter(writer);
EasyMock.expectLastCall();
EasyMock.replay(delegate);
dataSource.setLogWriter(writer);
EasyMock.verify(delegate);
verify(delegate).setLogWriter(writer);
}
@Test
public void shouldDelegateGetLoginTimeout() throws Exception {
int timeout = 123;
EasyMock.expect(delegate.getLoginTimeout()).andReturn(timeout);
EasyMock.replay(delegate);
given(delegate.getLoginTimeout()).willReturn(timeout);
assertThat(dataSource.getLoginTimeout(), is(timeout));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateSetLoginTimeoutWithSeconds() throws Exception {
int timeout = 123;
delegate.setLoginTimeout(timeout);
EasyMock.expectLastCall();
EasyMock.replay(delegate);
dataSource.setLoginTimeout(timeout);
EasyMock.verify(delegate);
verify(delegate).setLoginTimeout(timeout);
}
@Test
public void shouldDelegateUnwrapWithoutImplementing() throws Exception {
ExampleWrapper wrapper = EasyMock.createMock(ExampleWrapper.class);
EasyMock.expect(delegate.unwrap(ExampleWrapper.class)).andReturn(wrapper);
EasyMock.replay(delegate);
ExampleWrapper wrapper = mock(ExampleWrapper.class);
given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper);
assertThat(dataSource.unwrap(ExampleWrapper.class), is(wrapper));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateUnwrapImplementing() throws Exception {
dataSource = new DelegatingDataSourceWithWrapper();
EasyMock.replay(delegate);
assertThat(dataSource.unwrap(ExampleWrapper.class),
is((ExampleWrapper) dataSource));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateIsWrapperForWithoutImplementing() throws Exception {
EasyMock.expect(delegate.isWrapperFor(ExampleWrapper.class)).andReturn(true);
EasyMock.replay(delegate);
given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true);
assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true));
EasyMock.verify(delegate);
}
@Test
public void shouldDelegateIsWrapperForImplementing() throws Exception {
dataSource = new DelegatingDataSourceWithWrapper();
EasyMock.replay(delegate);
assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true));
EasyMock.verify(delegate);
}
public static interface ExampleWrapper {

View File

@@ -16,34 +16,34 @@
package org.springframework.jdbc.datasource;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import java.sql.Connection;
import java.util.Properties;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
/**
* @author Rod Johnson
*/
public class DriverManagerDataSourceTests extends TestCase {
public class DriverManagerDataSourceTests {
private Connection connection = mock(Connection.class);
@Test
public void testStandardUsage() throws Exception {
final String jdbcUrl = "url";
final String uname = "uname";
final String pwd = "pwd";
MockControl ctrlConnection =
MockControl.createControl(Connection.class);
final Connection mockConnection = (Connection) ctrlConnection.getMock();
ctrlConnection.replay();
class TestDriverManagerDataSource extends DriverManagerDataSource {
@Override
protected Connection getConnectionFromDriverManager(String url, Properties props) {
assertEquals(jdbcUrl, url);
assertEquals(uname, props.getProperty("user"));
assertEquals(pwd, props.getProperty("password"));
return mockConnection;
return connection;
}
}
@@ -54,15 +54,14 @@ public class DriverManagerDataSourceTests extends TestCase {
ds.setPassword(pwd);
Connection actualCon = ds.getConnection();
assertTrue(actualCon == mockConnection);
assertTrue(actualCon == connection);
assertTrue(ds.getUrl().equals(jdbcUrl));
assertTrue(ds.getPassword().equals(pwd));
assertTrue(ds.getUsername().equals(uname));
ctrlConnection.verify();
}
@Test
public void testUsageWithConnectionProperties() throws Exception {
final String jdbcUrl = "url";
@@ -72,11 +71,6 @@ public class DriverManagerDataSourceTests extends TestCase {
connProps.setProperty("user", "uname");
connProps.setProperty("password", "pwd");
MockControl ctrlConnection =
MockControl.createControl(Connection.class);
final Connection mockConnection = (Connection) ctrlConnection.getMock();
ctrlConnection.replay();
class TestDriverManagerDataSource extends DriverManagerDataSource {
@Override
protected Connection getConnectionFromDriverManager(String url, Properties props) {
@@ -85,7 +79,7 @@ public class DriverManagerDataSourceTests extends TestCase {
assertEquals("pwd", props.getProperty("password"));
assertEquals("myValue", props.getProperty("myProp"));
assertEquals("yourValue", props.getProperty("yourProp"));
return mockConnection;
return connection;
}
}
@@ -95,13 +89,12 @@ public class DriverManagerDataSourceTests extends TestCase {
ds.setConnectionProperties(connProps);
Connection actualCon = ds.getConnection();
assertTrue(actualCon == mockConnection);
assertTrue(actualCon == connection);
assertTrue(ds.getUrl().equals(jdbcUrl));
ctrlConnection.verify();
}
@Test
public void testUsageWithConnectionPropertiesAndUserCredentials() throws Exception {
final String jdbcUrl = "url";
final String uname = "uname";
@@ -113,11 +106,6 @@ public class DriverManagerDataSourceTests extends TestCase {
connProps.setProperty("user", "uname2");
connProps.setProperty("password", "pwd2");
MockControl ctrlConnection =
MockControl.createControl(Connection.class);
final Connection mockConnection = (Connection) ctrlConnection.getMock();
ctrlConnection.replay();
class TestDriverManagerDataSource extends DriverManagerDataSource {
@Override
protected Connection getConnectionFromDriverManager(String url, Properties props) {
@@ -126,7 +114,7 @@ public class DriverManagerDataSourceTests extends TestCase {
assertEquals(pwd, props.getProperty("password"));
assertEquals("myValue", props.getProperty("myProp"));
assertEquals("yourValue", props.getProperty("yourProp"));
return mockConnection;
return connection;
}
}
@@ -138,15 +126,14 @@ public class DriverManagerDataSourceTests extends TestCase {
ds.setConnectionProperties(connProps);
Connection actualCon = ds.getConnection();
assertTrue(actualCon == mockConnection);
assertTrue(actualCon == connection);
assertTrue(ds.getUrl().equals(jdbcUrl));
assertTrue(ds.getPassword().equals(pwd));
assertTrue(ds.getUsername().equals(uname));
ctrlConnection.verify();
}
@Test
public void testInvalidClassName() throws Exception {
String bogusClassName = "foobar";
DriverManagerDataSource ds = new DriverManagerDataSource();

View File

@@ -16,68 +16,58 @@
package org.springframework.jdbc.datasource;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
/**
* @author Juergen Hoeller
* @since 28.05.2004
*/
public class UserCredentialsDataSourceAdapterTests extends TestCase {
public class UserCredentialsDataSourceAdapterTests {
@Test
public void testStaticCredentials() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ds.getConnection("user", "pw");
dsControl.setReturnValue(con);
dsControl.replay();
conControl.replay();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
given(dataSource.getConnection("user", "pw")).willReturn(connection);
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
adapter.setTargetDataSource(ds);
adapter.setTargetDataSource(dataSource);
adapter.setUsername("user");
adapter.setPassword("pw");
assertEquals(con, adapter.getConnection());
assertEquals(connection, adapter.getConnection());
}
@Test
public void testNoCredentials() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con);
dsControl.replay();
conControl.replay();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
given(dataSource.getConnection()).willReturn(connection);
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
adapter.setTargetDataSource(ds);
assertEquals(con, adapter.getConnection());
adapter.setTargetDataSource(dataSource);
assertEquals(connection, adapter.getConnection());
}
@Test
public void testThreadBoundCredentials() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ds.getConnection("user", "pw");
dsControl.setReturnValue(con);
dsControl.replay();
conControl.replay();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
given(dataSource.getConnection("user", "pw")).willReturn(connection);
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
adapter.setTargetDataSource(ds);
adapter.setTargetDataSource(dataSource);
adapter.setCredentialsForCurrentThread("user", "pw");
try {
assertEquals(con, adapter.getConnection());
assertEquals(connection, adapter.getConnection());
}
finally {
adapter.removeCredentialsFromCurrentThread();

View File

@@ -17,15 +17,14 @@
package org.springframework.jdbc.datasource.init;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.SQLException;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Test;
import org.springframework.core.io.ClassRelativeResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
@@ -257,15 +256,9 @@ public class DatabasePopulatorTests {
public void usesBoundConnectionIfAvailable() throws SQLException {
TransactionSynchronizationManager.initSynchronization();
Connection connection = DataSourceUtils.getConnection(db);
DatabasePopulator populator = EasyMock.createMock(DatabasePopulator.class);
populator.populate(connection);
EasyMock.expectLastCall();
EasyMock.replay(populator);
DatabasePopulator populator = mock(DatabasePopulator.class);
DatabasePopulatorUtils.execute(populator, db);
EasyMock.verify(populator);
verify(populator).populate(connection);
}
/**

View File

@@ -16,8 +16,11 @@
package org.springframework.jdbc.datasource.lookup;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import javax.sql.DataSource;
@@ -37,12 +40,10 @@ public class BeanFactoryDataSourceLookupTests {
@Test
public void testLookupSunnyDay() {
BeanFactory beanFactory = createMock(BeanFactory.class);
BeanFactory beanFactory = mock(BeanFactory.class);
StubDataSource expectedDataSource = new StubDataSource();
expect(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).andReturn(expectedDataSource);
replay(beanFactory);
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willReturn(expectedDataSource);
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
lookup.setBeanFactory(beanFactory);
@@ -50,27 +51,21 @@ public class BeanFactoryDataSourceLookupTests {
assertNotNull("A DataSourceLookup implementation must *never* return null from " +
"getDataSource(): this one obviously (and incorrectly) is", dataSource);
assertSame(expectedDataSource, dataSource);
verify(beanFactory);
}
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
final BeanFactory beanFactory = createMock(BeanFactory.class);
final BeanFactory beanFactory = mock(BeanFactory.class);
expect(
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)
).andThrow(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
replay(beanFactory);
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
DataSource.class, String.class));
try {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
lookup.getDataSource(DATASOURCE_BEAN_NAME);
fail("should have thrown DataSourceLookupFailureException");
} catch (DataSourceLookupFailureException ex) { /* expected */ }
verify(beanFactory);
}
@Test(expected=IllegalStateException.class)

View File

@@ -16,30 +16,35 @@
package org.springframework.jdbc.object;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.Types;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource;
import org.springframework.jdbc.AbstractJdbcTests;
import org.junit.Test;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Juergen Hoeller
* @since 22.02.2005
*/
public class BatchSqlUpdateTests extends AbstractJdbcTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
public class BatchSqlUpdateTests {
@Test
public void testBatchUpdateWithExplicitFlush() throws Exception {
doTestBatchUpdate(false);
}
@Test
public void testBatchUpdateWithFlushThroughBatchSize() throws Exception {
doTestBatchUpdate(true);
}
@@ -49,42 +54,19 @@ public class BatchSqlUpdateTests extends AbstractJdbcTests {
final int[] ids = new int[] { 100, 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, new Integer(ids[0]), Types.INTEGER);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.setObject(1, new Integer(ids[1]), Types.INTEGER);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeBatch();
ctrlPreparedStatement.setReturnValue(rowsAffected);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
Connection connection = mock(Connection.class);
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
given(preparedStatement.getConnection()).willReturn(connection);
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
mockDatabaseMetaData.supportsBatchUpdates();
ctrlDatabaseMetaData.setReturnValue(true);
DatabaseMetaData mockDatabaseMetaData = mock(DatabaseMetaData.class);
given(mockDatabaseMetaData.supportsBatchUpdates()).willReturn(true);
given(connection.prepareStatement(sql)).willReturn(preparedStatement);
given(connection.getMetaData()).willReturn(mockDatabaseMetaData);
mockConnection.prepareStatement(sql);
ctrlConnection.setReturnValue(mockPreparedStatement);
mockConnection.getMetaData();
ctrlConnection.setReturnValue(mockDatabaseMetaData, 1);
ctrlPreparedStatement.replay();
ctrlDatabaseMetaData.replay();
replay();
BatchSqlUpdate update = new BatchSqlUpdate(mockDataSource, sql);
BatchSqlUpdate update = new BatchSqlUpdate(dataSource, sql);
update.declareParameter(new SqlParameter(Types.INTEGER));
if (flushThroughBatchSize) {
update.setBatchSize(2);
@@ -122,8 +104,9 @@ public class BatchSqlUpdateTests extends AbstractJdbcTests {
update.reset();
assertEquals(0, update.getRowsAffected().length);
ctrlPreparedStatement.verify();
ctrlDatabaseMetaData.verify();
verify(preparedStatement).setObject(1, new Integer(ids[0]), Types.INTEGER);
verify(preparedStatement).setObject(1, new Integer(ids[1]), Types.INTEGER);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement).close();
}
}

View File

@@ -16,10 +16,13 @@
package org.springframework.jdbc.object;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -28,119 +31,85 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.easymock.EasyMock;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.runners.JUnit4;
import org.junit.runner.RunWith;
import javax.sql.DataSource;
import org.springframework.jdbc.AbstractJdbcTests;
import org.springframework.jdbc.Customer;
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.Customer;
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
/**
* @author Thomas Risberg
*/
@RunWith(JUnit4.class)
public class GenericSqlQueryTests extends AbstractJdbcTests {
public class GenericSqlQueryTests {
private static final String SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED =
"select id, forename from custmr where id = ? and country = ?";
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private BeanFactory beanFactory;
private PreparedStatement mockPreparedStatement;
private ResultSet mockResultSet;
private Connection connection;
private BeanFactory bf;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
mockPreparedStatement = createMock(PreparedStatement.class);
mockResultSet = createMock(ResultSet.class);
this.bf = new XmlBeanFactory(
this.beanFactory = new XmlBeanFactory(
new ClassPathResource("org/springframework/jdbc/object/GenericSqlQueryTests-context.xml"));
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
testDataSource.setTarget(mockDataSource);
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
if (shouldVerify()) {
EasyMock.verify(mockPreparedStatement);
EasyMock.verify(mockResultSet);
}
}
@Override
protected void replay() {
super.replay();
EasyMock.replay(mockPreparedStatement);
EasyMock.replay(mockResultSet);
DataSource dataSource = mock(DataSource.class);
this.connection = mock(Connection.class);
this.preparedStatement = mock(PreparedStatement.class);
this.resultSet = mock(ResultSet.class);
given(dataSource.getConnection()).willReturn(connection);
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) beanFactory.getBean("dataSource");
testDataSource.setTarget(dataSource);
}
@Test
public void testPlaceHoldersCustomerQuery() throws SQLException {
SqlQuery query = (SqlQuery) bf.getBean("queryWithPlaceHolders");
testCustomerQuery(query, false);
SqlQuery query = (SqlQuery) beanFactory.getBean("queryWithPlaceHolders");
doTestCustomerQuery(query, false);
}
@Test
public void testNamedParameterCustomerQuery() throws SQLException {
SqlQuery query = (SqlQuery) bf.getBean("queryWithNamedParameters");
testCustomerQuery(query, true);
SqlQuery query = (SqlQuery) beanFactory.getBean("queryWithNamedParameters");
doTestCustomerQuery(query, true);
}
private void testCustomerQuery(SqlQuery query, boolean namedParameters) throws SQLException {
expect(mockResultSet.next()).andReturn(true);
expect(mockResultSet.getInt("id")).andReturn(1);
expect(mockResultSet.getString("forename")).andReturn("rod");
expect(mockResultSet.next()).andReturn(false);
mockResultSet.close();
expectLastCall();
private void doTestCustomerQuery(SqlQuery query, boolean namedParameters) throws SQLException {
given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod");
given(resultSet.next()).willReturn(true, false);
given(preparedStatement.executeQuery()).willReturn(resultSet);
given(connection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED)).willReturn(preparedStatement);
mockPreparedStatement.setObject(1, new Integer(1), Types.INTEGER);
expectLastCall();
mockPreparedStatement.setString(2, "UK");
expectLastCall();
expect(mockPreparedStatement.executeQuery()).andReturn(mockResultSet);
if (debugEnabled) {
expect(mockPreparedStatement.getWarnings()).andReturn(null);
}
mockPreparedStatement.close();
expectLastCall();
mockConnection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
List l;
List queryResults;
if (namedParameters) {
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("id", new Integer(1));
params.put("country", "UK");
l = query.executeByNamedParam(params);
queryResults = query.executeByNamedParam(params);
}
else {
Object[] params = new Object[] {new Integer(1), "UK"};
l = query.execute(params);
queryResults = query.execute(params);
}
assertTrue("Customer was returned correctly", l.size() == 1);
Customer cust = (Customer) l.get(0);
assertTrue("Customer was returned correctly", queryResults.size() == 1);
Customer cust = (Customer) queryResults.get(0);
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
verify(resultSet).close();
verify(preparedStatement).setObject(1, new Integer(1), Types.INTEGER);
verify(preparedStatement).setString(2, "UK");
verify(preparedStatement).close();
}
}
}

View File

@@ -16,104 +16,63 @@
package org.springframework.jdbc.object;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import org.easymock.EasyMock;
import javax.sql.DataSource;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.runners.JUnit4;
import org.junit.runner.RunWith;
import org.springframework.jdbc.AbstractJdbcTests;
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
/**
* @author Thomas Risberg
*/
@RunWith(JUnit4.class)
public class GenericStoredProcedureTests extends AbstractJdbcTests {
public class GenericStoredProcedureTests {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
private CallableStatement mockCallable;
private BeanFactory bf;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
mockCallable = createMock(CallableStatement.class);
bf = new XmlBeanFactory(
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
testDataSource.setTarget(mockDataSource);
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
if (shouldVerify()) {
EasyMock.verify(mockCallable);
}
}
@Override
protected void replay() {
super.replay();
EasyMock.replay(mockCallable);
}
@Test
public void testAddInvoices() throws Exception {
BeanFactory bf = new XmlBeanFactory(
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));
Connection connection = mock(Connection.class);
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
CallableStatement callableStatement = mock(CallableStatement.class);
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
testDataSource.setTarget(dataSource);
mockCallable.setObject(1, new Integer(1106), Types.INTEGER);
expectLastCall();
mockCallable.setObject(2, new Integer(3), Types.INTEGER);
expectLastCall();
mockCallable.registerOutParameter(3, Types.INTEGER);
expectLastCall();
expect(mockCallable.execute()).andReturn(false);
expect(mockCallable.getUpdateCount()).andReturn(-1);
expect(mockCallable.getObject(3)).andReturn(new Integer(4));
if (debugEnabled) {
expect(mockCallable.getWarnings()).andReturn(null);
}
mockCallable.close();
expectLastCall();
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(3)).willReturn(new Integer(4));
mockConnection.prepareCall("{call " + "add_invoice" + "(?, ?, ?)}");
ctrlConnection.setReturnValue(mockCallable);
replay();
testAddInvoice(1106, 3);
}
private void testAddInvoice(final int amount, final int custid)
throws Exception {
given(connection.prepareCall("{call " + "add_invoice" + "(?, ?, ?)}")).willReturn(callableStatement);
StoredProcedure adder = (StoredProcedure) bf.getBean("genericProcedure");
Map<String, Object> in = new HashMap<String, Object>(2);
in.put("amount", amount);
in.put("custid", custid);
in.put("amount", 1106);
in.put("custid", 3);
Map out = adder.execute(in);
Integer id = (Integer) out.get("newid");
assertEquals(4, id.intValue());
verify(callableStatement).setObject(1, new Integer(1106), Types.INTEGER);
verify(callableStatement).setObject(2, new Integer(3), Types.INTEGER);
verify(callableStatement).registerOutParameter(3, Types.INTEGER);
verify(callableStatement).close();
}
}
}

View File

@@ -16,6 +16,12 @@
package org.springframework.jdbc.object;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@ -24,13 +30,15 @@ import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource;
import org.springframework.jdbc.AbstractJdbcTests;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
@@ -39,151 +47,103 @@ import org.springframework.jdbc.support.KeyHolder;
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class SqlUpdateTests extends AbstractJdbcTests {
public class SqlUpdateTests {
private static final String UPDATE =
"update seat_status set booking_id = null";
"update seat_status set booking_id = null";
private static final String UPDATE_INT =
"update seat_status set booking_id = null where performance_id = ?";
"update seat_status set booking_id = null where performance_id = ?";
private static final String UPDATE_INT_INT =
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
private static final String UPDATE_NAMED_PARAMETERS =
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
private static final String UPDATE_STRING =
"update seat_status set booking_id = null where name = ?";
"update seat_status set booking_id = null where name = ?";
private static final String UPDATE_OBJECTS =
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ? and name = ? and confirmed = ?";
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ? and name = ? and confirmed = ?";
private static final String INSERT_GENERATE_KEYS =
"insert into show (name) values(?)";
"insert into show (name) values(?)";
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockControl ctrlPreparedStatement;
private PreparedStatement mockPreparedStatement;
private MockControl ctrlResultSet;
private ResultSet mockResultSet;
private MockControl ctrlResultSetMetaData;
private ResultSetMetaData mockResultSetMetaData;
private DataSource dataSource;
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private ResultSetMetaData resultSetMetaData;
@Override
protected void setUp() throws Exception {
super.setUp();
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
@Before
public void setUp() throws Exception {
dataSource = mock(DataSource.class);
connection = mock(Connection.class);
preparedStatement = mock(PreparedStatement.class);
resultSet = mock(ResultSet.class);
resultSetMetaData = mock(ResultSetMetaData.class);
given(dataSource.getConnection()).willReturn(connection);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
if (shouldVerify()) {
ctrlPreparedStatement.verify();
}
@After
public void verifyClosed() throws Exception {
verify(preparedStatement).close();
verify(connection).close();
}
@Override
protected void replay() {
super.replay();
ctrlPreparedStatement.replay();
}
@Test
public void testUpdate() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
Updater pc = new Updater();
int rowsAffected = pc.run();
assertEquals(1, rowsAffected);
}
@Test
public void testUpdateInt() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_INT);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_INT)).willReturn(preparedStatement);
IntUpdater pc = new IntUpdater();
int rowsAffected = pc.run(1);
assertEquals(1, rowsAffected);
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
}
@Test
public void testUpdateIntInt() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_INT_INT);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement);
IntIntUpdater pc = new IntIntUpdater();
int rowsAffected = pc.run(1, 1);
assertEquals(1, rowsAffected);
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
verify(preparedStatement).setObject(2, 1, Types.NUMERIC);
}
@Test
public void testNamedParameterUpdateWithUnnamedDeclarations() throws SQLException {
doTestNamedParameterUpdate(false);
}
@Test
public void testNamedParameterUpdateWithNamedDeclarations() throws SQLException {
doTestNamedParameterUpdate(true);
}
private void doTestNamedParameterUpdate(final boolean namedDeclarations) throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
mockPreparedStatement.setObject(2, new Integer(1), Types.DECIMAL);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_INT_INT);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
private void doTestNamedParameterUpdate(final boolean namedDeclarations)
throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement);
class NamedParameterUpdater extends SqlUpdate {
public NamedParameterUpdater() {
setSql(UPDATE_NAMED_PARAMETERS);
setDataSource(mockDataSource);
setDataSource(dataSource);
if (namedDeclarations) {
declareParameter(new SqlParameter("priceId", Types.DECIMAL));
declareParameter(new SqlParameter("perfId", Types.NUMERIC));
@@ -196,9 +156,9 @@ public class SqlUpdateTests extends AbstractJdbcTests {
}
public int run(int performanceId, int type) {
Map params = new HashMap();
params.put("perfId", new Integer(performanceId));
params.put("priceId", new Integer(type));
Map<String, Integer> params = new HashMap<String, Integer>();
params.put("perfId", performanceId);
params.put("priceId", type);
return updateByNamedParam(params);
}
}
@@ -206,245 +166,134 @@ public class SqlUpdateTests extends AbstractJdbcTests {
NamedParameterUpdater pc = new NamedParameterUpdater();
int rowsAffected = pc.run(1, 1);
assertEquals(1, rowsAffected);
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
verify(preparedStatement).setObject(2, 1, Types.DECIMAL);
}
@Test
public void testUpdateString() throws SQLException {
mockPreparedStatement.setString(1, "rod");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_STRING);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_STRING)).willReturn(preparedStatement);
StringUpdater pc = new StringUpdater();
int rowsAffected = pc.run("rod");
assertEquals(1, rowsAffected);
verify(preparedStatement).setString(1, "rod");
}
@Test
public void testUpdateMixed() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC, 2);
mockPreparedStatement.setString(3, "rod");
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_OBJECTS);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
MixedUpdater pc = new MixedUpdater();
int rowsAffected = pc.run(1, 1, "rod", true);
assertEquals(1, rowsAffected);
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
verify(preparedStatement).setObject(2, 1, Types.NUMERIC, 2);
verify(preparedStatement).setString(3, "rod");
verify(preparedStatement).setObject(4, Boolean.TRUE, Types.BOOLEAN);
}
@Test
public void testUpdateAndGeneratedKeys() throws SQLException {
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
mockResultSetMetaData.getColumnCount();
ctrlResultSetMetaData.setReturnValue(1);
mockResultSetMetaData.getColumnLabel(1);
ctrlResultSetMetaData.setReturnValue("1", 2);
ctrlResultSet = MockControl.createControl(ResultSet.class);
mockResultSet = (ResultSet) ctrlResultSet.getMock();
mockResultSet.getMetaData();
ctrlResultSet.setReturnValue(mockResultSetMetaData);
mockResultSet.next();
ctrlResultSet.setReturnValue(true);
mockResultSet.getObject(1);
ctrlResultSet.setReturnValue(new Integer(11));
mockResultSet.next();
ctrlResultSet.setReturnValue(false);
mockResultSet.close();
ctrlResultSet.setVoidCallable();
mockPreparedStatement.setString(1, "rod");
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
mockPreparedStatement.getGeneratedKeys();
ctrlPreparedStatement.setReturnValue(mockResultSet);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(INSERT_GENERATE_KEYS, PreparedStatement.RETURN_GENERATED_KEYS);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
ctrlResultSet.replay();
ctrlResultSetMetaData.replay();
given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11);
given(preparedStatement.executeUpdate()).willReturn(1);
given(preparedStatement.getGeneratedKeys()).willReturn(resultSet);
given(connection.prepareStatement(INSERT_GENERATE_KEYS,
PreparedStatement.RETURN_GENERATED_KEYS)
).willReturn(preparedStatement);
GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
int rowsAffected = pc.run("rod", generatedKeyHolder);
assertEquals(1, rowsAffected);
assertEquals(1, generatedKeyHolder.getKeyList().size());
assertEquals(11, generatedKeyHolder.getKey().intValue());
verify(preparedStatement).setString(1, "rod");
verify(resultSet).close();
}
@Test
public void testUpdateConstructor() throws SQLException {
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
mockPreparedStatement.setString(3, "rod");
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(1);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE_OBJECTS);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
ConstructorUpdater pc = new ConstructorUpdater();
int rowsAffected = pc.run(1, 1, "rod", true);
assertEquals(1, rowsAffected);
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
verify(preparedStatement).setObject(2, 1, Types.NUMERIC);
verify(preparedStatement).setString(3, "rod");
verify(preparedStatement).setObject(4, Boolean.TRUE, Types.BOOLEAN);
}
@Test
public void testUnderMaxRows() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(3);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(3);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
MaxRowsUpdater pc = new MaxRowsUpdater();
int rowsAffected = pc.run();
assertEquals(3, rowsAffected);
}
@Test
public void testMaxRows() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(5);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(5);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
MaxRowsUpdater pc = new MaxRowsUpdater();
int rowsAffected = pc.run();
assertEquals(5, rowsAffected);
}
@Test
public void testOverMaxRows() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(8);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(8);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
MaxRowsUpdater pc = new MaxRowsUpdater();
try {
int rowsAffected = pc.run();
fail("Shouldn't continue when too many rows affected");
}
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
// OK
}
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
pc.run();
}
@Test
public void testRequiredRows() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(3);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(3);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
RequiredRowsUpdater pc = new RequiredRowsUpdater();
int rowsAffected = pc.run();
assertEquals(3, rowsAffected);
}
@Test
public void testNotRequiredRows() throws SQLException {
mockPreparedStatement.executeUpdate();
ctrlPreparedStatement.setReturnValue(2);
if (debugEnabled) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockConnection.prepareStatement(UPDATE);
ctrlConnection.setReturnValue(mockPreparedStatement);
replay();
given(preparedStatement.executeUpdate()).willReturn(2);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
RequiredRowsUpdater pc = new RequiredRowsUpdater();
try {
int rowsAffected = pc.run();
fail("Shouldn't continue when too many rows affected");
}
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
// OK
}
pc.run();
}
private class Updater extends SqlUpdate {
public Updater() {
setSql(UPDATE);
setDataSource(mockDataSource);
setDataSource(dataSource);
compile();
}
@@ -458,7 +307,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public IntUpdater() {
setSql(UPDATE_INT);
setDataSource(mockDataSource);
setDataSource(dataSource);
declareParameter(new SqlParameter(Types.NUMERIC));
compile();
}
@@ -473,7 +322,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public IntIntUpdater() {
setSql(UPDATE_INT_INT);
setDataSource(mockDataSource);
setDataSource(dataSource);
declareParameter(new SqlParameter(Types.NUMERIC));
declareParameter(new SqlParameter(Types.NUMERIC));
compile();
@@ -489,7 +338,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public StringUpdater() {
setSql(UPDATE_STRING);
setDataSource(mockDataSource);
setDataSource(dataSource);
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
@@ -504,7 +353,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public MixedUpdater() {
setSql(UPDATE_OBJECTS);
setDataSource(mockDataSource);
setDataSource(dataSource);
declareParameter(new SqlParameter(Types.NUMERIC));
declareParameter(new SqlParameter(Types.NUMERIC, 2));
declareParameter(new SqlParameter(Types.VARCHAR));
@@ -514,7 +363,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public int run(int performanceId, int type, String name, boolean confirmed) {
Object[] params =
new Object[] {new Integer(performanceId), new Integer(type), name,
new Object[] {performanceId, type, name,
new Boolean(confirmed)};
return update(params);
}
@@ -525,7 +374,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public GeneratedKeysUpdater() {
setSql(INSERT_GENERATE_KEYS);
setDataSource(mockDataSource);
setDataSource(dataSource);
declareParameter(new SqlParameter(Types.VARCHAR));
setReturnGeneratedKeys(true);
compile();
@@ -541,7 +390,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
private class ConstructorUpdater extends SqlUpdate {
public ConstructorUpdater() {
super(mockDataSource, UPDATE_OBJECTS,
super(dataSource, UPDATE_OBJECTS,
new int[] {Types.NUMERIC, Types.NUMERIC, Types.VARCHAR, Types.BOOLEAN });
compile();
}
@@ -549,7 +398,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public int run(int performanceId, int type, String name, boolean confirmed) {
Object[] params =
new Object[] {
new Integer(performanceId), new Integer(type), name, new Boolean(confirmed)};
performanceId, type, name, new Boolean(confirmed)};
return update(params);
}
}
@@ -559,7 +408,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public MaxRowsUpdater() {
setSql(UPDATE);
setDataSource(mockDataSource);
setDataSource(dataSource);
setMaxRowsAffected(5);
compile();
}
@@ -574,7 +423,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
public RequiredRowsUpdater() {
setSql(UPDATE);
setDataSource(mockDataSource);
setDataSource(dataSource);
setRequiredRowsAffected(3);
compile();
}

View File

@@ -16,6 +16,12 @@
package org.springframework.jdbc.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -23,9 +29,7 @@ import java.sql.Statement;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
@@ -35,50 +39,26 @@ import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIn
* @author Juergen Hoeller
* @since 27.02.2004
*/
public class DataFieldMaxValueIncrementerTests extends TestCase {
public class DataFieldMaxValueIncrementerTests {
private DataSource dataSource = mock(DataSource.class);
private Connection connection = mock(Connection.class);
private Statement statement = mock(Statement.class);
private ResultSet resultSet = mock(ResultSet.class);
@Test
public void testHsqlMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeUpdate("insert into myseq values(null)");
stmtControl.setReturnValue(1, 6);
stmt.executeQuery("select max(identity()) from myseq");
stmtControl.setReturnValue(rs, 6);
rs.next();
rsControl.setReturnValue(true, 6);
for (long i = 0; i < 6; i++) {
rs.getLong(1);
rsControl.setReturnValue(i);
}
rs.close();
rsControl.setVoidCallable(6);
stmt.executeUpdate("delete from myseq where seq < 2");
stmtControl.setReturnValue(1);
stmt.executeUpdate("delete from myseq where seq < 5");
stmtControl.setReturnValue(1);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
given(dataSource.getConnection()).willReturn(connection);
given(connection.createStatement()).willReturn(statement);
given(statement.executeUpdate("insert into myseq values(null)")).willReturn(1);
given(statement.executeQuery("select max(identity()) from myseq")).willReturn(resultSet);
given(resultSet.next()).willReturn(true);
given(resultSet.getLong(1)).willReturn(0L, 1L, 2L, 3L, 4L, 5L);
given(statement.executeUpdate("delete from myseq where seq < 2")).willReturn(1);
given(statement.executeUpdate("delete from myseq where seq < 5")).willReturn(1);
HsqlMaxValueIncrementer incrementer = new HsqlMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setDataSource(dataSource);
incrementer.setIncrementerName("myseq");
incrementer.setColumnName("seq");
incrementer.setCacheSize(3);
@@ -90,51 +70,22 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
assertEquals("002", incrementer.nextStringValue());
assertEquals(3, incrementer.nextIntValue());
assertEquals(4, incrementer.nextLongValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
verify(resultSet, times(6)).close();
verify(statement, times(2)).close();
verify(connection, times(2)).close();
}
@Test
public void testMySQLMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeUpdate("update myseq set seq = last_insert_id(seq + 2)");
stmtControl.setReturnValue(1, 2);
stmt.executeQuery("select last_insert_id()");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(2);
rs.getLong(1);
rsControl.setReturnValue(4);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
given(dataSource.getConnection()).willReturn(connection);
given(connection.createStatement()).willReturn(statement);
given(statement.executeUpdate("update myseq set seq = last_insert_id(seq + 2)")).willReturn(1);
given(statement.executeQuery("select last_insert_id()")).willReturn(resultSet);
given(resultSet.next()).willReturn(true);
given(resultSet.getLong(1)).willReturn(2L, 4L);
MySQLMaxValueIncrementer incrementer = new MySQLMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setDataSource(dataSource);
incrementer.setIncrementerName("myseq");
incrementer.setColumnName("seq");
incrementer.setCacheSize(2);
@@ -146,48 +97,21 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
assertEquals("3", incrementer.nextStringValue());
assertEquals(4, incrementer.nextLongValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
verify(resultSet, times(2)).close();
verify(statement, times(2)).close();
verify(connection, times(2)).close();
}
@Test
public void testPostgreSQLSequenceMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeQuery("select nextval('myseq')");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(10);
rs.getLong(1);
rsControl.setReturnValue(12);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
given(dataSource.getConnection()).willReturn(connection);
given(connection.createStatement()).willReturn(statement);
given(statement.executeQuery("select nextval('myseq')")).willReturn(resultSet);
given(resultSet.next()).willReturn(true);
given(resultSet.getLong(1)).willReturn(10L, 12L);
PostgreSQLSequenceMaxValueIncrementer incrementer = new PostgreSQLSequenceMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setDataSource(dataSource);
incrementer.setIncrementerName("myseq");
incrementer.setPaddingLength(5);
incrementer.afterPropertiesSet();
@@ -195,48 +119,21 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
assertEquals("00010", incrementer.nextStringValue());
assertEquals(12, incrementer.nextIntValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
verify(resultSet, times(2)).close();
verify(statement, times(2)).close();
verify(connection, times(2)).close();
}
@Test
public void testOracleSequenceMaxValueIncrementer() throws SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
ds.getConnection();
dsControl.setReturnValue(con, 2);
con.createStatement();
conControl.setReturnValue(stmt, 2);
stmt.executeQuery("select myseq.nextval from dual");
stmtControl.setReturnValue(rs, 2);
rs.next();
rsControl.setReturnValue(true, 2);
rs.getLong(1);
rsControl.setReturnValue(10);
rs.getLong(1);
rsControl.setReturnValue(12);
rs.close();
rsControl.setVoidCallable(2);
stmt.close();
stmtControl.setVoidCallable(2);
con.close();
conControl.setVoidCallable(2);
dsControl.replay();
conControl.replay();
stmtControl.replay();
rsControl.replay();
given(dataSource.getConnection()).willReturn(connection);
given(connection.createStatement()).willReturn(statement);
given(statement.executeQuery("select myseq.nextval from dual")).willReturn(resultSet);
given(resultSet.next()).willReturn(true);
given(resultSet.getLong(1)).willReturn(10L, 12L);
OracleSequenceMaxValueIncrementer incrementer = new OracleSequenceMaxValueIncrementer();
incrementer.setDataSource(ds);
incrementer.setDataSource(dataSource);
incrementer.setIncrementerName("myseq");
incrementer.setPaddingLength(2);
incrementer.afterPropertiesSet();
@@ -244,10 +141,9 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
assertEquals(10, incrementer.nextLongValue());
assertEquals("12", incrementer.nextStringValue());
dsControl.verify();
conControl.verify();
stmtControl.verify();
rsControl.verify();
verify(resultSet, times(2)).close();
verify(statement, times(2)).close();
verify(connection, times(2)).close();
}
}

View File

@@ -16,18 +16,19 @@
package org.springframework.jdbc.support;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.SQLException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
@@ -36,126 +37,77 @@ import org.springframework.jdbc.support.lob.LobHandler;
* @author Juergen Hoeller
* @since 17.12.2003
*/
public class DefaultLobHandlerTests extends TestCase {
public class DefaultLobHandlerTests {
private ResultSet rs = mock(ResultSet.class);
private PreparedStatement ps = mock(PreparedStatement.class);
private LobHandler lobHandler = new DefaultLobHandler();
private LobCreator lobCreator = lobHandler.getLobCreator();
@Test
public void testGetBlobAsBytes() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getBytes(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getBlobAsBytes(rs, 1);
rsControl.verify();
verify(rs).getBytes(1);
}
@Test
public void testGetBlobAsBinaryStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getBinaryStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getBlobAsBinaryStream(rs, 1);
rsControl.verify();
verify(rs).getBinaryStream(1);
}
@Test
public void testGetClobAsString() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getString(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsString(rs, 1);
rsControl.verify();
verify(rs).getString(1);
}
@Test
public void testGetClobAsAsciiStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getAsciiStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsAsciiStream(rs, 1);
rsControl.verify();
verify(rs).getAsciiStream(1);
}
@Test
public void testGetClobAsCharacterStream() throws SQLException {
LobHandler lobHandler = new DefaultLobHandler();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rs.getCharacterStream(1);
rsControl.setReturnValue(null);
rsControl.replay();
lobHandler.getClobAsCharacterStream(rs, 1);
rsControl.verify();
verify(rs).getCharacterStream(1);
}
@Test
public void testSetBlobAsBytes() throws SQLException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
byte[] content = "testContent".getBytes();
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setBytes(1, content);
psControl.replay();
lobCreator.setBlobAsBytes(ps, 1, content);
psControl.verify();
verify(ps).setBytes(1, content);
}
@Test
public void testSetBlobAsBinaryStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setBinaryStream(1, bis, 11);
psControl.replay();
lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11);
psControl.verify();
verify(ps).setBinaryStream(1, bis, 11);
}
@Test
public void testSetClobAsString() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
String content = "testContent";
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setString(1, content);
psControl.replay();
lobCreator.setClobAsString(ps, 1, content);
psControl.verify();
verify(ps).setString(1, content);
}
@Test
public void testSetClobAsAsciiStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setAsciiStream(1, bis, 11);
psControl.replay();
lobCreator.setClobAsAsciiStream(ps, 1, bis, 11);
psControl.verify();
verify(ps).setAsciiStream(1, bis, 11);
}
@Test
public void testSetClobAsCharacterStream() throws SQLException, IOException {
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
Reader str = new StringReader("testContent");
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
ps.setCharacterStream(1, str, 11);
psControl.replay();
lobCreator.setClobAsCharacterStream(ps, 1, str, 11);
psControl.verify();
verify(ps).setCharacterStream(1, str, 11);
}
}

View File

@@ -16,6 +16,10 @@
package org.springframework.jdbc.support;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
@@ -24,9 +28,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor;
import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
@@ -34,33 +36,23 @@ import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
* @author Andre Biryukov
* @author Juergen Hoeller
*/
public class NativeJdbcExtractorTests extends TestCase {
public class NativeJdbcExtractorTests {
@Test
public void testSimpleNativeJdbcExtractor() throws SQLException {
SimpleNativeJdbcExtractor extractor = new SimpleNativeJdbcExtractor();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl dbmdControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData dbmd = (DatabaseMetaData) dbmdControl.getMock();
MockControl con2Control = MockControl.createControl(Connection.class);
Connection con2 = (Connection) con2Control.getMock();
con.getMetaData();
conControl.setReturnValue(dbmd, 2);
dbmd.getConnection();
dbmdControl.setReturnValue(con2, 2);
conControl.replay();
dbmdControl.replay();
con2Control.replay();
Connection con = mock(Connection.class);
DatabaseMetaData dbmd = mock(DatabaseMetaData.class);
Connection con2 = mock(Connection.class);
given(con.getMetaData()).willReturn(dbmd);
given(dbmd.getConnection()).willReturn(con2);
Connection nativeCon = extractor.getNativeConnection(con);
assertEquals(con2, nativeCon);
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
stmt.getConnection();
stmtControl.setReturnValue(con);
stmtControl.replay();
Statement stmt = mock(Statement.class);
given(stmt.getConnection()).willReturn(con);
nativeCon = extractor.getNativeConnectionFromStatement(stmt);
assertEquals(con2, nativeCon);
@@ -68,51 +60,29 @@ public class NativeJdbcExtractorTests extends TestCase {
Statement nativeStmt = extractor.getNativeStatement(stmt);
assertEquals(nativeStmt, stmt);
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
psControl.replay();
PreparedStatement ps = mock(PreparedStatement.class);
PreparedStatement nativePs = extractor.getNativePreparedStatement(ps);
assertEquals(ps, nativePs);
MockControl csControl = MockControl.createControl(CallableStatement.class);
CallableStatement cs = (CallableStatement) csControl.getMock();
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
cs.getResultSet();
csControl.setReturnValue(rs);
csControl.replay();
rsControl.replay();
CallableStatement cs = mock(CallableStatement.class);
ResultSet rs = mock(ResultSet.class);
given(cs.getResultSet()).willReturn(rs);
CallableStatement nativeCs = extractor.getNativeCallableStatement(cs);
assertEquals(cs, nativeCs);
ResultSet nativeRs = extractor.getNativeResultSet(cs.getResultSet());
assertEquals(nativeRs, rs);
conControl.verify();
dbmdControl.verify();
con2Control.verify();
stmtControl.verify();
psControl.verify();
csControl.verify();
rsControl.verify();
}
public void testCommonsDbcpNativeJdbcExtractor() throws SQLException {
CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
assertFalse(extractor.isNativeConnectionNecessaryForNativeStatements());
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl stmtControl = MockControl.createControl(Statement.class);
Statement stmt = (Statement) stmtControl.getMock();
con.getMetaData();
conControl.setReturnValue(null, 2);
stmt.getConnection();
stmtControl.setReturnValue(con, 1);
conControl.replay();
stmtControl.replay();
Connection con = mock(Connection.class);
Statement stmt = mock(Statement.class);
given(stmt.getConnection()).willReturn(con);
Connection nativeConnection = extractor.getNativeConnection(con);
assertEquals(con, nativeConnection);
@@ -121,24 +91,14 @@ public class NativeJdbcExtractorTests extends TestCase {
assertEquals(con, nativeConnection);
assertEquals(stmt, extractor.getNativeStatement(stmt));
MockControl psControl = MockControl.createControl(PreparedStatement.class);
PreparedStatement ps = (PreparedStatement) psControl.getMock();
psControl.replay();
PreparedStatement ps = mock(PreparedStatement.class);
assertEquals(ps, extractor.getNativePreparedStatement(ps));
MockControl csControl = MockControl.createControl(CallableStatement.class);
CallableStatement cs = (CallableStatement) csControl.getMock();
csControl.replay();
CallableStatement cs = mock(CallableStatement.class);
assertEquals(cs, extractor.getNativePreparedStatement(cs));
MockControl rsControl = MockControl.createControl(ResultSet.class);
ResultSet rs = (ResultSet) rsControl.getMock();
rsControl.replay();
ResultSet rs = mock(ResultSet.class);
assertEquals(rs, extractor.getNativeResultSet(rs));
conControl.verify();
stmtControl.verify();
psControl.verify();
}
}

View File

@@ -16,6 +16,16 @@
package org.springframework.jdbc.support;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
@@ -23,26 +33,22 @@ import java.util.Arrays;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Tests for SQLErrorCodes loading.
*
* @author Rod Johnson
* @author Thomas Risberg
*/
public class SQLErrorCodesFactoryTests extends TestCase {
public class SQLErrorCodesFactoryTests {
/**
* Check that a default instance returns empty error codes for an unknown database.
*/
@Test
public void testDefaultInstanceWithNoSuchDatabase() {
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx");
assertTrue(sec.getBadSqlGrammarCodes().length == 0);
@@ -52,6 +58,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
/**
* Check that a known database produces recognizable codes.
*/
@Test
public void testDefaultInstanceWithOracle() {
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("Oracle");
assertIsOracle(sec);
@@ -119,6 +126,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0);
}
@Test
public void testLookupOrder() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
private int lookups = 0;
@@ -147,6 +155,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
/**
* Check that user defined error codes take precedence.
*/
@Test
public void testFindUserDefinedCodes() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
@Override
@@ -166,6 +175,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]);
}
@Test
public void testInvalidUserDefinedCodeFormat() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
@Override
@@ -187,6 +197,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
/**
* Check that custom error codes take precedence.
*/
@Test
public void testFindCustomCodes() {
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
@Override
@@ -207,43 +218,27 @@ public class SQLErrorCodesFactoryTests extends TestCase {
assertEquals(1, translation.getErrorCodes().length);
}
@Test
public void testDataSourceWithNullMetadata() throws Exception {
Connection connection = mock(Connection.class);
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setReturnValue(null);
mockConnection.close();
ctrlConnection.setVoidCallable();
ctrlConnection.replay();
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
ctrlDataSource.replay();
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(dataSource);
assertIsEmpty(sec);
ctrlConnection.verify();
ctrlDataSource.verify();
verify(connection).close();
}
@Test
public void testGetFromDataSourceWithSQLException() throws Exception {
SQLException expectedSQLException = new SQLException();
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setThrowable(expectedSQLException);
ctrlDataSource.replay();
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willThrow(expectedSQLException);
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(dataSource);
assertIsEmpty(sec);
ctrlDataSource.verify();
}
private void assertIsEmpty(SQLErrorCodes sec) {
@@ -253,25 +248,14 @@ public class SQLErrorCodesFactoryTests extends TestCase {
}
private SQLErrorCodes getErrorCodesFromDataSource(String productName, SQLErrorCodesFactory factory) throws Exception {
MockControl mdControl = MockControl.createControl(DatabaseMetaData.class);
DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock();
md.getDatabaseProductName();
mdControl.setReturnValue(productName);
mdControl.replay();
DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
given(databaseMetaData.getDatabaseProductName()).willReturn(productName);
MockControl ctrlConnection = MockControl.createControl(Connection.class);
Connection mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setReturnValue(md);
mockConnection.close();
ctrlConnection.setVoidCallable();
ctrlConnection.replay();
Connection connection = mock(Connection.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
ctrlDataSource.replay();
DataSource dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
SQLErrorCodesFactory secf = null;
if (factory != null) {
@@ -281,33 +265,35 @@ public class SQLErrorCodesFactoryTests extends TestCase {
secf = SQLErrorCodesFactory.getInstance();
}
SQLErrorCodes sec = secf.getErrorCodes(mockDataSource);
SQLErrorCodes sec = secf.getErrorCodes(dataSource);
mdControl.verify();
ctrlConnection.verify();
ctrlDataSource.verify();
SQLErrorCodes sec2 = secf.getErrorCodes(mockDataSource);
SQLErrorCodes sec2 = secf.getErrorCodes(dataSource);
assertSame("Cached per DataSource", sec2, sec);
verify(connection).close();
return sec;
}
@Test
public void testSQLServerRecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("MS-SQL", null);
assertIsSQLServer(sec);
}
@Test
public void testOracleRecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("Oracle", null);
assertIsOracle(sec);
}
@Test
public void testHsqlRecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("HSQL Database Engine", null);
assertIsHsql(sec);
}
@Test
public void testDB2RecognizedFromMetadata() throws Exception {
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", null);
assertIsDB2(sec);
@@ -320,6 +306,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
/**
* Check that wild card database name works.
*/
@Test
public void testWildCardNameRecognized() throws Exception {
class WildcardSQLErrorCodesFactory extends SQLErrorCodesFactory {
@Override

View File

@@ -16,6 +16,11 @@
package org.springframework.jdbc.support.rowset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
@@ -25,156 +30,172 @@ import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.InvalidResultSetAccessException;
/**
* @author Thomas Risberg
*/
public class ResultSetWrappingRowSetTests extends TestCase {
public class ResultSetWrappingRowSetTests {
private MockControl rsetControl;
private ResultSet rset;
private ResultSetWrappingSqlRowSet rowset;
@Override
@Before
public void setUp() throws Exception {
rsetControl = MockControl.createControl(ResultSet.class);
rset = (ResultSet) rsetControl.getMock();
rset.getMetaData();
rsetControl.setReturnValue(null);
rset.getMetaData();
rsetControl.setReturnValue(null);
rset = mock(ResultSet.class);
rowset = new ResultSetWrappingSqlRowSet(rset);
}
@Test
public void testGetBigDecimalInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), BigDecimal.valueOf(1));
}
@Test
public void testGetBigDecimalString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {String.class});
doTest(rset, rowset, "test", BigDecimal.valueOf(1));
}
@Test
public void testGetStringInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), "test");
}
@Test
public void testGetStringString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {String.class});
doTest(rset, rowset, "test", "test");
}
@Test
public void testGetTimestampInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Timestamp(1234l));
}
@Test
public void testGetTimestampString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {String.class});
doTest(rset, rowset, "test", new Timestamp(1234l));
}
@Test
public void testGetDateInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Date(1234l));
}
@Test
public void testGetDateString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {String.class});
doTest(rset, rowset, "test", new Date(1234l));
}
@Test
public void testGetTimeInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Time(1234l));
}
@Test
public void testGetTimeString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {String.class});
doTest(rset, rowset, "test", new Time(1234l));
}
@Test
public void testGetObjectInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Object());
}
@Test
public void testGetObjectString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {String.class});
doTest(rset, rowset, "test", new Object());
}
@Test
public void testGetIntInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Integer(1));
}
@Test
public void testGetIntString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {String.class});
doTest(rset, rowset, "test", new Integer(1));
}
@Test
public void testGetFloatInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Float(1));
}
@Test
public void testGetFloatString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {String.class});
doTest(rset, rowset, "test", new Float(1));
}
@Test
public void testGetDoubleInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Double(1));
}
@Test
public void testGetDoubleString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {String.class});
doTest(rset, rowset, "test", new Double(1));
}
@Test
public void testGetLongInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Long(1));
}
@Test
public void testGetLongString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {String.class});
doTest(rset, rowset, "test", new Long(1));
}
@Test
public void testGetBooleanInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
doTest(rset, rowset, new Integer(1), new Boolean(true));
}
@Test
public void testGetBooleanString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {String.class});
@@ -183,56 +204,14 @@ public class ResultSetWrappingRowSetTests extends TestCase {
private void doTest(Method rsetMethod, Method rowsetMethod, Object arg, Object ret) throws Exception {
if (arg instanceof String) {
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
findMethod.invoke(rset, new Object[] {arg});
rsetControl.setReturnValue(1);
rsetMethod.invoke(rset, new Object[] {1});
given(rset.findColumn((String) arg)).willReturn(1);
given(rsetMethod.invoke(rset, 1)).willReturn(ret).willThrow(new SQLException("test"));
} else {
given(rsetMethod.invoke(rset, arg)).willReturn(ret).willThrow(new SQLException("test"));
}
else {
rsetMethod.invoke(rset, new Object[] {arg});
}
if (ret instanceof Double) {
rsetControl.setReturnValue(((Double) ret).doubleValue());
}
else if (ret instanceof Float) {
rsetControl.setReturnValue(((Float) ret).floatValue());
}
else if (ret instanceof Integer) {
rsetControl.setReturnValue(((Integer) ret).intValue());
}
else if (ret instanceof Short) {
rsetControl.setReturnValue(((Short) ret).shortValue());
}
else if (ret instanceof Long) {
rsetControl.setReturnValue(((Long) ret).longValue());
}
else if (ret instanceof Boolean) {
rsetControl.setReturnValue(((Boolean) ret).booleanValue());
}
else if (ret instanceof Byte) {
rsetControl.setReturnValue(((Byte) ret).byteValue());
}
else {
rsetControl.setReturnValue(ret);
}
if (arg instanceof String) {
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
findMethod.invoke(rset, new Object[] {arg});
rsetControl.setReturnValue(1);
rsetMethod.invoke(rset, new Object[] {1});
}
else {
rsetMethod.invoke(rset, new Object[] {arg});
}
rsetControl.setThrowable(new SQLException("test"));
rsetControl.replay();
rowset = new ResultSetWrappingSqlRowSet(rset);
rowsetMethod.invoke(rowset, new Object[] {arg});
rowsetMethod.invoke(rowset, arg);
try {
rowsetMethod.invoke(rowset, new Object[] {arg});
rowsetMethod.invoke(rowset, arg);
fail("InvalidResultSetAccessException should have been thrown");
}
catch (InvocationTargetException ex) {