This commit is contained in:
Stéphane Nicoll
2024-01-06 09:11:59 +01:00
parent a51c22b266
commit 87b35e7d8e
58 changed files with 651 additions and 679 deletions

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Dave Syer * @author Dave Syer
*/ */
public class InitializeDatabaseIntegrationTests { class InitializeDatabaseIntegrationTests {
private String enabled; private String enabled;
@@ -44,12 +44,12 @@ public class InitializeDatabaseIntegrationTests {
@BeforeEach @BeforeEach
public void init() { void init() {
enabled = System.setProperty("ENABLED", "true"); enabled = System.setProperty("ENABLED", "true");
} }
@AfterEach @AfterEach
public void after() { void after() {
if (enabled != null) { if (enabled != null) {
System.setProperty("ENABLED", enabled); System.setProperty("ENABLED", enabled);
} }
@@ -63,13 +63,13 @@ public class InitializeDatabaseIntegrationTests {
@Test @Test
public void testCreateEmbeddedDatabase() throws Exception { void testCreateEmbeddedDatabase() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml");
assertCorrectSetup(context.getBean("dataSource", DataSource.class)); assertCorrectSetup(context.getBean("dataSource", DataSource.class));
} }
@Test @Test
public void testDisableCreateEmbeddedDatabase() throws Exception { void testDisableCreateEmbeddedDatabase() {
System.setProperty("ENABLED", "false"); System.setProperty("ENABLED", "false");
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml");
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
@@ -77,13 +77,13 @@ public class InitializeDatabaseIntegrationTests {
} }
@Test @Test
public void testIgnoreFailedDrops() throws Exception { void testIgnoreFailedDrops() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-fail-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-fail-config.xml");
assertCorrectSetup(context.getBean("dataSource", DataSource.class)); assertCorrectSetup(context.getBean("dataSource", DataSource.class));
} }
@Test @Test
public void testScriptNameWithPattern() throws Exception { void testScriptNameWithPattern() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-pattern-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-pattern-config.xml");
DataSource dataSource = context.getBean("dataSource", DataSource.class); DataSource dataSource = context.getBean("dataSource", DataSource.class);
assertCorrectSetup(dataSource); assertCorrectSetup(dataSource);
@@ -92,21 +92,21 @@ public class InitializeDatabaseIntegrationTests {
} }
@Test @Test
public void testScriptNameWithPlaceholder() throws Exception { void testScriptNameWithPlaceholder() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-placeholder-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-placeholder-config.xml");
DataSource dataSource = context.getBean("dataSource", DataSource.class); DataSource dataSource = context.getBean("dataSource", DataSource.class);
assertCorrectSetup(dataSource); assertCorrectSetup(dataSource);
} }
@Test @Test
public void testScriptNameWithExpressions() throws Exception { void testScriptNameWithExpressions() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-expression-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-expression-config.xml");
DataSource dataSource = context.getBean("dataSource", DataSource.class); DataSource dataSource = context.getBean("dataSource", DataSource.class);
assertCorrectSetup(dataSource); assertCorrectSetup(dataSource);
} }
@Test @Test
public void testCacheInitialization() throws Exception { void testCacheInitialization() {
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-cache-config.xml"); context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-cache-config.xml");
assertCorrectSetup(context.getBean("dataSource", DataSource.class)); assertCorrectSetup(context.getBean("dataSource", DataSource.class));
CacheData cache = context.getBean(CacheData.class); CacheData cache = context.getBean(CacheData.class);
@@ -134,7 +134,7 @@ public class InitializeDatabaseIntegrationTests {
} }
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() {
cache = jdbcTemplate.queryForList("SELECT * FROM T_TEST"); cache = jdbcTemplate.queryForList("SELECT * FROM T_TEST");
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -52,40 +52,40 @@ class JdbcNamespaceIntegrationTests {
@Test @Test
@EnabledForTestGroups(LONG_RUNNING) @EnabledForTestGroups(LONG_RUNNING)
void createEmbeddedDatabase() throws Exception { void createEmbeddedDatabase() {
assertCorrectSetup("jdbc-config.xml", "dataSource", "h2DataSource", "derbyDataSource"); assertCorrectSetup("jdbc-config.xml", "dataSource", "h2DataSource", "derbyDataSource");
} }
@Test @Test
@EnabledForTestGroups(LONG_RUNNING) @EnabledForTestGroups(LONG_RUNNING)
void createEmbeddedDatabaseAgain() throws Exception { void createEmbeddedDatabaseAgain() {
// If Derby isn't cleaned up properly this will fail... // If Derby isn't cleaned up properly this will fail...
assertCorrectSetup("jdbc-config.xml", "derbyDataSource"); assertCorrectSetup("jdbc-config.xml", "derbyDataSource");
} }
@Test @Test
void createWithResourcePattern() throws Exception { void createWithResourcePattern() {
assertCorrectSetup("jdbc-config-pattern.xml", "dataSource"); assertCorrectSetup("jdbc-config-pattern.xml", "dataSource");
} }
@Test @Test
void createWithAnonymousDataSourceAndDefaultDatabaseName() throws Exception { void createWithAnonymousDataSourceAndDefaultDatabaseName() {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-default-and-anonymous-datasource.xml", assertCorrectSetupForSingleDataSource("jdbc-config-db-name-default-and-anonymous-datasource.xml",
url -> url.endsWith(DEFAULT_DATABASE_NAME)); url -> url.endsWith(DEFAULT_DATABASE_NAME));
} }
@Test @Test
void createWithImplicitDatabaseName() throws Exception { void createWithImplicitDatabaseName() {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-implicit.xml", url -> url.endsWith("dataSource")); assertCorrectSetupForSingleDataSource("jdbc-config-db-name-implicit.xml", url -> url.endsWith("dataSource"));
} }
@Test @Test
void createWithExplicitDatabaseName() throws Exception { void createWithExplicitDatabaseName() {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-explicit.xml", url -> url.endsWith("customDbName")); assertCorrectSetupForSingleDataSource("jdbc-config-db-name-explicit.xml", url -> url.endsWith("customDbName"));
} }
@Test @Test
void createWithGeneratedDatabaseName() throws Exception { void createWithGeneratedDatabaseName() {
Predicate<String> urlPredicate = url -> url.startsWith("jdbc:hsqldb:mem:"); Predicate<String> urlPredicate = url -> url.startsWith("jdbc:hsqldb:mem:");
urlPredicate.and(url -> !url.endsWith("dataSource")); urlPredicate.and(url -> !url.endsWith("dataSource"));
urlPredicate.and(url -> !url.endsWith("shouldBeOverriddenByGeneratedName")); urlPredicate.and(url -> !url.endsWith("shouldBeOverriddenByGeneratedName"));
@@ -93,17 +93,17 @@ class JdbcNamespaceIntegrationTests {
} }
@Test @Test
void createWithEndings() throws Exception { void createWithEndings() {
assertCorrectSetupAndCloseContext("jdbc-initialize-endings-config.xml", 2, "dataSource"); assertCorrectSetupAndCloseContext("jdbc-initialize-endings-config.xml", 2, "dataSource");
} }
@Test @Test
void createWithEndingsNested() throws Exception { void createWithEndingsNested() {
assertCorrectSetupAndCloseContext("jdbc-initialize-endings-nested-config.xml", 2, "dataSource"); assertCorrectSetupAndCloseContext("jdbc-initialize-endings-nested-config.xml", 2, "dataSource");
} }
@Test @Test
void createAndDestroy() throws Exception { void createAndDestroy() {
try (ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml")) { try (ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml")) {
DataSource dataSource = context.getBean(DataSource.class); DataSource dataSource = context.getBean(DataSource.class);
JdbcTemplate template = new JdbcTemplate(dataSource); JdbcTemplate template = new JdbcTemplate(dataSource);
@@ -116,7 +116,7 @@ class JdbcNamespaceIntegrationTests {
} }
@Test @Test
void createAndDestroyNestedWithHsql() throws Exception { void createAndDestroyNestedWithHsql() {
try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml")) { try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml")) {
DataSource dataSource = context.getBean(DataSource.class); DataSource dataSource = context.getBean(DataSource.class);
JdbcTemplate template = new JdbcTemplate(dataSource); JdbcTemplate template = new JdbcTemplate(dataSource);
@@ -129,7 +129,7 @@ class JdbcNamespaceIntegrationTests {
} }
@Test @Test
void createAndDestroyNestedWithH2() throws Exception { void createAndDestroyNestedWithH2() {
try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml")) { try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml")) {
DataSource dataSource = context.getBean(DataSource.class); DataSource dataSource = context.getBean(DataSource.class);
JdbcTemplate template = new JdbcTemplate(dataSource); JdbcTemplate template = new JdbcTemplate(dataSource);
@@ -142,7 +142,7 @@ class JdbcNamespaceIntegrationTests {
} }
@Test @Test
void multipleDataSourcesHaveDifferentDatabaseNames() throws Exception { void multipleDataSourcesHaveDifferentDatabaseNames() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(factory).loadBeanDefinitions(new ClassPathResource( new XmlBeanDefinitionReader(factory).loadBeanDefinitions(new ClassPathResource(
"jdbc-config-multiple-datasources.xml", getClass())); "jdbc-config-multiple-datasources.xml", getClass()));
@@ -151,12 +151,12 @@ class JdbcNamespaceIntegrationTests {
} }
@Test @Test
void initializeWithCustomSeparator() throws Exception { void initializeWithCustomSeparator() {
assertCorrectSetupAndCloseContext("jdbc-initialize-custom-separator.xml", 2, "dataSource"); assertCorrectSetupAndCloseContext("jdbc-initialize-custom-separator.xml", 2, "dataSource");
} }
@Test @Test
void embeddedWithCustomSeparator() throws Exception { void embeddedWithCustomSeparator() {
assertCorrectSetupAndCloseContext("jdbc-config-custom-separator.xml", 2, "dataSource"); assertCorrectSetupAndCloseContext("jdbc-config-custom-separator.xml", 2, "dataSource");
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify;
* @author Rob Winch * @author Rob Winch
* @since 19.12.2004 * @since 19.12.2004
*/ */
public class JdbcTemplateQueryTests { class JdbcTemplateQueryTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -66,7 +66,7 @@ public class JdbcTemplateQueryTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(this.dataSource.getConnection()).willReturn(this.connection); given(this.dataSource.getConnection()).willReturn(this.connection);
given(this.connection.createStatement()).willReturn(this.statement); given(this.connection.createStatement()).willReturn(this.statement);
given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement); given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement);
@@ -81,7 +81,7 @@ public class JdbcTemplateQueryTests {
@Test @Test
public void testQueryForList() throws Exception { void testQueryForList() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(true, true, false); given(this.resultSet.next()).willReturn(true, true, false);
given(this.resultSet.getObject(1)).willReturn(11, 12); given(this.resultSet.getObject(1)).willReturn(11, 12);
@@ -95,7 +95,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithEmptyResult() throws Exception { void testQueryForListWithEmptyResult() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(false); given(this.resultSet.next()).willReturn(false);
List<Map<String, Object>> li = this.template.queryForList(sql); List<Map<String, Object>> li = this.template.queryForList(sql);
@@ -106,7 +106,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithSingleRowAndColumn() throws Exception { void testQueryForListWithSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getObject(1)).willReturn(11); given(this.resultSet.getObject(1)).willReturn(11);
@@ -119,20 +119,19 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithIntegerElement() throws Exception { void testQueryForListWithIntegerElement() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(11); given(this.resultSet.getInt(1)).willReturn(11);
List<Integer> li = this.template.queryForList(sql, Integer.class); List<Integer> li = this.template.queryForList(sql, Integer.class);
assertThat(li).as("All rows returned").hasSize(1); assertThat(li).containsExactly(11);
assertThat(li).element(0).as("Element is Integer").isEqualTo(11);
verify(this.resultSet).close(); verify(this.resultSet).close();
verify(this.statement).close(); verify(this.statement).close();
verify(this.connection).close(); verify(this.connection).close();
} }
@Test @Test
public void testQueryForMapWithSingleRowAndColumn() throws Exception { void testQueryForMapWithSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getObject(1)).willReturn(11); given(this.resultSet.getObject(1)).willReturn(11);
@@ -144,7 +143,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception { void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception {
String sql = "select pass from t_account where first_name='Alef'"; String sql = "select pass from t_account where first_name='Alef'";
given(this.resultSet.next()).willReturn(true, true, false); given(this.resultSet.next()).willReturn(true, true, false);
given(this.resultSet.getString(1)).willReturn("pass"); given(this.resultSet.getString(1)).willReturn("pass");
@@ -156,11 +155,11 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithRowMapper() throws Exception { void testQueryForObjectWithRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
Object o = this.template.queryForObject(sql, (RowMapper<Integer>) (rs, rowNum) -> rs.getInt(1)); Object o = this.template.queryForObject(sql, (rs, rowNum) -> rs.getInt(1));
assertThat(o).as("Correct result type").isInstanceOf(Integer.class); assertThat(o).as("Correct result type").isInstanceOf(Integer.class);
verify(this.resultSet).close(); verify(this.resultSet).close();
verify(this.statement).close(); verify(this.statement).close();
@@ -168,7 +167,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForStreamWithRowMapper() throws Exception { void testQueryForStreamWithRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -186,7 +185,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithString() throws Exception { void testQueryForObjectWithString() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getString(1)).willReturn("myvalue"); given(this.resultSet.getString(1)).willReturn("myvalue");
@@ -197,7 +196,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithBigInteger() throws Exception { void testQueryForObjectWithBigInteger() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getObject(1, BigInteger.class)).willReturn(new BigInteger("22")); given(this.resultSet.getObject(1, BigInteger.class)).willReturn(new BigInteger("22"));
@@ -208,7 +207,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithBigDecimal() throws Exception { void testQueryForObjectWithBigDecimal() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getBigDecimal(1)).willReturn(new BigDecimal("22.5")); given(this.resultSet.getBigDecimal(1)).willReturn(new BigDecimal("22.5"));
@@ -219,7 +218,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithInteger() throws Exception { void testQueryForObjectWithInteger() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -230,7 +229,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithIntegerAndNull() throws Exception { void testQueryForObjectWithIntegerAndNull() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(0); given(this.resultSet.getInt(1)).willReturn(0);
@@ -242,7 +241,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForInt() throws Exception { void testQueryForInt() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -254,7 +253,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForIntPrimitive() throws Exception { void testQueryForIntPrimitive() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -266,7 +265,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForLong() throws Exception { void testQueryForLong() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getLong(1)).willReturn(87L); given(this.resultSet.getLong(1)).willReturn(87L);
@@ -278,7 +277,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForLongPrimitive() throws Exception { void testQueryForLongPrimitive() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getLong(1)).willReturn(87L); given(this.resultSet.getLong(1)).willReturn(87L);
@@ -290,12 +289,12 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithArgs() throws Exception { void testQueryForListWithArgs() throws Exception {
doTestQueryForListWithArgs("SELECT AGE FROM CUSTMR WHERE ID < ?"); doTestQueryForListWithArgs("SELECT AGE FROM CUSTMR WHERE ID < ?");
} }
@Test @Test
public void testQueryForListIsNotConfusedByNamedParameterPrefix() throws Exception { void testQueryForListIsNotConfusedByNamedParameterPrefix() throws Exception {
doTestQueryForListWithArgs("SELECT AGE FROM PREFIX:CUSTMR WHERE ID < ?"); doTestQueryForListWithArgs("SELECT AGE FROM PREFIX:CUSTMR WHERE ID < ?");
} }
@@ -313,7 +312,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithArgsAndEmptyResult() throws Exception { void testQueryForListWithArgsAndEmptyResult() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
given(this.resultSet.next()).willReturn(false); given(this.resultSet.next()).willReturn(false);
List<Map<String, Object>> li = this.template.queryForList(sql, 3); List<Map<String, Object>> li = this.template.queryForList(sql, 3);
@@ -325,7 +324,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithArgsAndSingleRowAndColumn() throws Exception { void testQueryForListWithArgsAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getObject(1)).willReturn(11); given(this.resultSet.getObject(1)).willReturn(11);
@@ -339,13 +338,12 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForListWithArgsAndIntegerElementAndSingleRowAndColumn() throws Exception { void testQueryForListWithArgsAndIntegerElementAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(11); given(this.resultSet.getInt(1)).willReturn(11);
List<Integer> li = this.template.queryForList(sql, Integer.class, 3); List<Integer> li = this.template.queryForList(sql, Integer.class, 3);
assertThat(li).as("All rows returned").hasSize(1); assertThat(li).containsExactly(11);
assertThat(li).element(0).as("First row is Integer").isEqualTo(11);
verify(this.preparedStatement).setObject(1, 3); verify(this.preparedStatement).setObject(1, 3);
verify(this.resultSet).close(); verify(this.resultSet).close();
verify(this.preparedStatement).close(); verify(this.preparedStatement).close();
@@ -353,7 +351,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForMapWithArgsAndSingleRowAndColumn() throws Exception { void testQueryForMapWithArgsAndSingleRowAndColumn() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getObject(1)).willReturn(11); given(this.resultSet.getObject(1)).willReturn(11);
@@ -366,7 +364,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithArgsAndRowMapper() throws Exception { void testQueryForObjectWithArgsAndRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -379,7 +377,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForStreamWithArgsAndRowMapper() throws Exception { void testQueryForStreamWithArgsAndRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -398,7 +396,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForObjectWithArgsAndInteger() throws Exception { void testQueryForObjectWithArgsAndInteger() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -411,7 +409,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForIntWithArgs() throws Exception { void testQueryForIntWithArgs() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22); given(this.resultSet.getInt(1)).willReturn(22);
@@ -424,7 +422,7 @@ public class JdbcTemplateQueryTests {
} }
@Test @Test
public void testQueryForLongWithArgs() throws Exception { void testQueryForLongWithArgs() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?"; String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getLong(1)).willReturn(87L); given(this.resultSet.getLong(1)).willReturn(87L);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -75,7 +75,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Phillip Webb * @author Phillip Webb
*/ */
public class JdbcTemplateTests { class JdbcTemplateTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -93,7 +93,7 @@ public class JdbcTemplateTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(this.dataSource.getConnection()).willReturn(this.connection); given(this.dataSource.getConnection()).willReturn(this.connection);
given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement); given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement);
given(this.connection.prepareCall(anyString())).willReturn(this.callableStatement); given(this.connection.prepareCall(anyString())).willReturn(this.callableStatement);
@@ -107,7 +107,7 @@ public class JdbcTemplateTests {
@Test @Test
public void testBeanProperties() throws Exception { void testBeanProperties() {
assertThat(this.template.getDataSource()).as("datasource ok").isSameAs(this.dataSource); assertThat(this.template.getDataSource()).as("datasource ok").isSameAs(this.dataSource);
assertThat(this.template.isIgnoreWarnings()).as("ignores warnings by default").isTrue(); assertThat(this.template.isIgnoreWarnings()).as("ignores warnings by default").isTrue();
this.template.setIgnoreWarnings(false); this.template.setIgnoreWarnings(false);
@@ -116,7 +116,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testUpdateCount() throws Exception { void testUpdateCount() throws Exception {
final String sql = "UPDATE INVOICE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE INVOICE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
int idParam = 11111; int idParam = 11111;
given(this.preparedStatement.executeUpdate()).willReturn(1); given(this.preparedStatement.executeUpdate()).willReturn(1);
@@ -129,7 +129,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBogusUpdate() throws Exception { void testBogusUpdate() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int idParam = 6666; final int idParam = 6666;
@@ -147,23 +147,23 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testStringsWithStaticSql() throws Exception { void testStringsWithStaticSql() throws Exception {
doTestStrings(null, null, null, null, JdbcTemplate::query); doTestStrings(null, null, null, null, JdbcTemplate::query);
} }
@Test @Test
public void testStringsWithStaticSqlAndFetchSizeAndMaxRows() throws Exception { void testStringsWithStaticSqlAndFetchSizeAndMaxRows() throws Exception {
doTestStrings(10, 20, 30, null, JdbcTemplate::query); doTestStrings(10, 20, 30, null, JdbcTemplate::query);
} }
@Test @Test
public void testStringsWithEmptyPreparedStatementSetter() throws Exception { void testStringsWithEmptyPreparedStatementSetter() throws Exception {
doTestStrings(null, null, null, null, (template, sql, rch) -> doTestStrings(null, null, null, null, (template, sql, rch) ->
template.query(sql, (PreparedStatementSetter) null, rch)); template.query(sql, (PreparedStatementSetter) null, rch));
} }
@Test @Test
public void testStringsWithPreparedStatementSetter() throws Exception { void testStringsWithPreparedStatementSetter() throws Exception {
final Integer argument = 99; final Integer argument = 99;
doTestStrings(null, null, null, argument, (template, sql, rch) -> doTestStrings(null, null, null, argument, (template, sql, rch) ->
template.query(sql, ps -> ps.setObject(1, argument), rch)); template.query(sql, ps -> ps.setObject(1, argument), rch));
@@ -244,7 +244,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testLeaveConnectionOpenOnRequest() throws Exception { void testLeaveConnectionOpenOnRequest() throws Exception {
String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3"; String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(false); given(this.resultSet.next()).willReturn(false);
@@ -263,7 +263,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testConnectionCallback() throws Exception { void testConnectionCallback() {
String result = this.template.execute((ConnectionCallback<String>) con -> { String result = this.template.execute((ConnectionCallback<String>) con -> {
assertThat(con).isInstanceOf(ConnectionProxy.class); assertThat(con).isInstanceOf(ConnectionProxy.class);
assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection); assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection);
@@ -273,7 +273,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testConnectionCallbackWithStatementSettings() throws Exception { void testConnectionCallbackWithStatementSettings() throws Exception {
String result = this.template.execute((ConnectionCallback<String>) con -> { String result = this.template.execute((ConnectionCallback<String>) con -> {
PreparedStatement ps = con.prepareStatement("some SQL"); PreparedStatement ps = con.prepareStatement("some SQL");
ps.setFetchSize(10); ps.setFetchSize(10);
@@ -290,7 +290,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCloseConnectionOnRequest() throws Exception { void testCloseConnectionOnRequest() throws Exception {
String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3"; String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";
given(this.resultSet.next()).willReturn(false); given(this.resultSet.next()).willReturn(false);
@@ -308,7 +308,7 @@ public class JdbcTemplateTests {
* Test that we see a runtime exception come back. * Test that we see a runtime exception come back.
*/ */
@Test @Test
public void testExceptionComesBack() throws Exception { void testExceptionComesBack() throws Exception {
final String sql = "SELECT ID FROM CUSTMR"; final String sql = "SELECT ID FROM CUSTMR";
final RuntimeException runtimeException = new RuntimeException("Expected"); final RuntimeException runtimeException = new RuntimeException("Expected");
@@ -334,7 +334,7 @@ public class JdbcTemplateTests {
* Test update with static SQL. * Test update with static SQL.
*/ */
@Test @Test
public void testSqlUpdate() throws Exception { void testSqlUpdate() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4";
int rowsAffected = 33; int rowsAffected = 33;
@@ -351,7 +351,7 @@ public class JdbcTemplateTests {
* Test update with dynamic SQL. * Test update with dynamic SQL.
*/ */
@Test @Test
public void testSqlUpdateWithArguments() throws Exception { void testSqlUpdateWithArguments() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ? and PR = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ? and PR = ?";
int rowsAffected = 33; int rowsAffected = 33;
given(this.preparedStatement.executeUpdate()).willReturn(rowsAffected); given(this.preparedStatement.executeUpdate()).willReturn(rowsAffected);
@@ -366,7 +366,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testSqlUpdateEncountersSqlException() throws Exception { void testSqlUpdateEncountersSqlException() throws Exception {
SQLException sqlException = new SQLException("bad update"); SQLException sqlException = new SQLException("bad update");
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4";
@@ -381,7 +381,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testSqlUpdateWithThreadConnection() throws Exception { void testSqlUpdateWithThreadConnection() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4";
int rowsAffected = 33; int rowsAffected = 33;
@@ -396,7 +396,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdate() throws Exception { void testBatchUpdate() throws Exception {
final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1", final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2"}; "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2"};
@@ -416,7 +416,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithBatchFailure() throws Exception { void testBatchUpdateWithBatchFailure() throws Exception {
final String[] sql = {"A", "B", "C", "D"}; final String[] sql = {"A", "B", "C", "D"};
given(this.statement.executeBatch()).willThrow( given(this.statement.executeBatch()).willThrow(
new BatchUpdateException(new int[] {1, Statement.EXECUTE_FAILED, 1, Statement.EXECUTE_FAILED})); new BatchUpdateException(new int[] {1, Statement.EXECUTE_FAILED, 1, Statement.EXECUTE_FAILED}));
@@ -433,7 +433,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithNoBatchSupport() throws Exception { void testBatchUpdateWithNoBatchSupport() throws Exception {
final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1", final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2"}; "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2"};
@@ -455,7 +455,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithNoBatchSupportAndSelect() throws Exception { void testBatchUpdateWithNoBatchSupportAndSelect() throws Exception {
final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1", final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
"SELECT * FROM NOSUCHTABLE"}; "SELECT * FROM NOSUCHTABLE"};
@@ -474,7 +474,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithPreparedStatement() throws Exception { void testBatchUpdateWithPreparedStatement() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
final int[] rowsAffected = new int[] {1, 2}; final int[] rowsAffected = new int[] {1, 2};
@@ -508,7 +508,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithPreparedStatementWithEmptyData() throws Exception { void testBatchUpdateWithPreparedStatementWithEmptyData() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {}; final int[] ids = new int[] {};
final int[] rowsAffected = new int[] {}; final int[] rowsAffected = new int[] {};
@@ -536,7 +536,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testInterruptibleBatchUpdate() throws Exception { void testInterruptibleBatchUpdate() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
final int[] rowsAffected = new int[] {1, 2}; final int[] rowsAffected = new int[] {1, 2};
@@ -577,7 +577,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testInterruptibleBatchUpdateWithBaseClass() throws Exception { void testInterruptibleBatchUpdateWithBaseClass() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
final int[] rowsAffected = new int[] {1, 2}; final int[] rowsAffected = new int[] {1, 2};
@@ -614,7 +614,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testInterruptibleBatchUpdateWithBaseClassAndNoBatchSupport() throws Exception { void testInterruptibleBatchUpdateWithBaseClassAndNoBatchSupport() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
final int[] rowsAffected = new int[] {1, 2}; final int[] rowsAffected = new int[] {1, 2};
@@ -651,7 +651,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithPreparedStatementAndNoBatchSupport() throws Exception { void testBatchUpdateWithPreparedStatementAndNoBatchSupport() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
final int[] rowsAffected = new int[] {1, 2}; final int[] rowsAffected = new int[] {1, 2};
@@ -682,7 +682,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateFails() throws Exception { void testBatchUpdateFails() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final int[] ids = new int[] {100, 200}; final int[] ids = new int[] {100, 200};
SQLException sqlException = new SQLException(); SQLException sqlException = new SQLException();
@@ -716,7 +716,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithEmptyList() throws Exception { void testBatchUpdateWithEmptyList() {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
JdbcTemplate template = new JdbcTemplate(this.dataSource, false); JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
@@ -725,7 +725,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithListOfObjectArrays() throws Exception { void testBatchUpdateWithListOfObjectArrays() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final List<Object[]> ids = new ArrayList<>(2); final List<Object[]> ids = new ArrayList<>(2);
ids.add(new Object[] {100}); ids.add(new Object[] {100});
@@ -749,7 +749,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception { void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final List<Object[]> ids = new ArrayList<>(2); final List<Object[]> ids = new ArrayList<>(2);
ids.add(new Object[] {100}); ids.add(new Object[] {100});
@@ -773,7 +773,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithCollectionOfObjects() throws Exception { void testBatchUpdateWithCollectionOfObjects() throws Exception {
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
final List<Integer> ids = Arrays.asList(100, 200, 300); final List<Integer> ids = Arrays.asList(100, 200, 300);
final int[] rowsAffected1 = new int[] {1, 2}; final int[] rowsAffected1 = new int[] {1, 2};
@@ -800,7 +800,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCouldNotGetConnectionForOperationOrExceptionTranslator() throws SQLException { void testCouldNotGetConnectionForOperationOrExceptionTranslator() throws SQLException {
SQLException sqlException = new SQLException("foo", "07xxx"); SQLException sqlException = new SQLException("foo", "07xxx");
given(this.dataSource.getConnection()).willThrow(sqlException); given(this.dataSource.getConnection()).willThrow(sqlException);
JdbcTemplate template = new JdbcTemplate(this.dataSource, false); JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
@@ -812,7 +812,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCouldNotGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException { void testCouldNotGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
SQLException sqlException = new SQLException("foo", "07xxx"); SQLException sqlException = new SQLException("foo", "07xxx");
given(this.dataSource.getConnection()).willThrow(sqlException); given(this.dataSource.getConnection()).willThrow(sqlException);
this.template = new JdbcTemplate(); this.template = new JdbcTemplate();
@@ -826,14 +826,14 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCouldNotGetConnectionInOperationWithExceptionTranslatorInitializedViaBeanProperty() void testCouldNotGetConnectionInOperationWithExceptionTranslatorInitializedViaBeanProperty()
throws SQLException { throws SQLException {
doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(true); doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(true);
} }
@Test @Test
public void testCouldNotGetConnectionInOperationWithExceptionTranslatorInitializedInAfterPropertiesSet() void testCouldNotGetConnectionInOperationWithExceptionTranslatorInitializedInAfterPropertiesSet()
throws SQLException { throws SQLException {
doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(false); doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(false);
@@ -866,7 +866,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testPreparedStatementSetterSucceeds() throws Exception { void testPreparedStatementSetterSucceeds() throws Exception {
final String sql = "UPDATE FOO SET NAME=? WHERE ID = 1"; final String sql = "UPDATE FOO SET NAME=? WHERE ID = 1";
final String name = "Gary"; final String name = "Gary";
int expectedRowsUpdated = 1; int expectedRowsUpdated = 1;
@@ -882,7 +882,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testPreparedStatementSetterFails() throws Exception { void testPreparedStatementSetterFails() throws Exception {
final String sql = "UPDATE FOO SET NAME=? WHERE ID = 1"; final String sql = "UPDATE FOO SET NAME=? WHERE ID = 1";
final String name = "Gary"; final String name = "Gary";
SQLException sqlException = new SQLException(); SQLException sqlException = new SQLException();
@@ -898,7 +898,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCouldNotClose() throws Exception { void testCouldNotClose() throws Exception {
SQLException sqlException = new SQLException("bar"); SQLException sqlException = new SQLException("bar");
given(this.connection.createStatement()).willReturn(this.statement); given(this.connection.createStatement()).willReturn(this.statement);
given(this.resultSet.next()).willReturn(false); given(this.resultSet.next()).willReturn(false);
@@ -915,7 +915,7 @@ public class JdbcTemplateTests {
* Mock objects allow us to produce warnings at will * Mock objects allow us to produce warnings at will
*/ */
@Test @Test
public void testFatalWarning() throws Exception { void testFatalWarning() throws Exception {
String sql = "SELECT forename from custmr"; String sql = "SELECT forename from custmr";
SQLWarning warnings = new SQLWarning("My warning"); SQLWarning warnings = new SQLWarning("My warning");
@@ -936,7 +936,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testIgnoredWarning() throws Exception { void testIgnoredWarning() throws Exception {
String sql = "SELECT forename from custmr"; String sql = "SELECT forename from custmr";
SQLWarning warnings = new SQLWarning("My warning"); SQLWarning warnings = new SQLWarning("My warning");
@@ -956,7 +956,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testSQLErrorCodeTranslation() throws Exception { void testSQLErrorCodeTranslation() throws Exception {
final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054); final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
final String sql = "SELECT ID FROM CUSTOMER"; final String sql = "SELECT ID FROM CUSTOMER";
@@ -977,7 +977,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testSQLErrorCodeTranslationWithSpecifiedDatabaseName() throws Exception { void testSQLErrorCodeTranslationWithSpecifiedDatabaseName() throws Exception {
final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054); final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
final String sql = "SELECT ID FROM CUSTOMER"; final String sql = "SELECT ID FROM CUSTOMER";
@@ -1002,7 +1002,7 @@ public class JdbcTemplateTests {
* to get the metadata * to get the metadata
*/ */
@Test @Test
public void testUseCustomExceptionTranslator() throws Exception { void testUseCustomExceptionTranslator() throws Exception {
// Bad SQL state // Bad SQL state
final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054); final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
final String sql = "SELECT ID FROM CUSTOMER"; final String sql = "SELECT ID FROM CUSTOMER";
@@ -1027,7 +1027,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testStaticResultSetClosed() throws Exception { void testStaticResultSetClosed() throws Exception {
ResultSet resultSet2 = mock(); ResultSet resultSet2 = mock();
reset(this.preparedStatement); reset(this.preparedStatement);
given(this.preparedStatement.executeQuery()).willReturn(resultSet2); given(this.preparedStatement.executeQuery()).willReturn(resultSet2);
@@ -1049,7 +1049,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testExecuteClosed() throws Exception { void testExecuteClosed() throws Exception {
given(this.resultSet.next()).willReturn(true); given(this.resultSet.next()).willReturn(true);
given(this.callableStatement.execute()).willReturn(true); given(this.callableStatement.execute()).willReturn(true);
given(this.callableStatement.getUpdateCount()).willReturn(-1); given(this.callableStatement.getUpdateCount()).willReturn(-1);
@@ -1066,7 +1066,7 @@ public class JdbcTemplateTests {
} }
@Test @Test
public void testCaseInsensitiveResultsMap() throws Exception { void testCaseInsensitiveResultsMap() throws Exception {
given(this.callableStatement.execute()).willReturn(false); given(this.callableStatement.execute()).willReturn(false);
given(this.callableStatement.getUpdateCount()).willReturn(-1); given(this.callableStatement.getUpdateCount()).willReturn(-1);
given(this.callableStatement.getObject(1)).willReturn("X"); given(this.callableStatement.getObject(1)).willReturn("X");

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify;
* @author Sam Brannen * @author Sam Brannen
* @since 02.08.2004 * @since 02.08.2004
*/ */
public class RowMapperTests { class RowMapperTests {
private final Connection connection = mock(); private final Connection connection = mock();
@@ -61,7 +61,7 @@ public class RowMapperTests {
private List<TestBean> result; private List<TestBean> result;
@BeforeEach @BeforeEach
public void setUp() throws SQLException { void setUp() throws SQLException {
given(connection.createStatement()).willReturn(statement); given(connection.createStatement()).willReturn(statement);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(statement.executeQuery(anyString())).willReturn(resultSet); given(statement.executeQuery(anyString())).willReturn(resultSet);
@@ -76,12 +76,12 @@ public class RowMapperTests {
} }
@AfterEach @AfterEach
public void verifyClosed() throws Exception { void verifyClosed() throws Exception {
verify(resultSet).close(); verify(resultSet).close();
} }
@AfterEach @AfterEach
public void verifyResults() { void verifyResults() {
assertThat(result).isNotNull(); assertThat(result).isNotNull();
assertThat(result).hasSize(2); assertThat(result).hasSize(2);
TestBean testBean1 = result.get(0); TestBean testBean1 = result.get(0);
@@ -93,19 +93,19 @@ public class RowMapperTests {
} }
@Test @Test
public void staticQueryWithRowMapper() throws SQLException { void staticQueryWithRowMapper() throws SQLException {
result = template.query("some SQL", testRowMapper); result = template.query("some SQL", testRowMapper);
verify(statement).close(); verify(statement).close();
} }
@Test @Test
public void preparedStatementCreatorWithRowMapper() throws SQLException { void preparedStatementCreatorWithRowMapper() throws SQLException {
result = template.query(con -> preparedStatement, testRowMapper); result = template.query(con -> preparedStatement, testRowMapper);
verify(preparedStatement).close(); verify(preparedStatement).close();
} }
@Test @Test
public void preparedStatementSetterWithRowMapper() throws SQLException { void preparedStatementSetterWithRowMapper() throws SQLException {
result = template.query("some SQL", ps -> ps.setString(1, "test"), testRowMapper); result = template.query("some SQL", ps -> ps.setString(1, "test"), testRowMapper);
verify(preparedStatement).setString(1, "test"); verify(preparedStatement).setString(1, "test");
verify(preparedStatement).close(); verify(preparedStatement).close();
@@ -121,7 +121,7 @@ public class RowMapperTests {
} }
@Test @Test
public void queryWithArgsAndTypesAndRowMapper() throws SQLException { void queryWithArgsAndTypesAndRowMapper() throws SQLException {
result = template.query("some SQL", result = template.query("some SQL",
new Object[] { "test1", "test2" }, new Object[] { "test1", "test2" },
new int[] { Types.VARCHAR, Types.VARCHAR }, new int[] { Types.VARCHAR, Types.VARCHAR },

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.jdbc.core; package org.springframework.jdbc.core;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
/** /**
* Simple row count callback handler for testing purposes. * Simple row count callback handler for testing purposes.
@@ -32,7 +31,7 @@ public class SimpleRowCountCallbackHandler implements RowCallbackHandler {
@Override @Override
public void processRow(ResultSet rs) throws SQLException { public void processRow(ResultSet rs) {
count++; count++;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import static org.mockito.Mockito.mock;
* @author Kazuki Shimizu * @author Kazuki Shimizu
* @since 5.0.4 * @since 5.0.4
*/ */
public class SingleColumnRowMapperTests { class SingleColumnRowMapperTests {
@Test // SPR-16483 @Test // SPR-16483
public void useDefaultConversionService() throws SQLException { public void useDefaultConversionService() throws SQLException {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -48,25 +48,25 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 31.08.2004 * @since 31.08.2004
*/ */
public class StatementCreatorUtilsTests { class StatementCreatorUtilsTests {
private PreparedStatement preparedStatement = mock(); private PreparedStatement preparedStatement = mock();
@Test @Test
public void testSetParameterValueWithNullAndType() throws SQLException { void testSetParameterValueWithNullAndType() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, null); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, null);
verify(preparedStatement).setNull(1, Types.VARCHAR); verify(preparedStatement).setNull(1, Types.VARCHAR);
} }
@Test @Test
public void testSetParameterValueWithNullAndTypeName() throws SQLException { void testSetParameterValueWithNullAndTypeName() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, "mytype", null); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, "mytype", null);
verify(preparedStatement).setNull(1, Types.VARCHAR, "mytype"); verify(preparedStatement).setNull(1, Types.VARCHAR, "mytype");
} }
@Test @Test
public void testSetParameterValueWithNullAndUnknownType() throws SQLException { void testSetParameterValueWithNullAndUnknownType() throws SQLException {
StatementCreatorUtils.shouldIgnoreGetParameterType = true; StatementCreatorUtils.shouldIgnoreGetParameterType = true;
Connection con = mock(); Connection con = mock();
DatabaseMetaData dbmd = mock(); DatabaseMetaData dbmd = mock();
@@ -80,7 +80,7 @@ public class StatementCreatorUtilsTests {
} }
@Test @Test
public void testSetParameterValueWithNullAndUnknownTypeOnInformix() throws SQLException { void testSetParameterValueWithNullAndUnknownTypeOnInformix() throws SQLException {
StatementCreatorUtils.shouldIgnoreGetParameterType = true; StatementCreatorUtils.shouldIgnoreGetParameterType = true;
Connection con = mock(); Connection con = mock();
DatabaseMetaData dbmd = mock(); DatabaseMetaData dbmd = mock();
@@ -96,7 +96,7 @@ public class StatementCreatorUtilsTests {
} }
@Test @Test
public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException { void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
StatementCreatorUtils.shouldIgnoreGetParameterType = true; StatementCreatorUtils.shouldIgnoreGetParameterType = true;
Connection con = mock(); Connection con = mock();
DatabaseMetaData dbmd = mock(); DatabaseMetaData dbmd = mock();
@@ -112,7 +112,7 @@ public class StatementCreatorUtilsTests {
} }
@Test @Test
public void testSetParameterValueWithNullAndGetParameterTypeWorking() throws SQLException { void testSetParameterValueWithNullAndGetParameterTypeWorking() throws SQLException {
ParameterMetaData pmd = mock(); ParameterMetaData pmd = mock();
given(preparedStatement.getParameterMetaData()).willReturn(pmd); given(preparedStatement.getParameterMetaData()).willReturn(pmd);
given(pmd.getParameterType(1)).willReturn(Types.SMALLINT); given(pmd.getParameterType(1)).willReturn(Types.SMALLINT);
@@ -123,13 +123,13 @@ public class StatementCreatorUtilsTests {
} }
@Test @Test
public void testSetParameterValueWithString() throws SQLException { void testSetParameterValueWithString() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, "test"); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, "test");
verify(preparedStatement).setString(1, "test"); verify(preparedStatement).setString(1, "test");
} }
@Test @Test
public void testSetParameterValueWithStringAndSpecialType() throws SQLException { void testSetParameterValueWithStringAndSpecialType() throws SQLException {
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.CHAR, null, "test"); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.CHAR, null, "test");
verify(preparedStatement).setObject(1, "test", Types.CHAR); verify(preparedStatement).setObject(1, "test", Types.CHAR);
} }
@@ -140,77 +140,77 @@ public class StatementCreatorUtilsTests {
} }
@Test @Test
public void testSetParameterValueWithSqlDate() throws SQLException { void testSetParameterValueWithSqlDate() throws SQLException {
java.sql.Date date = new java.sql.Date(1000); java.sql.Date date = new java.sql.Date(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
verify(preparedStatement).setDate(1, date); verify(preparedStatement).setDate(1, date);
} }
@Test @Test
public void testSetParameterValueWithDateAndUtilDate() throws SQLException { void testSetParameterValueWithDateAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000); java.util.Date date = new java.util.Date(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
verify(preparedStatement).setDate(1, new java.sql.Date(1000)); verify(preparedStatement).setDate(1, new java.sql.Date(1000));
} }
@Test @Test
public void testSetParameterValueWithDateAndCalendar() throws SQLException { void testSetParameterValueWithDateAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar(); java.util.Calendar cal = new GregorianCalendar();
StatementCreatorUtils.setParameterValue(preparedStatement, 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); verify(preparedStatement).setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
} }
@Test @Test
public void testSetParameterValueWithSqlTime() throws SQLException { void testSetParameterValueWithSqlTime() throws SQLException {
java.sql.Time time = new java.sql.Time(1000); java.sql.Time time = new java.sql.Time(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, time); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, time);
verify(preparedStatement).setTime(1, time); verify(preparedStatement).setTime(1, time);
} }
@Test @Test
public void testSetParameterValueWithTimeAndUtilDate() throws SQLException { void testSetParameterValueWithTimeAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000); java.util.Date date = new java.util.Date(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, date); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, date);
verify(preparedStatement).setTime(1, new java.sql.Time(1000)); verify(preparedStatement).setTime(1, new java.sql.Time(1000));
} }
@Test @Test
public void testSetParameterValueWithTimeAndCalendar() throws SQLException { void testSetParameterValueWithTimeAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar(); java.util.Calendar cal = new GregorianCalendar();
StatementCreatorUtils.setParameterValue(preparedStatement, 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); verify(preparedStatement).setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
} }
@Test @Test
public void testSetParameterValueWithSqlTimestamp() throws SQLException { void testSetParameterValueWithSqlTimestamp() throws SQLException {
java.sql.Timestamp timestamp = new java.sql.Timestamp(1000); java.sql.Timestamp timestamp = new java.sql.Timestamp(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, timestamp); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, timestamp);
verify(preparedStatement).setTimestamp(1, timestamp); verify(preparedStatement).setTimestamp(1, timestamp);
} }
@Test @Test
public void testSetParameterValueWithTimestampAndUtilDate() throws SQLException { void testSetParameterValueWithTimestampAndUtilDate() throws SQLException {
java.util.Date date = new java.util.Date(1000); java.util.Date date = new java.util.Date(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, date); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, date);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000)); verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
} }
@Test @Test
public void testSetParameterValueWithTimestampAndCalendar() throws SQLException { void testSetParameterValueWithTimestampAndCalendar() throws SQLException {
java.util.Calendar cal = new GregorianCalendar(); java.util.Calendar cal = new GregorianCalendar();
StatementCreatorUtils.setParameterValue(preparedStatement, 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); verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
} }
@Test @Test
public void testSetParameterValueWithDateAndUnknownType() throws SQLException { void testSetParameterValueWithDateAndUnknownType() throws SQLException {
java.util.Date date = new java.util.Date(1000); java.util.Date date = new java.util.Date(1000);
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, date); StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000)); verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
} }
@Test @Test
public void testSetParameterValueWithCalendarAndUnknownType() throws SQLException { void testSetParameterValueWithCalendarAndUnknownType() throws SQLException {
java.util.Calendar cal = new GregorianCalendar(); java.util.Calendar cal = new GregorianCalendar();
StatementCreatorUtils.setParameterValue(preparedStatement, 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); verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,23 +32,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class BeanPropertySqlParameterSourceTests { class BeanPropertySqlParameterSourceTests {
@Test @Test
public void withNullBeanPassedToCtor() { void withNullBeanPassedToCtor() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
new BeanPropertySqlParameterSource(null)); new BeanPropertySqlParameterSource(null));
} }
@Test @Test
public void getValueWhereTheUnderlyingBeanHasNoSuchProperty() { void getValueWhereTheUnderlyingBeanHasNoSuchProperty() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean()); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean());
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
source.getValue("thisPropertyDoesNotExist")); source.getValue("thisPropertyDoesNotExist"));
} }
@Test @Test
public void successfulPropertyAccess() { void successfulPropertyAccess() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
assertThat(Arrays.asList(source.getReadablePropertyNames())).contains("name"); assertThat(Arrays.asList(source.getReadablePropertyNames())).contains("name");
assertThat(Arrays.asList(source.getReadablePropertyNames())).contains("age"); assertThat(Arrays.asList(source.getReadablePropertyNames())).contains("age");
@@ -59,7 +59,7 @@ public class BeanPropertySqlParameterSourceTests {
} }
@Test @Test
public void successfulPropertyAccessWithOverriddenSqlType() { void successfulPropertyAccessWithOverriddenSqlType() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
source.registerSqlType("age", Types.NUMERIC); source.registerSqlType("age", Types.NUMERIC);
assertThat(source.getValue("name")).isEqualTo("tb"); assertThat(source.getValue("name")).isEqualTo("tb");
@@ -69,26 +69,26 @@ public class BeanPropertySqlParameterSourceTests {
} }
@Test @Test
public void hasValueWhereTheUnderlyingBeanHasNoSuchProperty() { void hasValueWhereTheUnderlyingBeanHasNoSuchProperty() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean()); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean());
assertThat(source.hasValue("thisPropertyDoesNotExist")).isFalse(); assertThat(source.hasValue("thisPropertyDoesNotExist")).isFalse();
} }
@Test @Test
public void getValueWhereTheUnderlyingBeanPropertyIsNotReadable() { void getValueWhereTheUnderlyingBeanPropertyIsNotReadable() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties()); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties());
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
source.getValue("noOp")); source.getValue("noOp"));
} }
@Test @Test
public void hasValueWhereTheUnderlyingBeanPropertyIsNotReadable() { void hasValueWhereTheUnderlyingBeanPropertyIsNotReadable() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties()); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties());
assertThat(source.hasValue("noOp")).isFalse(); assertThat(source.hasValue("noOp")).isFalse();
} }
@Test @Test
public void toStringShowsParameterDetails() { void toStringShowsParameterDetails() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
assertThat(source.toString()) assertThat(source.toString())
.startsWith("BeanPropertySqlParameterSource {") .startsWith("BeanPropertySqlParameterSource {")
@@ -98,7 +98,7 @@ public class BeanPropertySqlParameterSourceTests {
} }
@Test @Test
public void toStringShowsCustomSqlType() { void toStringShowsCustomSqlType() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
source.registerSqlType("name", Integer.MAX_VALUE); source.registerSqlType("name", Integer.MAX_VALUE);
assertThat(source.toString()) assertThat(source.toString())
@@ -109,7 +109,7 @@ public class BeanPropertySqlParameterSourceTests {
} }
@Test @Test
public void toStringDoesNotShowTypeUnknown() { void toStringDoesNotShowTypeUnknown() {
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
assertThat(source.toString()) assertThat(source.toString())
.startsWith("BeanPropertySqlParameterSource {") .startsWith("BeanPropertySqlParameterSource {")

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,22 +31,22 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class MapSqlParameterSourceTests { class MapSqlParameterSourceTests {
@Test @Test
public void nullParameterValuesPassedToCtorIsOk() { void nullParameterValuesPassedToCtorIsOk() {
new MapSqlParameterSource(null); new MapSqlParameterSource(null);
} }
@Test @Test
public void getValueChokesIfParameterIsNotPresent() { void getValueChokesIfParameterIsNotPresent() {
MapSqlParameterSource source = new MapSqlParameterSource(); MapSqlParameterSource source = new MapSqlParameterSource();
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
source.getValue("pechorin was right!")); source.getValue("pechorin was right!"));
} }
@Test @Test
public void sqlParameterValueRegistersSqlType() { void sqlParameterValueRegistersSqlType() {
MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo")); MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo"));
assertThat(msps.getSqlType("FOO")).as("Correct SQL Type not registered").isEqualTo(2); assertThat(msps.getSqlType("FOO")).as("Correct SQL Type not registered").isEqualTo(2);
MapSqlParameterSource msps2 = new MapSqlParameterSource(); MapSqlParameterSource msps2 = new MapSqlParameterSource();
@@ -55,19 +55,19 @@ public class MapSqlParameterSourceTests {
} }
@Test @Test
public void toStringShowsParameterDetails() { void toStringShowsParameterDetails() {
MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo")); MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo"));
assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo (type:NUMERIC)}"); assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo (type:NUMERIC)}");
} }
@Test @Test
public void toStringShowsCustomSqlType() { void toStringShowsCustomSqlType() {
MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Integer.MAX_VALUE, "Foo")); MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Integer.MAX_VALUE, "Foo"));
assertThat(source.toString()).isEqualTo(("MapSqlParameterSource {FOO=Foo (type:" + Integer.MAX_VALUE + ")}")); assertThat(source.toString()).isEqualTo(("MapSqlParameterSource {FOO=Foo (type:" + Integer.MAX_VALUE + ")}"));
} }
@Test @Test
public void toStringDoesNotShowTypeUnknown() { void toStringDoesNotShowTypeUnknown() {
MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(JdbcUtils.TYPE_UNKNOWN, "Foo")); MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(JdbcUtils.TYPE_UNKNOWN, "Foo"));
assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo}"); assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo}");
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -61,7 +61,7 @@ import static org.mockito.Mockito.verify;
* @author Nikita Khateev * @author Nikita Khateev
* @author Fedor Bobin * @author Fedor Bobin
*/ */
public class NamedParameterJdbcTemplateTests { class NamedParameterJdbcTemplateTests {
private static final String SELECT_NAMED_PARAMETERS = private static final String SELECT_NAMED_PARAMETERS =
"select id, forename from custmr where id = :id and country = :country"; "select id, forename from custmr where id = :id and country = :country";
@@ -99,7 +99,7 @@ public class NamedParameterJdbcTemplateTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(preparedStatement.getConnection()).willReturn(connection); given(preparedStatement.getConnection()).willReturn(connection);
@@ -110,24 +110,24 @@ public class NamedParameterJdbcTemplateTests {
@Test @Test
public void testNullDataSourceProvidedToCtor() { void testNullDataSourceProvidedToCtor() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
new NamedParameterJdbcTemplate((DataSource) null)); new NamedParameterJdbcTemplate((DataSource) null));
} }
@Test @Test
public void testNullJdbcTemplateProvidedToCtor() { void testNullJdbcTemplateProvidedToCtor() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
new NamedParameterJdbcTemplate((JdbcOperations) null)); new NamedParameterJdbcTemplate((JdbcOperations) null));
} }
@Test @Test
public void testTemplateConfiguration() { void testTemplateConfiguration() {
assertThat(namedParameterTemplate.getJdbcTemplate().getDataSource()).isSameAs(dataSource); assertThat(namedParameterTemplate.getJdbcTemplate().getDataSource()).isSameAs(dataSource);
} }
@Test @Test
public void testExecute() throws SQLException { void testExecute() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.put("perfId", 1); params.put("perfId", 1);
@@ -149,7 +149,7 @@ public class NamedParameterJdbcTemplateTests {
@Disabled("SPR-16340") @Disabled("SPR-16340")
@Test @Test
public void testExecuteArray() throws SQLException { void testExecuteArray() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
List<Integer> typeIds = Arrays.asList(1, 2, 3); List<Integer> typeIds = Arrays.asList(1, 2, 3);
@@ -174,7 +174,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testExecuteWithTypedParameters() throws SQLException { void testExecuteWithTypedParameters() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
@@ -195,7 +195,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testExecuteNoParameters() throws SQLException { void testExecuteNoParameters() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS, Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
@@ -212,7 +212,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithResultSetExtractor() throws SQLException { void testQueryWithResultSetExtractor() throws SQLException {
given(resultSet.next()).willReturn(true); given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -239,7 +239,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithResultSetExtractorNoParameters() throws SQLException { void testQueryWithResultSetExtractorNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true); given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -262,7 +262,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithRowCallbackHandler() throws SQLException { void testQueryWithRowCallbackHandler() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -289,7 +289,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithRowCallbackHandlerNoParameters() throws SQLException { void testQueryWithRowCallbackHandlerNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -312,7 +312,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithRowMapper() throws SQLException { void testQueryWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -339,7 +339,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryWithRowMapperNoParameters() throws SQLException { void testQueryWithRowMapperNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -362,7 +362,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryForObjectWithRowMapper() throws SQLException { void testQueryForObjectWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -389,7 +389,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testQueryForStreamWithRowMapper() throws SQLException { void testQueryForStreamWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -422,7 +422,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testUpdate() throws SQLException { void testUpdate() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.put("perfId", 1); params.put("perfId", 1);
@@ -438,7 +438,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testUpdateWithTypedParameters() throws SQLException { void testUpdateWithTypedParameters() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
@@ -454,7 +454,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithPlainMap() throws Exception { void testBatchUpdateWithPlainMap() throws Exception {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Map<String, Integer>[] ids = new Map[2]; final Map<String, Integer>[] ids = new Map[2];
ids[0] = Collections.singletonMap("id", 100); ids[0] = Collections.singletonMap("id", 100);
@@ -479,7 +479,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithEmptyMap() throws Exception { void testBatchUpdateWithEmptyMap() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Map<String, Integer>[] ids = new Map[0]; final Map<String, Integer>[] ids = new Map[0];
namedParameterTemplate = new NamedParameterJdbcTemplate(new JdbcTemplate(dataSource, false)); namedParameterTemplate = new NamedParameterJdbcTemplate(new JdbcTemplate(dataSource, false));
@@ -490,7 +490,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithSqlParameterSource() throws Exception { void testBatchUpdateWithSqlParameterSource() throws Exception {
SqlParameterSource[] ids = new SqlParameterSource[2]; SqlParameterSource[] ids = new SqlParameterSource[2];
ids[0] = new MapSqlParameterSource("id", 100); ids[0] = new MapSqlParameterSource("id", 100);
ids[1] = new MapSqlParameterSource("id", 200); ids[1] = new MapSqlParameterSource("id", 200);
@@ -514,7 +514,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithInClause() throws Exception { void testBatchUpdateWithInClause() throws Exception {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object>[] parameters = new Map[3]; Map<String, Object>[] parameters = new Map[3];
parameters[0] = Collections.singletonMap("ids", Arrays.asList(1, 2)); parameters[0] = Collections.singletonMap("ids", Arrays.asList(1, 2));
@@ -554,7 +554,7 @@ public class NamedParameterJdbcTemplateTests {
} }
@Test @Test
public void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception { void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception {
SqlParameterSource[] ids = new SqlParameterSource[3]; SqlParameterSource[] ids = new SqlParameterSource[3];
ids[0] = new MapSqlParameterSource().addValue("id", null, Types.NULL); ids[0] = new MapSqlParameterSource().addValue("id", null, Types.NULL);
ids[1] = new MapSqlParameterSource().addValue("id", 100, Types.NUMERIC); ids[1] = new MapSqlParameterSource().addValue("id", 100, Types.NUMERIC);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify;
* @author Thomas Risberg * @author Thomas Risberg
* @author Phillip Webb * @author Phillip Webb
*/ */
public class NamedParameterQueryTests { class NamedParameterQueryTests {
private Connection connection = mock(); private Connection connection = mock();
@@ -60,7 +60,7 @@ public class NamedParameterQueryTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
given(resultSetMetaData.getColumnCount()).willReturn(1); given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("age"); given(resultSetMetaData.getColumnLabel(1)).willReturn("age");
@@ -69,7 +69,7 @@ public class NamedParameterQueryTests {
} }
@AfterEach @AfterEach
public void verifyClose() throws Exception { void verifyClose() throws Exception {
verify(preparedStatement).close(); verify(preparedStatement).close();
verify(resultSet).close(); verify(resultSet).close();
verify(connection).close(); verify(connection).close();
@@ -77,7 +77,7 @@ public class NamedParameterQueryTests {
@Test @Test
public void testQueryForListWithParamMap() throws Exception { void testQueryForListWithParamMap() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getObject(1)).willReturn(11, 12); given(resultSet.getObject(1)).willReturn(11, 12);
@@ -96,7 +96,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForListWithParamMapAndEmptyResult() throws Exception { void testQueryForListWithParamMapAndEmptyResult() throws Exception {
given(resultSet.next()).willReturn(false); given(resultSet.next()).willReturn(false);
MapSqlParameterSource params = new MapSqlParameterSource(); MapSqlParameterSource params = new MapSqlParameterSource();
@@ -110,7 +110,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForListWithParamMapAndSingleRowAndColumn() throws Exception { void testQueryForListWithParamMapAndSingleRowAndColumn() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -127,7 +127,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn() throws Exception { void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(11); given(resultSet.getInt(1)).willReturn(11);
@@ -137,14 +137,13 @@ public class NamedParameterQueryTests {
List<Integer> li = template.queryForList("SELECT AGE FROM CUSTMR WHERE ID < :id", List<Integer> li = template.queryForList("SELECT AGE FROM CUSTMR WHERE ID < :id",
params, Integer.class); params, Integer.class);
assertThat(li.size()).as("All rows returned").isEqualTo(1); assertThat(li).containsExactly(11);
assertThat(li).element(0).as("First row is Integer").isEqualTo(11);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3); verify(preparedStatement).setObject(1, 3);
} }
@Test @Test
public void testQueryForMapWithParamMapAndSingleRowAndColumn() throws Exception { void testQueryForMapWithParamMapAndSingleRowAndColumn() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -159,7 +158,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForObjectWithParamMapAndRowMapper() throws Exception { void testQueryForObjectWithParamMapAndRowMapper() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -174,7 +173,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForObjectWithMapAndInteger() throws Exception { void testQueryForObjectWithMapAndInteger() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -190,7 +189,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForObjectWithParamMapAndInteger() throws Exception { void testQueryForObjectWithParamMapAndInteger() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -206,7 +205,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForObjectWithParamMapAndList() throws Exception { void testQueryForObjectWithParamMapAndList() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -221,7 +220,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForObjectWithParamMapAndListOfExpressionLists() throws Exception { void testQueryForObjectWithParamMapAndListOfExpressionLists() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -240,7 +239,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForIntWithParamMap() throws Exception { void testQueryForIntWithParamMap() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -255,7 +254,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForLongWithParamBean() throws Exception { void testQueryForLongWithParamBean() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -269,7 +268,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForLongWithParamBeanWithCollection() throws Exception { void testQueryForLongWithParamBeanWithCollection() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -284,7 +283,7 @@ public class NamedParameterQueryTests {
} }
@Test @Test
public void testQueryForLongWithParamRecord() throws Exception { void testQueryForLongWithParamRecord() throws Exception {
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify;
* *
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class CallMetaDataContextTests { class CallMetaDataContextTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -57,19 +57,19 @@ public class CallMetaDataContextTests {
@BeforeEach @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
given(connection.getMetaData()).willReturn(databaseMetaData); given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
} }
@AfterEach @AfterEach
public void verifyClosed() throws Exception { void verifyClosed() throws Exception {
verify(connection).close(); verify(connection).close();
} }
@Test @Test
public void testMatchParameterValuesAndSqlInOutParameters() throws Exception { void testMatchParameterValuesAndSqlInOutParameters() throws Exception {
final String TABLE = "customers"; final String TABLE = "customers";
final String USER = "me"; final String USER = "me";
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB"); given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 6.1 * @since 6.1
*/ */
public class JdbcClientIndexedParameterTests { class JdbcClientIndexedParameterTests {
private static final String SELECT_INDEXED_PARAMETERS = private static final String SELECT_INDEXED_PARAMETERS =
"select id, forename from custmr where id = ? and country = ?"; "select id, forename from custmr where id = ? and country = ?";
@@ -84,7 +84,7 @@ public class JdbcClientIndexedParameterTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(preparedStatement.getConnection()).willReturn(connection); given(preparedStatement.getConnection()).willReturn(connection);
@@ -95,7 +95,7 @@ public class JdbcClientIndexedParameterTests {
@Test @Test
public void queryWithResultSetExtractor() throws SQLException { void queryWithResultSetExtractor() throws SQLException {
given(resultSet.next()).willReturn(true); given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -122,7 +122,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryWithResultSetExtractorNoParameters() throws SQLException { void queryWithResultSetExtractorNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true); given(resultSet.next()).willReturn(true);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -145,7 +145,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryWithRowCallbackHandler() throws SQLException { void queryWithRowCallbackHandler() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -172,7 +172,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryWithRowCallbackHandlerNoParameters() throws SQLException { void queryWithRowCallbackHandlerNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -195,7 +195,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryWithRowMapper() throws SQLException { void queryWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -223,7 +223,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryWithRowMapperNoParameters() throws SQLException { void queryWithRowMapperNoParameters() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -247,7 +247,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryForObjectWithRowMapper() throws SQLException { void queryForObjectWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -274,7 +274,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void queryForStreamWithRowMapper() throws SQLException { void queryForStreamWithRowMapper() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -307,7 +307,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void update() throws SQLException { void update() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.add(1); params.add(1);
@@ -323,7 +323,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void updateWithTypedParameters() throws SQLException { void updateWithTypedParameters() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
params.add(new SqlParameterValue(Types.DECIMAL, 1)); params.add(new SqlParameterValue(Types.DECIMAL, 1));
@@ -339,7 +339,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void updateWithGeneratedKeys() throws SQLException { void updateWithGeneratedKeys() throws SQLException {
given(resultSetMetaData.getColumnCount()).willReturn(1); given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1"); given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
@@ -363,7 +363,7 @@ public class JdbcClientIndexedParameterTests {
} }
@Test @Test
public void updateWithGeneratedKeysAndKeyColumnNames() throws SQLException { void updateWithGeneratedKeysAndKeyColumnNames() throws SQLException {
given(resultSetMetaData.getColumnCount()).willReturn(1); given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1"); given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -155,6 +155,6 @@ class JdbcClientIntegrationTests {
} }
record User(long id, String firstName, String lastName) {}; record User(long id, String firstName, String lastName) {}
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -430,7 +430,7 @@ class JdbcClientNamedParameterTests {
} }
@Test @Test
public void updateWithGeneratedKeysAndKeyColumnNames() throws SQLException { void updateWithGeneratedKeysAndKeyColumnNames() throws SQLException {
given(resultSetMetaData.getColumnCount()).willReturn(1); given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1"); given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 6.1 * @since 6.1
*/ */
public class JdbcClientQueryTests { class JdbcClientQueryTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -60,7 +60,7 @@ public class JdbcClientQueryTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
given(preparedStatement.executeQuery()).willReturn(resultSet); given(preparedStatement.executeQuery()).willReturn(resultSet);
@@ -73,7 +73,7 @@ public class JdbcClientQueryTests {
// Indexed parameters // Indexed parameters
@Test @Test
public void queryForListWithIndexedParam() throws Exception { void queryForListWithIndexedParam() throws Exception {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getObject(1)).willReturn(11, 12); given(resultSet.getObject(1)).willReturn(11, 12);
@@ -92,7 +92,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithIndexedParamAndEmptyResult() throws Exception { void queryForListWithIndexedParamAndEmptyResult() throws Exception {
given(resultSet.next()).willReturn(false); given(resultSet.next()).willReturn(false);
List<Map<String, Object>> li = client.sql("SELECT AGE FROM CUSTMR WHERE ID < ?") List<Map<String, Object>> li = client.sql("SELECT AGE FROM CUSTMR WHERE ID < ?")
@@ -107,7 +107,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithIndexedParamAndSingleRow() throws Exception { void queryForListWithIndexedParamAndSingleRow() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -124,7 +124,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForMapWithIndexedParamAndSingleRow() throws Exception { void queryForMapWithIndexedParamAndSingleRow() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -141,7 +141,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithIndexedParamAndSingleColumn() throws Exception { void queryForListWithIndexedParamAndSingleColumn() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -149,8 +149,7 @@ public class JdbcClientQueryTests {
.param(1, 3) .param(1, 3)
.query().singleColumn(); .query().singleColumn();
assertThat(li.size()).as("All rows returned").isEqualTo(1); assertThat(li).containsExactly(11);
assertThat(li).element(0).as("First row is Integer").isEqualTo(11);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3); verify(preparedStatement).setObject(1, 3);
verify(resultSet).close(); verify(resultSet).close();
@@ -159,7 +158,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithIndexedParamAndSingleValue() throws Exception { void queryForIntegerWithIndexedParamAndSingleValue() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(22); given(resultSet.getObject(1)).willReturn(22);
@@ -176,7 +175,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithIndexedParamAndRowMapper() throws Exception { void queryForIntegerWithIndexedParamAndRowMapper() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -194,7 +193,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForOptionalWithIndexedParamAndRowMapper() throws Exception { void queryForOptionalWithIndexedParamAndRowMapper() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -212,7 +211,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithIndexedParam() throws Exception { void queryForIntegerWithIndexedParam() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -229,7 +228,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntWithIndexedParam() throws Exception { void queryForIntWithIndexedParam() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -246,7 +245,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForObjectWithIndexedParamAndList() { void queryForObjectWithIndexedParamAndList() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
client.sql("SELECT AGE FROM CUSTMR WHERE ID IN (?)").param(Arrays.asList(3, 4)).query().singleValue()); client.sql("SELECT AGE FROM CUSTMR WHERE ID IN (?)").param(Arrays.asList(3, 4)).query().singleValue());
} }
@@ -255,7 +254,7 @@ public class JdbcClientQueryTests {
// Named parameters // Named parameters
@Test @Test
public void queryForListWithNamedParam() throws Exception { void queryForListWithNamedParam() throws Exception {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getObject(1)).willReturn(11, 12); given(resultSet.getObject(1)).willReturn(11, 12);
@@ -275,7 +274,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithNamedParamAndEmptyResult() throws Exception { void queryForListWithNamedParamAndEmptyResult() throws Exception {
given(resultSet.next()).willReturn(false); given(resultSet.next()).willReturn(false);
List<Map<String, Object>> li = client.sql("SELECT AGE FROM CUSTMR WHERE ID < :id") List<Map<String, Object>> li = client.sql("SELECT AGE FROM CUSTMR WHERE ID < :id")
@@ -291,7 +290,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithNamedParamAndSingleRow() throws Exception { void queryForListWithNamedParamAndSingleRow() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -309,7 +308,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForMapWithNamedParamAndSingleRow() throws Exception { void queryForMapWithNamedParamAndSingleRow() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -326,7 +325,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForListWithNamedParamAndSingleColumn() throws Exception { void queryForListWithNamedParamAndSingleColumn() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11); given(resultSet.getObject(1)).willReturn(11);
@@ -334,8 +333,7 @@ public class JdbcClientQueryTests {
.param("id", 3) .param("id", 3)
.query().singleColumn(); .query().singleColumn();
assertThat(li.size()).as("All rows returned").isEqualTo(1); assertThat(li).containsExactly(11);
assertThat(li).element(0).as("First row is Integer").isEqualTo(11);
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
verify(preparedStatement).setObject(1, 3); verify(preparedStatement).setObject(1, 3);
verify(resultSet).close(); verify(resultSet).close();
@@ -344,7 +342,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithNamedParamAndSingleValue() throws Exception { void queryForIntegerWithNamedParamAndSingleValue() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(22); given(resultSet.getObject(1)).willReturn(22);
@@ -361,7 +359,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithNamedParamAndRowMapper() throws Exception { void queryForIntegerWithNamedParamAndRowMapper() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -379,7 +377,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForOptionalWithNamedParamAndRowMapper() throws Exception { void queryForOptionalWithNamedParamAndRowMapper() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -397,7 +395,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithNamedParam() throws Exception { void queryForIntegerWithNamedParam() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -414,7 +412,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithNamedParamAndList() throws Exception { void queryForIntegerWithNamedParamAndList() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -432,7 +430,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntegerWithNamedParamAndListOfExpressionLists() throws Exception { void queryForIntegerWithNamedParamAndListOfExpressionLists() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -455,7 +453,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForIntWithNamedParam() throws Exception { void queryForIntWithNamedParam() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -472,7 +470,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForLongWithParamBean() throws Exception { void queryForLongWithParamBean() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -489,7 +487,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForLongWithParamBeanWithCollection() throws Exception { void queryForLongWithParamBeanWithCollection() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -507,7 +505,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForLongWithParamRecord() throws Exception { void queryForLongWithParamRecord() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -524,7 +522,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForLongWithParamFieldHolder() throws Exception { void queryForLongWithParamFieldHolder() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getLong(1)).willReturn(87L); given(resultSet.getLong(1)).willReturn(87L);
@@ -541,7 +539,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForMappedRecordWithNamedParam() throws Exception { void queryForMappedRecordWithNamedParam() throws Exception {
given(resultSet.findColumn("age")).willReturn(1); given(resultSet.findColumn("age")).willReturn(1);
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);
@@ -559,7 +557,7 @@ public class JdbcClientQueryTests {
} }
@Test @Test
public void queryForMappedFieldHolderWithNamedParam() throws Exception { void queryForMappedFieldHolderWithNamedParam() throws Exception {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(22); given(resultSet.getInt(1)).willReturn(22);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -79,7 +79,7 @@ class SimpleJdbcCallTests {
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC); SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
try { try {
assertThatExceptionOfType(BadSqlGrammarException.class) assertThatExceptionOfType(BadSqlGrammarException.class)
.isThrownBy(() -> sproc.execute()) .isThrownBy(sproc::execute)
.withCause(sqlException); .withCause(sqlException);
} }
finally { finally {
@@ -89,7 +89,7 @@ class SimpleJdbcCallTests {
} }
@Test @Test
void unnamedParameterHandling() throws Exception { void unnamedParameterHandling() {
final String MY_PROC = "my_proc"; final String MY_PROC = "my_proc";
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC); SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC);
// Shouldn't succeed in adding unnamed parameter // Shouldn't succeed in adding unnamed parameter

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -52,7 +52,7 @@ class SimpleJdbcInsertIntegrationTests {
class UnquotedIdentifiersInSchemaTests extends AbstractSimpleJdbcInsertIntegrationTests { class UnquotedIdentifiersInSchemaTests extends AbstractSimpleJdbcInsertIntegrationTests {
@Test @Test
void retrieveColumnNamesFromMetadata() throws Exception { void retrieveColumnNamesFromMetadata() {
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
.withTableName("users") .withTableName("users")
.usingGeneratedKeyColumns("id"); .usingGeneratedKeyColumns("id");
@@ -80,7 +80,7 @@ class SimpleJdbcInsertIntegrationTests {
} }
@Test // gh-24013 @Test // gh-24013
void usingColumnsAndQuotedIdentifiers() throws Exception { void usingColumnsAndQuotedIdentifiers() {
// NOTE: unquoted identifiers in H2/HSQL must be converted to UPPERCASE // NOTE: unquoted identifiers in H2/HSQL must be converted to UPPERCASE
// since that's how they are stored in the DB metadata. // since that's how they are stored in the DB metadata.
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
@@ -118,7 +118,7 @@ class SimpleJdbcInsertIntegrationTests {
class QuotedIdentifiersInSchemaTests extends AbstractSimpleJdbcInsertIntegrationTests { class QuotedIdentifiersInSchemaTests extends AbstractSimpleJdbcInsertIntegrationTests {
@Test @Test
void retrieveColumnNamesFromMetadata() throws Exception { void retrieveColumnNamesFromMetadata() {
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
.withTableName("Order") .withTableName("Order")
.usingGeneratedKeyColumns("id"); .usingGeneratedKeyColumns("id");
@@ -134,7 +134,7 @@ class SimpleJdbcInsertIntegrationTests {
} }
@Test // gh-24013 @Test // gh-24013
void usingColumnsAndQuotedIdentifiers() throws Exception { void usingColumnsAndQuotedIdentifiers() {
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
.withoutTableColumnMetaDataAccess() .withoutTableColumnMetaDataAccess()
.withTableName("Order") .withTableName("Order")
@@ -194,7 +194,7 @@ class SimpleJdbcInsertIntegrationTests {
} }
@Test // gh-24013 @Test // gh-24013
void usingColumnsAndQuotedIdentifiersWithSchemaName() throws Exception { void usingColumnsAndQuotedIdentifiersWithSchemaName() {
// NOTE: unquoted identifiers in H2/HSQL must be converted to UPPERCASE // NOTE: unquoted identifiers in H2/HSQL must be converted to UPPERCASE
// since that's how they are stored in the DB metadata. // since that's how they are stored in the DB metadata.
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
@@ -252,7 +252,7 @@ class SimpleJdbcInsertIntegrationTests {
} }
@Test // gh-24013 @Test // gh-24013
void usingColumnsAndQuotedIdentifiersWithSchemaName() throws Exception { void usingColumnsAndQuotedIdentifiersWithSchemaName() {
SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase) SimpleJdbcInsert insert = new SimpleJdbcInsert(embeddedDatabase)
.withoutTableColumnMetaDataAccess() .withoutTableColumnMetaDataAccess()
.withSchemaName("My_Schema") .withSchemaName("My_Schema")

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify;
* *
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class TableMetaDataContextTests { class TableMetaDataContextTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -56,14 +56,14 @@ public class TableMetaDataContextTests {
@BeforeEach @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
given(connection.getMetaData()).willReturn(databaseMetaData); given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
} }
@Test @Test
public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception { void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
final String TABLE = "customers"; final String TABLE = "customers";
final String USER = "me"; final String USER = "me";
@@ -119,7 +119,7 @@ public class TableMetaDataContextTests {
} }
@Test @Test
public void testTableWithSingleColumnGeneratedKey() throws Exception { void testTableWithSingleColumnGeneratedKey() throws Exception {
final String TABLE = "customers"; final String TABLE = "customers";
final String USER = "me"; final String USER = "me";

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,10 +32,10 @@ import static org.mockito.Mockito.mock;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 30.07.2003 * @since 30.07.2003
*/ */
public class JdbcDaoSupportTests { class JdbcDaoSupportTests {
@Test @Test
public void testJdbcDaoSupportWithDataSource() throws Exception { void testJdbcDaoSupportWithDataSource() {
DataSource ds = mock(); DataSource ds = mock();
final List<String> test = new ArrayList<>(); final List<String> test = new ArrayList<>();
JdbcDaoSupport dao = new JdbcDaoSupport() { JdbcDaoSupport dao = new JdbcDaoSupport() {
@@ -52,7 +52,7 @@ public class JdbcDaoSupportTests {
} }
@Test @Test
public void testJdbcDaoSupportWithJdbcTemplate() throws Exception { void testJdbcDaoSupportWithJdbcTemplate() {
JdbcTemplate template = new JdbcTemplate(); JdbcTemplate template = new JdbcTemplate();
final List<String> test = new ArrayList<>(); final List<String> test = new ArrayList<>();
JdbcDaoSupport dao = new JdbcDaoSupport() { JdbcDaoSupport dao = new JdbcDaoSupport() {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,10 +37,10 @@ import static org.mockito.Mockito.verify;
/** /**
* @author Alef Arendsen * @author Alef Arendsen
*/ */
public class LobSupportTests { class LobSupportTests {
@Test @Test
public void testCreatingPreparedStatementCallback() throws SQLException { void testCreatingPreparedStatementCallback() throws SQLException {
LobHandler handler = mock(); LobHandler handler = mock();
LobCreator creator = mock(); LobCreator creator = mock();
PreparedStatement ps = mock(); PreparedStatement ps = mock();
@@ -69,7 +69,7 @@ public class LobSupportTests {
} }
@Test @Test
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException { void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
ResultSet rs = mock(); ResultSet rs = mock();
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false); AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class) assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
@@ -78,7 +78,7 @@ public class LobSupportTests {
} }
@Test @Test
public void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException { void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException {
ResultSet rs = mock(); ResultSet rs = mock();
given(rs.next()).willReturn(true, false); given(rs.next()).willReturn(true, false);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false); AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
@@ -87,7 +87,7 @@ public class LobSupportTests {
} }
@Test @Test
public void testAbstractLobStreamingResultSetExtractorMultipleRows() throws SQLException { void testAbstractLobStreamingResultSetExtractorMultipleRows() throws SQLException {
ResultSet rs = mock(); ResultSet rs = mock();
given(rs.next()).willReturn(true, true, false); given(rs.next()).willReturn(true, true, false);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false); AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
@@ -97,7 +97,7 @@ public class LobSupportTests {
} }
@Test @Test
public void testAbstractLobStreamingResultSetExtractorCorrectException() throws SQLException { void testAbstractLobStreamingResultSetExtractorCorrectException() throws SQLException {
ResultSet rs = mock(); ResultSet rs = mock();
given(rs.next()).willReturn(true); given(rs.next()).willReturn(true);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(true); AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(true);
@@ -106,7 +106,7 @@ public class LobSupportTests {
} }
private AbstractLobStreamingResultSetExtractor<Void> getResultSetExtractor(final boolean ex) { private AbstractLobStreamingResultSetExtractor<Void> getResultSetExtractor(final boolean ex) {
AbstractLobStreamingResultSetExtractor<Void> lobRse = new AbstractLobStreamingResultSetExtractor<>() { return new AbstractLobStreamingResultSetExtractor<>() {
@Override @Override
protected void streamData(ResultSet rs) throws SQLException, IOException { protected void streamData(ResultSet rs) throws SQLException, IOException {
if (ex) { if (ex) {
@@ -117,7 +117,6 @@ public class LobSupportTests {
} }
} }
}; };
return lobRse;
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -96,7 +96,7 @@ class SqlLobValueTests {
} }
@Test @Test
void test3() throws SQLException { void test3() {
SqlLobValue lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12); SqlLobValue lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test")); lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test"));
@@ -132,7 +132,7 @@ class SqlLobValueTests {
} }
@Test @Test
void test7() throws SQLException { void test7() {
SqlLobValue lob = new SqlLobValue("bla".getBytes()); SqlLobValue lob = new SqlLobValue("bla".getBytes());
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test")); lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test"));
@@ -182,7 +182,7 @@ class SqlLobValueTests {
} }
@Test @Test
void testOtherSqlType() throws SQLException { void testOtherSqlType() {
SqlLobValue lob = new SqlLobValue("Bla", handler); SqlLobValue lob = new SqlLobValue("Bla", handler);
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test")); lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test"));

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,6 @@ import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status; import jakarta.transaction.Status;
import jakarta.transaction.SystemException; import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction; import jakarta.transaction.Transaction;
@@ -61,7 +60,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 17.10.2005 * @since 17.10.2005
*/ */
public class DataSourceJtaTransactionTests { class DataSourceJtaTransactionTests {
private DataSource dataSource = mock(); private DataSource dataSource = mock();
@@ -75,12 +74,12 @@ public class DataSourceJtaTransactionTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
} }
@AfterEach @AfterEach
public void verifyTransactionSynchronizationManagerState() { void verifyTransactionSynchronizationManagerState() {
assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull();
@@ -91,12 +90,12 @@ public class DataSourceJtaTransactionTests {
@Test @Test
public void testJtaTransactionCommit() throws Exception { void testJtaTransactionCommit() throws Exception {
doTestJtaTransaction(false); doTestJtaTransaction(false);
} }
@Test @Test
public void testJtaTransactionRollback() throws Exception { void testJtaTransactionRollback() throws Exception {
doTestJtaTransaction(true); doTestJtaTransaction(true);
} }
@@ -146,52 +145,52 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false); doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false); doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false); doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false); doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true); doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true);
} }
@Test @Test
public void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception { void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false); doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false);
} }
@Test @Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception { void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false); doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false);
} }
@Test @Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception { void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false); doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false);
} }
@Test @Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception { void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false); doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false);
} }
@Test @Test
public void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception { void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true); doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true);
} }
@@ -317,22 +316,22 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception { void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false); doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception { void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true); doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false); doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception {
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true); doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true);
} }
@@ -406,42 +405,42 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true);
} }
@Test @Test
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception { void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception {
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true); doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true);
} }
@@ -546,21 +545,16 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception { void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
@SuppressWarnings("serial") @SuppressWarnings("serial")
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) { JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {
@Override @Override
protected void doRegisterAfterCompletionWithJtaTransaction( protected void doRegisterAfterCompletionWithJtaTransaction(
JtaTransactionObject txObject, JtaTransactionObject txObject,
final List<TransactionSynchronization> synchronizations) final List<TransactionSynchronization> synchronizations) {
throws RollbackException, SystemException { Thread async = new Thread(() -> invokeAfterCompletion(
Thread async = new Thread() { synchronizations, TransactionSynchronization.STATUS_COMMITTED));
@Override
public void run() {
invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
}
};
async.start(); async.start();
try { try {
async.join(); async.join();
@@ -608,7 +602,7 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception { void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
given(userTransaction.getStatus()).willReturn( given(userTransaction.getStatus()).willReturn(
Status.STATUS_NO_TRANSACTION, Status.STATUS_NO_TRANSACTION,
Status.STATUS_ACTIVE, Status.STATUS_ACTIVE,
@@ -655,12 +649,12 @@ public class DataSourceJtaTransactionTests {
} }
@Test @Test
public void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception { void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(false); doTestJtaTransactionWithIsolationLevelDataSourceRouter(false);
} }
@Test @Test
public void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception { void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception {
doTestJtaTransactionWithIsolationLevelDataSourceRouter(true); doTestJtaTransactionWithIsolationLevelDataSourceRouter(true);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -68,7 +68,7 @@ import static org.springframework.core.testfixture.TestGroup.LONG_RUNNING;
* @since 04.07.2003 * @since 04.07.2003
* @see org.springframework.jdbc.support.JdbcTransactionManagerTests * @see org.springframework.jdbc.support.JdbcTransactionManagerTests
*/ */
public class DataSourceTransactionManagerTests<T extends DataSourceTransactionManager> { public class DataSourceTransactionManagerTests {
protected DataSource ds = mock(); protected DataSource ds = mock();
@@ -78,7 +78,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
tm = createTransactionManager(ds); tm = createTransactionManager(ds);
given(ds.getConnection()).willReturn(con); given(ds.getConnection()).willReturn(con);
} }
@@ -88,7 +88,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@AfterEach @AfterEach
public void verifyTransactionSynchronizationManagerState() { void verifyTransactionSynchronizationManagerState() {
assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
@@ -97,32 +97,32 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
@Test @Test
public void testTransactionCommitWithAutoCommitTrue() throws Exception { void testTransactionCommitWithAutoCommitTrue() throws Exception {
doTestTransactionCommitRestoringAutoCommit(true, false, false); doTestTransactionCommitRestoringAutoCommit(true, false, false);
} }
@Test @Test
public void testTransactionCommitWithAutoCommitFalse() throws Exception { void testTransactionCommitWithAutoCommitFalse() throws Exception {
doTestTransactionCommitRestoringAutoCommit(false, false, false); doTestTransactionCommitRestoringAutoCommit(false, false, false);
} }
@Test @Test
public void testTransactionCommitWithAutoCommitTrueAndLazyConnection() throws Exception { void testTransactionCommitWithAutoCommitTrueAndLazyConnection() throws Exception {
doTestTransactionCommitRestoringAutoCommit(true, true, false); doTestTransactionCommitRestoringAutoCommit(true, true, false);
} }
@Test @Test
public void testTransactionCommitWithAutoCommitFalseAndLazyConnection() throws Exception { void testTransactionCommitWithAutoCommitFalseAndLazyConnection() throws Exception {
doTestTransactionCommitRestoringAutoCommit(false, true, false); doTestTransactionCommitRestoringAutoCommit(false, true, false);
} }
@Test @Test
public void testTransactionCommitWithAutoCommitTrueAndLazyConnectionAndStatementCreated() throws Exception { void testTransactionCommitWithAutoCommitTrueAndLazyConnectionAndStatementCreated() throws Exception {
doTestTransactionCommitRestoringAutoCommit(true, true, true); doTestTransactionCommitRestoringAutoCommit(true, true, true);
} }
@Test @Test
public void testTransactionCommitWithAutoCommitFalseAndLazyConnectionAndStatementCreated() throws Exception { void testTransactionCommitWithAutoCommitFalseAndLazyConnectionAndStatementCreated() throws Exception {
doTestTransactionCommitRestoringAutoCommit(false, true, true); doTestTransactionCommitRestoringAutoCommit(false, true, true);
} }
@@ -184,32 +184,32 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitTrue() throws Exception { void testTransactionRollbackWithAutoCommitTrue() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(true, false, false); doTestTransactionRollbackRestoringAutoCommit(true, false, false);
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitFalse() throws Exception { void testTransactionRollbackWithAutoCommitFalse() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(false, false, false); doTestTransactionRollbackRestoringAutoCommit(false, false, false);
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitTrueAndLazyConnection() throws Exception { void testTransactionRollbackWithAutoCommitTrueAndLazyConnection() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(true, true, false); doTestTransactionRollbackRestoringAutoCommit(true, true, false);
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitFalseAndLazyConnection() throws Exception { void testTransactionRollbackWithAutoCommitFalseAndLazyConnection() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(false, true, false); doTestTransactionRollbackRestoringAutoCommit(false, true, false);
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitTrueAndLazyConnectionAndCreateStatement() throws Exception { void testTransactionRollbackWithAutoCommitTrueAndLazyConnectionAndCreateStatement() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(true, true, true); doTestTransactionRollbackRestoringAutoCommit(true, true, true);
} }
@Test @Test
public void testTransactionRollbackWithAutoCommitFalseAndLazyConnectionAndCreateStatement() throws Exception { void testTransactionRollbackWithAutoCommitFalseAndLazyConnectionAndCreateStatement() throws Exception {
doTestTransactionRollbackRestoringAutoCommit(false, true, true); doTestTransactionRollbackRestoringAutoCommit(false, true, true);
} }
@@ -268,7 +268,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionRollbackOnly() throws Exception { void testTransactionRollbackOnly() {
tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER); tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER);
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -302,12 +302,12 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithRollbackOnly() throws Exception { void testParticipatingTransactionWithRollbackOnly() throws Exception {
doTestParticipatingTransactionWithRollbackOnly(false); doTestParticipatingTransactionWithRollbackOnly(false);
} }
@Test @Test
public void testParticipatingTransactionWithRollbackOnlyAndFailEarly() throws Exception { void testParticipatingTransactionWithRollbackOnlyAndFailEarly() throws Exception {
doTestParticipatingTransactionWithRollbackOnly(true); doTestParticipatingTransactionWithRollbackOnly(true);
} }
@@ -376,7 +376,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithIncompatibleIsolationLevel() throws Exception { void testParticipatingTransactionWithIncompatibleIsolationLevel() throws Exception {
tm.setValidateExistingTransaction(true); tm.setValidateExistingTransaction(true);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -408,7 +408,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithIncompatibleReadOnly() throws Exception { void testParticipatingTransactionWithIncompatibleReadOnly() throws Exception {
willThrow(new SQLException("read-only not supported")).given(con).setReadOnly(true); willThrow(new SQLException("read-only not supported")).given(con).setReadOnly(true);
tm.setValidateExistingTransaction(true); tm.setValidateExistingTransaction(true);
@@ -442,7 +442,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithTransactionStartedFromSynch() throws Exception { void testParticipatingTransactionWithTransactionStartedFromSynch() throws Exception {
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
@@ -481,7 +481,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithDifferentConnectionObtainedFromSynch() throws Exception { void testParticipatingTransactionWithDifferentConnectionObtainedFromSynch() throws Exception {
DataSource ds2 = mock(); DataSource ds2 = mock();
final Connection con2 = mock(); final Connection con2 = mock();
given(ds2.getConnection()).willReturn(con2); given(ds2.getConnection()).willReturn(con2);
@@ -520,7 +520,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testParticipatingTransactionWithRollbackOnlyAndInnerSynch() throws Exception { void testParticipatingTransactionWithRollbackOnlyAndInnerSynch() throws Exception {
tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER); tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER);
DataSourceTransactionManager tm2 = createTransactionManager(ds); DataSourceTransactionManager tm2 = createTransactionManager(ds);
// tm has no synch enabled (used at outer level), tm2 has synch enabled (inner level) // tm has no synch enabled (used at outer level), tm2 has synch enabled (inner level)
@@ -568,7 +568,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationRequiresNewWithExistingTransaction() throws Exception { void testPropagationRequiresNewWithExistingTransaction() throws Exception {
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -605,7 +605,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource() throws Exception { void testPropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource() throws Exception {
Connection con2 = mock(); Connection con2 = mock();
final DataSource ds2 = mock(); final DataSource ds2 = mock();
given(ds2.getConnection()).willReturn(con2); given(ds2.getConnection()).willReturn(con2);
@@ -654,7 +654,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSource() throws Exception { void testPropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSource() throws Exception {
final DataSource ds2 = mock(); final DataSource ds2 = mock();
SQLException failure = new SQLException(); SQLException failure = new SQLException();
given(ds2.getConnection()).willThrow(failure); given(ds2.getConnection()).willThrow(failure);
@@ -698,7 +698,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationNotSupportedWithExistingTransaction() throws Exception { void testPropagationNotSupportedWithExistingTransaction() throws Exception {
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -739,7 +739,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationNeverWithExistingTransaction() throws Exception { void testPropagationNeverWithExistingTransaction() throws Exception {
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -769,7 +769,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationSupportsAndRequiresNew() throws Exception { void testPropagationSupportsAndRequiresNew() throws Exception {
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -805,7 +805,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testPropagationSupportsAndRequiresNewWithEarlyAccess() throws Exception { void testPropagationSupportsAndRequiresNewWithEarlyAccess() throws Exception {
final Connection con1 = mock(); final Connection con1 = mock();
final Connection con2 = mock(); final Connection con2 = mock();
given(ds.getConnection()).willReturn(con1, con2); given(ds.getConnection()).willReturn(con1, con2);
@@ -850,7 +850,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithIsolationAndReadOnly() throws Exception { void testTransactionWithIsolationAndReadOnly() throws Exception {
given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_UNCOMMITTED); given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_UNCOMMITTED);
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
@@ -871,7 +871,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithEnforceReadOnly() throws Exception { void testTransactionWithEnforceReadOnly() throws Exception {
tm.setEnforceReadOnly(true); tm.setEnforceReadOnly(true);
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
@@ -895,7 +895,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithLazyConnectionDataSourceAndStatement() throws Exception { void testTransactionWithLazyConnectionDataSourceAndStatement() throws Exception {
LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy(); LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy();
dsProxy.setTargetDataSource(ds); dsProxy.setTargetDataSource(ds);
dsProxy.setDefaultAutoCommit(true); dsProxy.setDefaultAutoCommit(true);
@@ -918,7 +918,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithLazyConnectionDataSourceNoStatement() throws Exception { void testTransactionWithLazyConnectionDataSourceNoStatement() {
LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy(); LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy();
dsProxy.setTargetDataSource(ds); dsProxy.setTargetDataSource(ds);
dsProxy.setDefaultAutoCommit(true); dsProxy.setDefaultAutoCommit(true);
@@ -931,7 +931,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithReadOnlyDataSourceAndStatement() throws Exception { void testTransactionWithReadOnlyDataSourceAndStatement() throws Exception {
LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy(); LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy();
dsProxy.setReadOnlyDataSource(ds); dsProxy.setReadOnlyDataSource(ds);
dsProxy.setDefaultAutoCommit(false); dsProxy.setDefaultAutoCommit(false);
@@ -950,7 +950,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithReadOnlyDataSourceNoStatement() throws Exception { void testTransactionWithReadOnlyDataSourceNoStatement() {
LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy(); LazyConnectionDataSourceProxy dsProxy = new LazyConnectionDataSourceProxy();
dsProxy.setReadOnlyDataSource(ds); dsProxy.setReadOnlyDataSource(ds);
dsProxy.setDefaultAutoCommit(false); dsProxy.setDefaultAutoCommit(false);
@@ -1058,7 +1058,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionAwareDataSourceProxy() throws Exception { void testTransactionAwareDataSourceProxy() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
given(con.getWarnings()).willThrow(new SQLException()); given(con.getWarnings()).willThrow(new SQLException());
@@ -1093,7 +1093,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionAwareDataSourceProxyWithLazyFalse() throws Exception { void testTransactionAwareDataSourceProxyWithLazyFalse() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
given(con.getWarnings()).willThrow(new SQLException()); given(con.getWarnings()).willThrow(new SQLException());
@@ -1129,7 +1129,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionAwareDataSourceProxyWithSuspension() throws Exception { void testTransactionAwareDataSourceProxyWithSuspension() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
@@ -1187,7 +1187,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionAwareDataSourceProxyWithSuspensionAndReobtaining() throws Exception { void testTransactionAwareDataSourceProxyWithSuspensionAndReobtaining() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
@@ -1249,7 +1249,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
* Test behavior if the first operation on a connection (getAutoCommit) throws SQLException. * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
*/ */
@Test @Test
public void testTransactionWithExceptionOnBegin() throws Exception { void testTransactionWithExceptionOnBegin() throws Exception {
willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit(); willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -1266,7 +1266,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithExceptionOnCommit() throws Exception { protected void testTransactionWithExceptionOnCommit() throws Exception {
willThrow(new SQLException("Cannot commit")).given(con).commit(); willThrow(new SQLException("Cannot commit")).given(con).commit();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -1283,7 +1283,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception { protected void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception {
willThrow(new SQLException("Cannot commit")).given(con).commit(); willThrow(new SQLException("Cannot commit")).given(con).commit();
tm.setRollbackOnCommitFailure(true); tm.setRollbackOnCommitFailure(true);
@@ -1302,7 +1302,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithExceptionOnRollback() throws Exception { protected void testTransactionWithExceptionOnRollback() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
willThrow(new SQLException("Cannot rollback")).given(con).rollback(); willThrow(new SQLException("Cannot rollback")).given(con).rollback();
@@ -1333,7 +1333,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithPropagationSupports() throws Exception { void testTransactionWithPropagationSupports() {
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -1352,7 +1352,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithPropagationNotSupported() throws Exception { void testTransactionWithPropagationNotSupported() {
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -1369,7 +1369,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithPropagationNever() throws Exception { void testTransactionWithPropagationNever() {
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -1386,12 +1386,12 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithPropagationNested() throws Exception { void testExistingTransactionWithPropagationNested() throws Exception {
doTestExistingTransactionWithPropagationNested(1); doTestExistingTransactionWithPropagationNested(1);
} }
@Test @Test
public void testExistingTransactionWithPropagationNestedTwice() throws Exception { void testExistingTransactionWithPropagationNestedTwice() throws Exception {
doTestExistingTransactionWithPropagationNested(2); doTestExistingTransactionWithPropagationNested(2);
} }
@@ -1444,7 +1444,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithPropagationNestedAndRollback() throws Exception { void testExistingTransactionWithPropagationNestedAndRollback() throws Exception {
DatabaseMetaData md = mock(); DatabaseMetaData md = mock();
Savepoint sp = mock(); Savepoint sp = mock();
@@ -1491,7 +1491,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithPropagationNestedAndRequiredRollback() throws Exception { void testExistingTransactionWithPropagationNestedAndRequiredRollback() throws Exception {
DatabaseMetaData md = mock(); DatabaseMetaData md = mock();
Savepoint sp = mock(); Savepoint sp = mock();
@@ -1551,7 +1551,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithPropagationNestedAndRequiredRollbackOnly() throws Exception { void testExistingTransactionWithPropagationNestedAndRequiredRollbackOnly() throws Exception {
DatabaseMetaData md = mock(); DatabaseMetaData md = mock();
Savepoint sp = mock(); Savepoint sp = mock();
@@ -1611,7 +1611,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithManualSavepoint() throws Exception { void testExistingTransactionWithManualSavepoint() throws Exception {
DatabaseMetaData md = mock(); DatabaseMetaData md = mock();
Savepoint sp = mock(); Savepoint sp = mock();
@@ -1644,7 +1644,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testExistingTransactionWithManualSavepointAndRollback() throws Exception { void testExistingTransactionWithManualSavepointAndRollback() throws Exception {
DatabaseMetaData md = mock(); DatabaseMetaData md = mock();
Savepoint sp = mock(); Savepoint sp = mock();
@@ -1676,7 +1676,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithPropagationNested() throws Exception { void testTransactionWithPropagationNested() throws Exception {
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();
@@ -1702,7 +1702,7 @@ public class DataSourceTransactionManagerTests<T extends DataSourceTransactionMa
} }
@Test @Test
public void testTransactionWithPropagationNestedAndRollback() throws Exception { void testTransactionWithPropagationNestedAndRollback() throws Exception {
final TransactionTemplate tt = new TransactionTemplate(tm); final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse(); assertThat(TransactionSynchronizationManager.hasResource(ds)).isFalse();

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ import static org.mockito.Mockito.verify;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class DelegatingDataSourceTests { class DelegatingDataSourceTests {
private final DataSource delegate = mock(); private final DataSource delegate = mock();
@@ -42,14 +42,14 @@ public class DelegatingDataSourceTests {
@Test @Test
public void shouldDelegateGetConnection() throws Exception { void shouldDelegateGetConnection() throws Exception {
Connection connection = mock(); Connection connection = mock();
given(delegate.getConnection()).willReturn(connection); given(delegate.getConnection()).willReturn(connection);
assertThat(dataSource.getConnection()).isEqualTo(connection); assertThat(dataSource.getConnection()).isEqualTo(connection);
} }
@Test @Test
public void shouldDelegateGetConnectionWithUsernameAndPassword() throws Exception { void shouldDelegateGetConnectionWithUsernameAndPassword() throws Exception {
Connection connection = mock(); Connection connection = mock();
String username = "username"; String username = "username";
String password = "password"; String password = "password";
@@ -58,54 +58,54 @@ public class DelegatingDataSourceTests {
} }
@Test @Test
public void shouldDelegateGetLogWriter() throws Exception { void shouldDelegateGetLogWriter() throws Exception {
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream()); PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
given(delegate.getLogWriter()).willReturn(writer); given(delegate.getLogWriter()).willReturn(writer);
assertThat(dataSource.getLogWriter()).isEqualTo(writer); assertThat(dataSource.getLogWriter()).isEqualTo(writer);
} }
@Test @Test
public void shouldDelegateSetLogWriter() throws Exception { void shouldDelegateSetLogWriter() throws Exception {
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream()); PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
dataSource.setLogWriter(writer); dataSource.setLogWriter(writer);
verify(delegate).setLogWriter(writer); verify(delegate).setLogWriter(writer);
} }
@Test @Test
public void shouldDelegateGetLoginTimeout() throws Exception { void shouldDelegateGetLoginTimeout() throws Exception {
int timeout = 123; int timeout = 123;
given(delegate.getLoginTimeout()).willReturn(timeout); given(delegate.getLoginTimeout()).willReturn(timeout);
assertThat(dataSource.getLoginTimeout()).isEqualTo(timeout); assertThat(dataSource.getLoginTimeout()).isEqualTo(timeout);
} }
@Test @Test
public void shouldDelegateSetLoginTimeoutWithSeconds() throws Exception { void shouldDelegateSetLoginTimeoutWithSeconds() throws Exception {
int timeout = 123; int timeout = 123;
dataSource.setLoginTimeout(timeout); dataSource.setLoginTimeout(timeout);
verify(delegate).setLoginTimeout(timeout); verify(delegate).setLoginTimeout(timeout);
} }
@Test @Test
public void shouldDelegateUnwrapWithoutImplementing() throws Exception { void shouldDelegateUnwrapWithoutImplementing() throws Exception {
ExampleWrapper wrapper = mock(); ExampleWrapper wrapper = mock();
given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper); given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper);
assertThat(dataSource.unwrap(ExampleWrapper.class)).isEqualTo(wrapper); assertThat(dataSource.unwrap(ExampleWrapper.class)).isEqualTo(wrapper);
} }
@Test @Test
public void shouldDelegateUnwrapImplementing() throws Exception { void shouldDelegateUnwrapImplementing() throws Exception {
dataSource = new DelegatingDataSourceWithWrapper(); dataSource = new DelegatingDataSourceWithWrapper();
assertThat(dataSource.unwrap(ExampleWrapper.class)).isSameAs(dataSource); assertThat(dataSource.unwrap(ExampleWrapper.class)).isSameAs(dataSource);
} }
@Test @Test
public void shouldDelegateIsWrapperForWithoutImplementing() throws Exception { void shouldDelegateIsWrapperForWithoutImplementing() throws Exception {
given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true); given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true);
assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue();
} }
@Test @Test
public void shouldDelegateIsWrapperForImplementing() throws Exception { void shouldDelegateIsWrapperForImplementing() throws Exception {
dataSource = new DelegatingDataSourceWithWrapper(); dataSource = new DelegatingDataSourceWithWrapper();
assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue();
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -28,13 +28,13 @@ import static org.mockito.Mockito.mock;
/** /**
* @author Rod Johnson * @author Rod Johnson
*/ */
public class DriverManagerDataSourceTests { class DriverManagerDataSourceTests {
private final Connection connection = mock(); private final Connection connection = mock();
@Test @Test
public void standardUsage() throws Exception { void standardUsage() throws Exception {
final String jdbcUrl = "url"; final String jdbcUrl = "url";
final String uname = "uname"; final String uname = "uname";
final String pwd = "pwd"; final String pwd = "pwd";
@@ -64,7 +64,7 @@ public class DriverManagerDataSourceTests {
} }
@Test @Test
public void usageWithConnectionProperties() throws Exception { void usageWithConnectionProperties() throws Exception {
final String jdbcUrl = "url"; final String jdbcUrl = "url";
final Properties connProps = new Properties(); final Properties connProps = new Properties();
@@ -97,7 +97,7 @@ public class DriverManagerDataSourceTests {
} }
@Test @Test
public void usageWithConnectionPropertiesAndUserCredentials() throws Exception { void usageWithConnectionPropertiesAndUserCredentials() throws Exception {
final String jdbcUrl = "url"; final String jdbcUrl = "url";
final String uname = "uname"; final String uname = "uname";
final String pwd = "pwd"; final String pwd = "pwd";
@@ -136,7 +136,7 @@ public class DriverManagerDataSourceTests {
} }
@Test @Test
public void invalidClassName() { void invalidClassName() {
String bogusClassName = "foobar"; String bogusClassName = "foobar";
DriverManagerDataSource ds = new DriverManagerDataSource(); DriverManagerDataSource ds = new DriverManagerDataSource();
assertThatIllegalStateException().isThrownBy( assertThatIllegalStateException().isThrownBy(

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.when;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 6.1.2 * @since 6.1.2
*/ */
public class ShardingKeyDataSourceAdapterTests { class ShardingKeyDataSourceAdapterTests {
private final Connection connection = mock(); private final Connection connection = mock();
@@ -57,11 +57,11 @@ public class ShardingKeyDataSourceAdapterTests {
private final ShardingKeyProvider shardingKeyProvider = new ShardingKeyProvider() { private final ShardingKeyProvider shardingKeyProvider = new ShardingKeyProvider() {
@Override @Override
public ShardingKey getShardingKey() throws SQLException { public ShardingKey getShardingKey() {
return shardingKey; return shardingKey;
} }
@Override @Override
public ShardingKey getSuperShardingKey() throws SQLException { public ShardingKey getSuperShardingKey() {
return superShardingKey; return superShardingKey;
} }
}; };

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,6 @@ class SingleConnectionDataSourceTests {
@Test @Test
@SuppressWarnings("resource")
void plainConnection() throws Exception { void plainConnection() throws Exception {
SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, false); SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, false);
@@ -57,7 +56,6 @@ class SingleConnectionDataSourceTests {
} }
@Test @Test
@SuppressWarnings("resource")
void withSuppressClose() throws Exception { void withSuppressClose() throws Exception {
SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, true); SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, true);
@@ -72,7 +70,6 @@ class SingleConnectionDataSourceTests {
} }
@Test @Test
@SuppressWarnings("resource")
void withRollbackBeforeClose() throws Exception { void withRollbackBeforeClose() throws Exception {
SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, true); SingleConnectionDataSource ds = new SingleConnectionDataSource(connection, true);
ds.setRollbackBeforeClose(true); ds.setRollbackBeforeClose(true);
@@ -83,7 +80,6 @@ class SingleConnectionDataSourceTests {
} }
@Test @Test
@SuppressWarnings("resource")
void withEnforcedAutoCommit() throws Exception { void withEnforcedAutoCommit() throws Exception {
SingleConnectionDataSource ds = new SingleConnectionDataSource() { SingleConnectionDataSource ds = new SingleConnectionDataSource() {
@Override @Override

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,10 +31,10 @@ import static org.mockito.Mockito.mock;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 28.05.2004 * @since 28.05.2004
*/ */
public class UserCredentialsDataSourceAdapterTests { class UserCredentialsDataSourceAdapterTests {
@Test @Test
public void testStaticCredentials() throws SQLException { void testStaticCredentials() throws SQLException {
DataSource dataSource = mock(); DataSource dataSource = mock();
Connection connection = mock(); Connection connection = mock();
given(dataSource.getConnection("user", "pw")).willReturn(connection); given(dataSource.getConnection("user", "pw")).willReturn(connection);
@@ -47,7 +47,7 @@ public class UserCredentialsDataSourceAdapterTests {
} }
@Test @Test
public void testNoCredentials() throws SQLException { void testNoCredentials() throws SQLException {
DataSource dataSource = mock(); DataSource dataSource = mock();
Connection connection = mock(); Connection connection = mock();
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
@@ -57,7 +57,7 @@ public class UserCredentialsDataSourceAdapterTests {
} }
@Test @Test
public void testThreadBoundCredentials() throws SQLException { void testThreadBoundCredentials() throws SQLException {
DataSource dataSource = mock(); DataSource dataSource = mock();
Connection connection = mock(); Connection connection = mock();
given(dataSource.getConnection("user", "pw")).willReturn(connection); given(dataSource.getConnection("user", "pw")).willReturn(connection);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,14 +34,14 @@ import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.
* @author Keith Donald * @author Keith Donald
* @author Sam Brannen * @author Sam Brannen
*/ */
public class EmbeddedDatabaseBuilderTests { class EmbeddedDatabaseBuilderTests {
private final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader( private final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(
getClass())); getClass()));
@Test @Test
public void addDefaultScripts() throws Exception { void addDefaultScripts() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()// EmbeddedDatabase db = new EmbeddedDatabaseBuilder()//
.addDefaultScripts()// .addDefaultScripts()//
@@ -51,13 +51,13 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void addScriptWithBogusFileName() { void addScriptWithBogusFileName() {
assertThatExceptionOfType(CannotReadScriptException.class).isThrownBy( assertThatExceptionOfType(CannotReadScriptException.class).isThrownBy(
new EmbeddedDatabaseBuilder().addScript("bogus.sql")::build); new EmbeddedDatabaseBuilder().addScript("bogus.sql")::build);
} }
@Test @Test
public void addScript() throws Exception { void addScript() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.addScript("db-schema.sql")// .addScript("db-schema.sql")//
@@ -68,7 +68,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void addScripts() throws Exception { void addScripts() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.addScripts("db-schema.sql", "db-test-data.sql")// .addScripts("db-schema.sql", "db-test-data.sql")//
@@ -78,7 +78,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void addScriptsWithDefaultCommentPrefix() throws Exception { void addScriptsWithDefaultCommentPrefix() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.addScripts("db-schema-comments.sql", "db-test-data.sql")// .addScripts("db-schema-comments.sql", "db-test-data.sql")//
@@ -88,7 +88,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void addScriptsWithCustomCommentPrefix() throws Exception { void addScriptsWithCustomCommentPrefix() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.addScripts("db-schema-custom-comments.sql", "db-test-data.sql")// .addScripts("db-schema-custom-comments.sql", "db-test-data.sql")//
@@ -99,7 +99,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void addScriptsWithCustomBlockComments() throws Exception { void addScriptsWithCustomBlockComments() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.addScripts("db-schema-block-comments.sql", "db-test-data.sql")// .addScripts("db-schema-block-comments.sql", "db-test-data.sql")//
@@ -111,7 +111,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void setTypeToH2() throws Exception { void setTypeToH2() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.setType(H2)// .setType(H2)//
@@ -122,7 +122,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void setTypeToDerbyAndIgnoreFailedDrops() throws Exception { void setTypeToDerbyAndIgnoreFailedDrops() {
doTwice(() -> { doTwice(() -> {
EmbeddedDatabase db = builder// EmbeddedDatabase db = builder//
.setType(DERBY)// .setType(DERBY)//
@@ -133,7 +133,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void createSameSchemaTwiceWithoutUniqueDbNames() throws Exception { void createSameSchemaTwiceWithoutUniqueDbNames() {
EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())) EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()))
.addScripts("db-schema-without-dropping.sql").build(); .addScripts("db-schema-without-dropping.sql").build();
try { try {
@@ -146,7 +146,7 @@ public class EmbeddedDatabaseBuilderTests {
} }
@Test @Test
public void createSameSchemaTwiceWithGeneratedUniqueDbNames() throws Exception { void createSameSchemaTwiceWithGeneratedUniqueDbNames() {
EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()))// EmbeddedDatabase db1 = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()))//
.addScripts("db-schema-without-dropping.sql", "db-test-data.sql")// .addScripts("db-schema-without-dropping.sql", "db-test-data.sql")//
.generateUniqueName(true)// .generateUniqueName(true)//

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Keith Donald * @author Keith Donald
*/ */
public class EmbeddedDatabaseFactoryBeanTests { class EmbeddedDatabaseFactoryBeanTests {
private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass()); private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass());
@@ -40,7 +40,7 @@ public class EmbeddedDatabaseFactoryBeanTests {
} }
@Test @Test
public void testFactoryBeanLifecycle() throws Exception { void testFactoryBeanLifecycle() {
EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean(); EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"), ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"),
resource("db-test-data.sql")); resource("db-test-data.sql"));

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Sebastien Deleuze * @author Sebastien Deleuze
*/ */
public class EmbeddedDatabaseFactoryRuntimeHintsTests { class EmbeddedDatabaseFactoryRuntimeHintsTests {
private RuntimeHints hints; private RuntimeHints hints;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,13 +27,13 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Keith Donald * @author Keith Donald
*/ */
public class EmbeddedDatabaseFactoryTests { class EmbeddedDatabaseFactoryTests {
private EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory(); private EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory();
@Test @Test
public void testGetDataSource() { void testGetDataSource() {
StubDatabasePopulator populator = new StubDatabasePopulator(); StubDatabasePopulator populator = new StubDatabasePopulator();
factory.setDatabasePopulator(populator); factory.setDatabasePopulator(populator);
EmbeddedDatabase db = factory.getDatabase(); EmbeddedDatabase db = factory.getDatabase();

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
@Test @Test
void scriptWithSingleLineCommentsAndFailedDrop() throws Exception { void scriptWithSingleLineCommentsAndFailedDrop() {
databasePopulator.addScript(resource("db-schema-failed-drop-comments.sql")); databasePopulator.addScript(resource("db-schema-failed-drop-comments.sql"));
databasePopulator.addScript(resource("db-test-data.sql")); databasePopulator.addScript(resource("db-test-data.sql"));
databasePopulator.setIgnoreFailedDrops(true); databasePopulator.setIgnoreFailedDrops(true);
@@ -55,7 +55,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithStandardEscapedLiteral() throws Exception { void scriptWithStandardEscapedLiteral() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-escaped-literal.sql")); databasePopulator.addScript(resource("db-test-data-escaped-literal.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -63,7 +63,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMySqlEscapedLiteral() throws Exception { void scriptWithMySqlEscapedLiteral() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-mysql-escaped-literal.sql")); databasePopulator.addScript(resource("db-test-data-mysql-escaped-literal.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -71,7 +71,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMultipleStatements() throws Exception { void scriptWithMultipleStatements() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-multiple.sql")); databasePopulator.addScript(resource("db-test-data-multiple.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -80,7 +80,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMultipleStatementsAndLongSeparator() throws Exception { void scriptWithMultipleStatementsAndLongSeparator() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-endings.sql")); databasePopulator.addScript(resource("db-test-data-endings.sql"));
databasePopulator.setSeparator("@@"); databasePopulator.setSeparator("@@");
@@ -90,7 +90,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMultipleStatementsAndWhitespaceSeparator() throws Exception { void scriptWithMultipleStatementsAndWhitespaceSeparator() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-whitespace.sql")); databasePopulator.addScript(resource("db-test-data-whitespace.sql"));
databasePopulator.setSeparator("/\n"); databasePopulator.setSeparator("/\n");
@@ -100,7 +100,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMultipleStatementsAndNewlineSeparator() throws Exception { void scriptWithMultipleStatementsAndNewlineSeparator() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-newline.sql")); databasePopulator.addScript(resource("db-test-data-newline.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -109,7 +109,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithMultipleStatementsAndMultipleNewlineSeparator() throws Exception { void scriptWithMultipleStatementsAndMultipleNewlineSeparator() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-multi-newline.sql")); databasePopulator.addScript(resource("db-test-data-multi-newline.sql"));
databasePopulator.setSeparator("\n\n"); databasePopulator.setSeparator("\n\n");
@@ -119,7 +119,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithEolBetweenTokens() throws Exception { void scriptWithEolBetweenTokens() {
databasePopulator.addScript(usersSchema()); databasePopulator.addScript(usersSchema());
databasePopulator.addScript(resource("users-data.sql")); databasePopulator.addScript(resource("users-data.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -127,7 +127,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithCommentsWithinStatements() throws Exception { void scriptWithCommentsWithinStatements() {
databasePopulator.addScript(usersSchema()); databasePopulator.addScript(usersSchema());
databasePopulator.addScript(resource("users-data-with-comments.sql")); databasePopulator.addScript(resource("users-data-with-comments.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);
@@ -135,7 +135,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithoutStatementSeparator() throws Exception { void scriptWithoutStatementSeparator() {
databasePopulator.setSeparator(ScriptUtils.EOF_STATEMENT_SEPARATOR); databasePopulator.setSeparator(ScriptUtils.EOF_STATEMENT_SEPARATOR);
databasePopulator.addScript(resource("drop-users-schema.sql")); databasePopulator.addScript(resource("drop-users-schema.sql"));
databasePopulator.addScript(resource("users-schema-without-separator.sql")); databasePopulator.addScript(resource("users-schema-without-separator.sql"));
@@ -146,7 +146,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void constructorWithMultipleScriptResources() throws Exception { void constructorWithMultipleScriptResources() {
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(usersSchema(), final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(usersSchema(),
resource("users-data-with-comments.sql")); resource("users-data-with-comments.sql"));
DatabasePopulatorUtils.execute(populator, db); DatabasePopulatorUtils.execute(populator, db);
@@ -154,7 +154,7 @@ abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializa
} }
@Test @Test
void scriptWithSelectStatements() throws Exception { void scriptWithSelectStatements() {
databasePopulator.addScript(defaultSchema()); databasePopulator.addScript(defaultSchema());
databasePopulator.addScript(resource("db-test-data-select.sql")); databasePopulator.addScript(resource("db-test-data-select.sql"));
DatabasePopulatorUtils.execute(databasePopulator, db); DatabasePopulatorUtils.execute(databasePopulator, db);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ class H2DatabasePopulatorTests extends AbstractDatabasePopulatorTests {
* @since 5.0 * @since 5.0
*/ */
@Test @Test
void scriptWithH2Alias() throws Exception { void scriptWithH2Alias() {
databasePopulator.addScript(usersSchema()); databasePopulator.addScript(usersSchema());
databasePopulator.addScript(resource("db-test-data-h2-alias.sql")); databasePopulator.addScript(resource("db-test-data-h2-alias.sql"));
// Set statement separator to double newline so that ";" is not // Set statement separator to double newline so that ";" is not

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ import static org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScr
* @since 4.0.3 * @since 4.0.3
* @see ScriptUtilsUnitTests * @see ScriptUtilsUnitTests
*/ */
public class ScriptUtilsIntegrationTests extends AbstractDatabaseInitializationTests { class ScriptUtilsIntegrationTests extends AbstractDatabaseInitializationTests {
@Override @Override
protected EmbeddedDatabaseType getEmbeddedDatabaseType() { protected EmbeddedDatabaseType getEmbeddedDatabaseType() {
@@ -40,12 +40,12 @@ public class ScriptUtilsIntegrationTests extends AbstractDatabaseInitializationT
} }
@BeforeEach @BeforeEach
public void setUpSchema() throws SQLException { void setUpSchema() throws SQLException {
executeSqlScript(db.getConnection(), usersSchema()); executeSqlScript(db.getConnection(), usersSchema());
} }
@Test @Test
public void executeSqlScriptContainingMultiLineComments() throws SQLException { void executeSqlScriptContainingMultiLineComments() throws SQLException {
executeSqlScript(db.getConnection(), resource("test-data-with-multi-line-comments.sql")); executeSqlScript(db.getConnection(), resource("test-data-with-multi-line-comments.sql"));
assertUsersDatabaseCreated("Hoeller", "Brannen"); assertUsersDatabaseCreated("Hoeller", "Brannen");
} }
@@ -54,7 +54,7 @@ public class ScriptUtilsIntegrationTests extends AbstractDatabaseInitializationT
* @since 4.2 * @since 4.2
*/ */
@Test @Test
public void executeSqlScriptContainingSingleQuotesNestedInsideDoubleQuotes() throws SQLException { void executeSqlScriptContainingSingleQuotesNestedInsideDoubleQuotes() throws SQLException {
executeSqlScript(db.getConnection(), resource("users-data-with-single-quotes-nested-in-double-quotes.sql")); executeSqlScript(db.getConnection(), resource("users-data-with-single-quotes-nested-in-double-quotes.sql"));
assertUsersDatabaseCreated("Hoeller", "Brannen"); assertUsersDatabaseCreated("Hoeller", "Brannen");
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -161,7 +161,7 @@ class AbstractRoutingDataSourceTests {
} }
@Test @Test
public void notInitialized() { void notInitialized() {
AbstractRoutingDataSource routingDataSource = new AbstractRoutingDataSource() { AbstractRoutingDataSource routingDataSource = new AbstractRoutingDataSource() {
@Override @Override
protected Object determineCurrentLookupKey() { protected Object determineCurrentLookupKey() {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,13 +34,13 @@ import static org.mockito.Mockito.mock;
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Chris Beams * @author Chris Beams
*/ */
public class BeanFactoryDataSourceLookupTests { class BeanFactoryDataSourceLookupTests {
private static final String DATASOURCE_BEAN_NAME = "dataSource"; private static final String DATASOURCE_BEAN_NAME = "dataSource";
@Test @Test
public void testLookupSunnyDay() { void testLookupSunnyDay() {
BeanFactory beanFactory = mock(); BeanFactory beanFactory = mock();
StubDataSource expectedDataSource = new StubDataSource(); StubDataSource expectedDataSource = new StubDataSource();
@@ -55,7 +55,7 @@ public class BeanFactoryDataSourceLookupTests {
} }
@Test @Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception { void testLookupWhereBeanFactoryYieldsNonDataSourceType() {
final BeanFactory beanFactory = mock(); final BeanFactory beanFactory = mock();
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow( given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
@@ -68,7 +68,7 @@ public class BeanFactoryDataSourceLookupTests {
} }
@Test @Test
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception { void testLookupWhereBeanFactoryHasNotBeenSupplied() {
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(); BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
assertThatIllegalStateException().isThrownBy(() -> assertThatIllegalStateException().isThrownBy(() ->
lookup.getDataSource(DATASOURCE_BEAN_NAME)); lookup.getDataSource(DATASOURCE_BEAN_NAME));

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -28,12 +28,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Rick Evans * @author Rick Evans
* @author Chris Beams * @author Chris Beams
*/ */
public class JndiDataSourceLookupTests { class JndiDataSourceLookupTests {
private static final String DATA_SOURCE_NAME = "Love is like a stove, burns you when it's hot"; private static final String DATA_SOURCE_NAME = "Love is like a stove, burns you when it's hot";
@Test @Test
public void testSunnyDay() throws Exception { void testSunnyDay() {
final DataSource expectedDataSource = new StubDataSource(); final DataSource expectedDataSource = new StubDataSource();
JndiDataSourceLookup lookup = new JndiDataSourceLookup() { JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
@Override @Override
@@ -48,7 +48,7 @@ public class JndiDataSourceLookupTests {
} }
@Test @Test
public void testNoDataSourceAtJndiLocation() throws Exception { void testNoDataSourceAtJndiLocation() {
JndiDataSourceLookup lookup = new JndiDataSourceLookup() { JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
@Override @Override
protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException { protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -30,14 +30,14 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Rick Evans * @author Rick Evans
* @author Chris Beams * @author Chris Beams
*/ */
public class MapDataSourceLookupTests { class MapDataSourceLookupTests {
private static final String DATA_SOURCE_NAME = "dataSource"; private static final String DATA_SOURCE_NAME = "dataSource";
@Test @Test
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public void getDataSourcesReturnsUnmodifiableMap() throws Exception { public void getDataSourcesReturnsUnmodifiableMap() {
MapDataSourceLookup lookup = new MapDataSourceLookup(); MapDataSourceLookup lookup = new MapDataSourceLookup();
Map dataSources = lookup.getDataSources(); Map dataSources = lookup.getDataSources();
@@ -46,7 +46,7 @@ public class MapDataSourceLookupTests {
} }
@Test @Test
public void lookupSunnyDay() throws Exception { void lookupSunnyDay() {
Map<String, DataSource> dataSources = new HashMap<>(); Map<String, DataSource> dataSources = new HashMap<>();
StubDataSource expectedDataSource = new StubDataSource(); StubDataSource expectedDataSource = new StubDataSource();
dataSources.put(DATA_SOURCE_NAME, expectedDataSource); dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
@@ -58,7 +58,7 @@ public class MapDataSourceLookupTests {
} }
@Test @Test
public void setDataSourcesIsAnIdempotentOperation() throws Exception { void setDataSourcesIsAnIdempotentOperation() {
Map<String, DataSource> dataSources = new HashMap<>(); Map<String, DataSource> dataSources = new HashMap<>();
StubDataSource expectedDataSource = new StubDataSource(); StubDataSource expectedDataSource = new StubDataSource();
dataSources.put(DATA_SOURCE_NAME, expectedDataSource); dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
@@ -71,7 +71,7 @@ public class MapDataSourceLookupTests {
} }
@Test @Test
public void addingDataSourcePermitsOverride() throws Exception { void addingDataSourcePermitsOverride() {
Map<String, DataSource> dataSources = new HashMap<>(); Map<String, DataSource> dataSources = new HashMap<>();
StubDataSource overriddenDataSource = new StubDataSource(); StubDataSource overriddenDataSource = new StubDataSource();
StubDataSource expectedDataSource = new StubDataSource(); StubDataSource expectedDataSource = new StubDataSource();
@@ -86,7 +86,7 @@ public class MapDataSourceLookupTests {
@Test @Test
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public void getDataSourceWhereSuppliedMapHasNonDataSourceTypeUnderSpecifiedKey() throws Exception { public void getDataSourceWhereSuppliedMapHasNonDataSourceTypeUnderSpecifiedKey() {
Map dataSources = new HashMap(); Map dataSources = new HashMap();
dataSources.put(DATA_SOURCE_NAME, new Object()); dataSources.put(DATA_SOURCE_NAME, new Object());
MapDataSourceLookup lookup = new MapDataSourceLookup(dataSources); MapDataSourceLookup lookup = new MapDataSourceLookup(dataSources);
@@ -96,7 +96,7 @@ public class MapDataSourceLookupTests {
} }
@Test @Test
public void getDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() throws Exception { void getDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() {
MapDataSourceLookup lookup = new MapDataSourceLookup(); MapDataSourceLookup lookup = new MapDataSourceLookup();
assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() -> assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() ->

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.jdbc.datasource.lookup; package org.springframework.jdbc.datasource.lookup;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.jdbc.datasource.AbstractDataSource; import org.springframework.jdbc.datasource.AbstractDataSource;
@@ -31,12 +30,12 @@ import org.springframework.jdbc.datasource.AbstractDataSource;
class StubDataSource extends AbstractDataSource { class StubDataSource extends AbstractDataSource {
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public Connection getConnection(String username, String password) throws SQLException { public Connection getConnection(String username, String password) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,15 +37,15 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 22.02.2005 * @since 22.02.2005
*/ */
public class BatchSqlUpdateTests { class BatchSqlUpdateTests {
@Test @Test
public void testBatchUpdateWithExplicitFlush() throws Exception { void testBatchUpdateWithExplicitFlush() throws Exception {
doTestBatchUpdate(false); doTestBatchUpdate(false);
} }
@Test @Test
public void testBatchUpdateWithFlushThroughBatchSize() throws Exception { void testBatchUpdateWithFlushThroughBatchSize() throws Exception {
doTestBatchUpdate(true); doTestBatchUpdate(true);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify;
* @author Thomas Risberg * @author Thomas Risberg
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class GenericSqlQueryTests { class GenericSqlQueryTests {
private static final String SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED = private static final String SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED =
"select id, forename from custmr where id = ? and country = ?"; "select id, forename from custmr where id = ? and country = ?";
@@ -61,7 +61,7 @@ public class GenericSqlQueryTests {
@BeforeEach @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions( new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions(
new ClassPathResource("org/springframework/jdbc/object/GenericSqlQueryTests-context.xml")); new ClassPathResource("org/springframework/jdbc/object/GenericSqlQueryTests-context.xml"));
DataSource dataSource = mock(); DataSource dataSource = mock();
@@ -71,19 +71,19 @@ public class GenericSqlQueryTests {
} }
@Test @Test
public void testCustomerQueryWithPlaceholders() throws SQLException { void testCustomerQueryWithPlaceholders() throws SQLException {
SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithPlaceholders"); SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithPlaceholders");
doTestCustomerQuery(query, false); doTestCustomerQuery(query, false);
} }
@Test @Test
public void testCustomerQueryWithNamedParameters() throws SQLException { void testCustomerQueryWithNamedParameters() throws SQLException {
SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithNamedParameters"); SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithNamedParameters");
doTestCustomerQuery(query, true); doTestCustomerQuery(query, true);
} }
@Test @Test
public void testCustomerQueryWithRowMapperInstance() throws SQLException { void testCustomerQueryWithRowMapperInstance() throws SQLException {
SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithRowMapperBean"); SqlQuery<?> query = (SqlQuery<?>) beanFactory.getBean("queryWithRowMapperBean");
doTestCustomerQuery(query, true); doTestCustomerQuery(query, true);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -38,10 +38,10 @@ import static org.mockito.Mockito.verify;
/** /**
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class GenericStoredProcedureTests { class GenericStoredProcedureTests {
@Test @Test
public void testAddInvoices() throws Exception { void testAddInvoices() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml")); new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,19 +39,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Sam Brannen * @author Sam Brannen
*/ */
public class RdbmsOperationTests { class RdbmsOperationTests {
private final TestRdbmsOperation operation = new TestRdbmsOperation(); private final TestRdbmsOperation operation = new TestRdbmsOperation();
@Test @Test
public void emptySql() { void emptySql() {
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy( assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
operation::compile); operation::compile);
} }
@Test @Test
public void setTypeAfterCompile() { void setTypeAfterCompile() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
operation.compile(); operation.compile();
@@ -60,7 +60,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void declareParameterAfterCompile() { void declareParameterAfterCompile() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
operation.compile(); operation.compile();
@@ -69,39 +69,38 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void tooFewParameters() { void tooFewParameters() {
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
operation.setTypes(new int[] { Types.INTEGER }); operation.setTypes(new int[] { Types.INTEGER });
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateParameters((Object[]) null)); operation.validateParameters(null));
} }
@Test @Test
public void tooFewMapParameters() { void tooFewMapParameters() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
operation.setTypes(new int[] { Types.INTEGER }); operation.setTypes(new int[] { Types.INTEGER });
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateNamedParameters((Map<String, String>) null)); operation.validateNamedParameters(null));
} }
@Test @Test
public void operationConfiguredViaJdbcTemplateMustGetDataSource() { void operationConfiguredViaJdbcTemplateMustGetDataSource() {
operation.setSql("foo"); operation.setSql("foo");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(operation::compile)
operation.compile())
.withMessageContaining("'dataSource'"); .withMessageContaining("'dataSource'");
} }
@Test @Test
public void tooManyParameters() { void tooManyParameters() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateParameters(new Object[] { 1, 2 })); operation.validateParameters(new Object[] { 1, 2 }));
} }
@Test @Test
public void tooManyMapParameters() { void tooManyMapParameters() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
@@ -109,7 +108,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void unspecifiedMapParameters() { void unspecifiedMapParameters() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
@@ -119,7 +118,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void compileTwice() { void compileTwice() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
operation.setTypes(null); operation.setTypes(null);
@@ -128,7 +127,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void emptyDataSource() { void emptyDataSource() {
SqlOperation operation = new SqlOperation() {}; SqlOperation operation = new SqlOperation() {};
operation.setSql("select * from mytable"); operation.setSql("select * from mytable");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy( assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
@@ -136,7 +135,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void parameterPropagation() { void parameterPropagation() {
SqlOperation operation = new SqlOperation() {}; SqlOperation operation = new SqlOperation() {};
DataSource ds = new DriverManagerDataSource(); DataSource ds = new DriverManagerDataSource();
operation.setDataSource(ds); operation.setDataSource(ds);
@@ -149,7 +148,7 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void validateInOutParameter() { void validateInOutParameter() {
operation.setDataSource(new DriverManagerDataSource()); operation.setDataSource(new DriverManagerDataSource());
operation.setSql("DUMMY_PROC"); operation.setSql("DUMMY_PROC");
operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR)); operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR));
@@ -158,13 +157,12 @@ public class RdbmsOperationTests {
} }
@Test @Test
public void parametersSetWithList() { void parametersSetWithList() {
DataSource ds = new DriverManagerDataSource(); DataSource ds = new DriverManagerDataSource();
operation.setDataSource(ds); operation.setDataSource(ds);
operation.setSql("select * from mytable where one = ? and two = ?"); operation.setSql("select * from mytable where one = ? and two = ?");
operation.setParameters(new SqlParameter[] { operation.setParameters(new SqlParameter("one", Types.NUMERIC),
new SqlParameter("one", Types.NUMERIC), new SqlParameter("two", Types.NUMERIC));
new SqlParameter("two", Types.NUMERIC)});
operation.afterPropertiesSet(); operation.afterPropertiesSet();
operation.validateParameters(new Object[] { 1, "2" }); operation.validateParameters(new Object[] { 1, "2" });
assertThat(operation.getDeclaredParameters()).hasSize(2); assertThat(operation.getDeclaredParameters()).hasSize(2);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -54,7 +53,7 @@ import static org.mockito.Mockito.verify;
* @author Thomas Risberg * @author Thomas Risberg
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class SqlQueryTests { class SqlQueryTests {
//FIXME inline? //FIXME inline?
private static final String SELECT_ID = private static final String SELECT_ID =
@@ -96,14 +95,14 @@ public class SqlQueryTests {
@BeforeEach @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
given(this.dataSource.getConnection()).willReturn(this.connection); given(this.dataSource.getConnection()).willReturn(this.connection);
given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement); given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement);
given(preparedStatement.executeQuery()).willReturn(resultSet); given(preparedStatement.executeQuery()).willReturn(resultSet);
} }
@Test @Test
public void testQueryWithoutParams() throws SQLException { void testQueryWithoutParams() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt(1)).willReturn(1); given(resultSet.getInt(1)).willReturn(1);
@@ -121,14 +120,14 @@ public class SqlQueryTests {
query.compile(); query.compile();
List<Integer> list = query.execute(); List<Integer> list = query.execute();
assertThat(list).isEqualTo(Arrays.asList(1)); assertThat(list).containsExactly(1);
verify(connection).prepareStatement(SELECT_ID); verify(connection).prepareStatement(SELECT_ID);
verify(resultSet).close(); verify(resultSet).close();
verify(preparedStatement).close(); verify(preparedStatement).close();
} }
@Test @Test
public void testQueryWithoutEnoughParams() { void testQueryWithoutEnoughParams() {
MappingSqlQuery<Integer> query = new MappingSqlQuery<>() { MappingSqlQuery<Integer> query = new MappingSqlQuery<>() {
@Override @Override
protected Integer mapRow(ResultSet rs, int rownum) throws SQLException { protected Integer mapRow(ResultSet rs, int rownum) throws SQLException {
@@ -146,7 +145,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testQueryWithMissingMapParams() { void testQueryWithMissingMapParams() {
MappingSqlQuery<Integer> query = new MappingSqlQuery<>() { MappingSqlQuery<Integer> query = new MappingSqlQuery<>() {
@Override @Override
protected Integer mapRow(ResultSet rs, int rownum) throws SQLException { protected Integer mapRow(ResultSet rs, int rownum) throws SQLException {
@@ -164,7 +163,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testStringQueryWithResults() throws Exception { void testStringQueryWithResults() throws Exception {
String[] dbResults = new String[] { "alpha", "beta", "charlie" }; String[] dbResults = new String[] { "alpha", "beta", "charlie" };
given(resultSet.next()).willReturn(true, true, true, false); given(resultSet.next()).willReturn(true, true, true, false);
given(resultSet.getString(1)).willReturn(dbResults[0], dbResults[1], dbResults[2]); given(resultSet.getString(1)).willReturn(dbResults[0], dbResults[1], dbResults[2]);
@@ -179,7 +178,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testStringQueryWithoutResults() throws SQLException { void testStringQueryWithoutResults() throws SQLException {
given(resultSet.next()).willReturn(false); given(resultSet.next()).willReturn(false);
StringQuery query = new StringQuery(dataSource, SELECT_FORENAME_EMPTY); StringQuery query = new StringQuery(dataSource, SELECT_FORENAME_EMPTY);
String[] results = query.run(); String[] results = query.run();
@@ -191,7 +190,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testFindCustomerIntInt() throws SQLException { void testFindCustomerIntInt() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -232,7 +231,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testFindCustomerString() throws SQLException { void testFindCustomerString() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -271,7 +270,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testFindCustomerMixed() throws SQLException { void testFindCustomerMixed() throws SQLException {
reset(connection); reset(connection);
PreparedStatement preparedStatement2 = mock(); PreparedStatement preparedStatement2 = mock();
ResultSet resultSet2 = mock(); ResultSet resultSet2 = mock();
@@ -300,7 +299,7 @@ public class SqlQueryTests {
} }
public Customer findCustomer(int id, String name) { public Customer findCustomer(int id, String name) {
return findObject(new Object[] { id, name }); return findObject(id, name);
} }
} }
@@ -325,7 +324,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testFindTooManyCustomers() throws SQLException { void testFindTooManyCustomers() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "rod"); given(resultSet.getString("forename")).willReturn("rod", "rod");
@@ -362,7 +361,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testListCustomersIntInt() throws SQLException { void testListCustomersIntInt() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "dave"); given(resultSet.getString("forename")).willReturn("rod", "dave");
@@ -399,7 +398,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testListCustomersString() throws SQLException { void testListCustomersString() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "dave"); given(resultSet.getString("forename")).willReturn("rod", "dave");
@@ -434,7 +433,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testFancyCustomerQuery() throws SQLException { void testFancyCustomerQuery() throws SQLException {
given(resultSet.next()).willReturn(true, false); given(resultSet.next()).willReturn(true, false);
given(resultSet.getInt("id")).willReturn(1); given(resultSet.getInt("id")).willReturn(1);
given(resultSet.getString("forename")).willReturn("rod"); given(resultSet.getString("forename")).willReturn("rod");
@@ -476,8 +475,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testUnnamedParameterDeclarationWithNamedParameterQuery() void testUnnamedParameterDeclarationWithNamedParameterQuery() {
throws SQLException {
class CustomerQuery extends MappingSqlQuery<Customer> { class CustomerQuery extends MappingSqlQuery<Customer> {
public CustomerQuery(DataSource ds) { public CustomerQuery(DataSource ds) {
@@ -509,13 +507,13 @@ public class SqlQueryTests {
} }
@Test @Test
public void testNamedParameterCustomerQueryWithUnnamedDeclarations() void testNamedParameterCustomerQueryWithUnnamedDeclarations()
throws SQLException { throws SQLException {
doTestNamedParameterCustomerQuery(false); doTestNamedParameterCustomerQuery(false);
} }
@Test @Test
public void testNamedParameterCustomerQueryWithNamedDeclarations() void testNamedParameterCustomerQueryWithNamedDeclarations()
throws SQLException { throws SQLException {
doTestNamedParameterCustomerQuery(true); doTestNamedParameterCustomerQuery(true);
} }
@@ -573,7 +571,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testNamedParameterInListQuery() throws SQLException { void testNamedParameterInListQuery() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "juergen"); given(resultSet.getString("forename")).willReturn("rod", "juergen");
@@ -626,7 +624,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testNamedParameterQueryReusingParameter() throws SQLException { void testNamedParameterQueryReusingParameter() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "juergen"); given(resultSet.getString("forename")).willReturn("rod", "juergen");
@@ -677,7 +675,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testNamedParameterUsingInvalidQuestionMarkPlaceHolders() void testNamedParameterUsingInvalidQuestionMarkPlaceHolders()
throws SQLException { throws SQLException {
given( given(
connection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID_REUSED_1, connection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID_REUSED_1,
@@ -713,7 +711,7 @@ public class SqlQueryTests {
} }
@Test @Test
public void testUpdateCustomers() throws SQLException { void testUpdateCustomers() throws SQLException {
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2); given(resultSet.getInt("id")).willReturn(1, 2);
given(connection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID, given(connection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID,

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ import static org.mockito.Mockito.verify;
* @author Thomas Risberg * @author Thomas Risberg
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class SqlUpdateTests { class SqlUpdateTests {
private static final String UPDATE = private static final String UPDATE =
"update seat_status set booking_id = null"; "update seat_status set booking_id = null";
@@ -83,19 +83,19 @@ public class SqlUpdateTests {
@BeforeEach @BeforeEach
public void setUp() throws Exception { void setUp() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
} }
@AfterEach @AfterEach
public void verifyClosed() throws Exception { void verifyClosed() throws Exception {
verify(preparedStatement).close(); verify(preparedStatement).close();
verify(connection).close(); verify(connection).close();
} }
@Test @Test
public void testUpdate() throws SQLException { void testUpdate() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
@@ -106,7 +106,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateInt() throws SQLException { void testUpdateInt() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_INT)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE_INT)).willReturn(preparedStatement);
@@ -118,7 +118,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateIntInt() throws SQLException { void testUpdateIntInt() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement);
@@ -131,12 +131,12 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testNamedParameterUpdateWithUnnamedDeclarations() throws SQLException { void testNamedParameterUpdateWithUnnamedDeclarations() throws SQLException {
doTestNamedParameterUpdate(false); doTestNamedParameterUpdate(false);
} }
@Test @Test
public void testNamedParameterUpdateWithNamedDeclarations() throws SQLException { void testNamedParameterUpdateWithNamedDeclarations() throws SQLException {
doTestNamedParameterUpdate(true); doTestNamedParameterUpdate(true);
} }
@@ -176,7 +176,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateString() throws SQLException { void testUpdateString() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_STRING)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE_STRING)).willReturn(preparedStatement);
@@ -188,7 +188,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateMixed() throws SQLException { void testUpdateMixed() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
@@ -203,7 +203,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateAndGeneratedKeys() throws SQLException { void testUpdateAndGeneratedKeys() throws SQLException {
given(resultSetMetaData.getColumnCount()).willReturn(1); given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1"); given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.getMetaData()).willReturn(resultSetMetaData);
@@ -226,7 +226,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUpdateConstructor() throws SQLException { void testUpdateConstructor() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(1); given(preparedStatement.executeUpdate()).willReturn(1);
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
ConstructorUpdater pc = new ConstructorUpdater(); ConstructorUpdater pc = new ConstructorUpdater();
@@ -241,7 +241,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testUnderMaxRows() throws SQLException { void testUnderMaxRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(3); given(preparedStatement.executeUpdate()).willReturn(3);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
@@ -252,7 +252,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testMaxRows() throws SQLException { void testMaxRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(5); given(preparedStatement.executeUpdate()).willReturn(5);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
@@ -263,7 +263,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testOverMaxRows() throws SQLException { void testOverMaxRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(8); given(preparedStatement.executeUpdate()).willReturn(8);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
@@ -274,7 +274,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testRequiredRows() throws SQLException { void testRequiredRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(3); given(preparedStatement.executeUpdate()).willReturn(3);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
@@ -285,7 +285,7 @@ public class SqlUpdateTests {
} }
@Test @Test
public void testNotRequiredRows() throws SQLException { void testNotRequiredRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(2); given(preparedStatement.executeUpdate()).willReturn(2);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement); given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
RequiredRowsUpdater pc = new RequiredRowsUpdater(); RequiredRowsUpdater pc = new RequiredRowsUpdater();

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -64,7 +64,7 @@ import static org.mockito.Mockito.verify;
* @author Trevor Cook * @author Trevor Cook
* @author Rod Johnson * @author Rod Johnson
*/ */
public class StoredProcedureTests { class StoredProcedureTests {
private Connection connection = mock(); private Connection connection = mock();
@@ -76,13 +76,13 @@ public class StoredProcedureTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
given(dataSource.getConnection()).willReturn(connection); given(dataSource.getConnection()).willReturn(connection);
given(callableStatement.getConnection()).willReturn(connection); given(callableStatement.getConnection()).willReturn(connection);
} }
@AfterEach @AfterEach
public void verifyClosed() throws Exception { void verifyClosed() throws Exception {
if (verifyClosedAfter) { if (verifyClosedAfter) {
verify(callableStatement).close(); verify(callableStatement).close();
verify(connection, atLeastOnce()).close(); verify(connection, atLeastOnce()).close();
@@ -90,7 +90,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testNoSuchStoredProcedure() throws Exception { void testNoSuchStoredProcedure() throws Exception {
SQLException sqlException = new SQLException( SQLException sqlException = new SQLException(
"Syntax error or access violation exception", "42000"); "Syntax error or access violation exception", "42000");
given(callableStatement.execute()).willThrow(sqlException); given(callableStatement.execute()).willThrow(sqlException);
@@ -102,21 +102,20 @@ public class StoredProcedureTests {
sproc::execute); sproc::execute);
} }
private void testAddInvoice(final int amount, final int custid) throws Exception { private void testAddInvoice(final int amount, final int custid) {
AddInvoice adder = new AddInvoice(dataSource); AddInvoice adder = new AddInvoice(dataSource);
int id = adder.execute(amount, custid); int id = adder.execute(amount, custid);
assertThat(id).isEqualTo(4); assertThat(id).isEqualTo(4);
} }
private void testAddInvoiceUsingObjectArray(final int amount, final int custid) private void testAddInvoiceUsingObjectArray(final int amount, final int custid) {
throws Exception {
AddInvoiceUsingObjectArray adder = new AddInvoiceUsingObjectArray(dataSource); AddInvoiceUsingObjectArray adder = new AddInvoiceUsingObjectArray(dataSource);
int id = adder.execute(amount, custid); int id = adder.execute(amount, custid);
assertThat(id).isEqualTo(5); assertThat(id).isEqualTo(5);
} }
@Test @Test
public void testAddInvoices() throws Exception { void testAddInvoices() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(3)).willReturn(4); given(callableStatement.getObject(3)).willReturn(4);
@@ -129,7 +128,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testAddInvoicesUsingObjectArray() throws Exception { void testAddInvoicesUsingObjectArray() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(3)).willReturn(5); given(callableStatement.getObject(3)).willReturn(5);
@@ -142,7 +141,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testAddInvoicesWithinTransaction() throws Exception { void testAddInvoicesWithinTransaction() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(3)).willReturn(4); given(callableStatement.getObject(3)).willReturn(4);
@@ -166,7 +165,7 @@ public class StoredProcedureTests {
* mechanism. * mechanism.
*/ */
@Test @Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator() void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
throws Exception { throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
@@ -202,7 +201,7 @@ public class StoredProcedureTests {
* Confirm our JdbcTemplate is used * Confirm our JdbcTemplate is used
*/ */
@Test @Test
public void testStoredProcedureConfiguredViaJdbcTemplate() throws Exception { void testStoredProcedureConfiguredViaJdbcTemplate() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn(4); given(callableStatement.getObject(2)).willReturn(4);
@@ -216,7 +215,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testNullArg() throws Exception { void testNullArg() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(connection.prepareCall("{call " + NullArg.SQL + "(?)}")).willReturn(callableStatement); given(connection.prepareCall("{call " + NullArg.SQL + "(?)}")).willReturn(callableStatement);
@@ -226,7 +225,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testUnnamedParameter() throws Exception { void testUnnamedParameter() {
this.verifyClosedAfter = false; this.verifyClosedAfter = false;
// Shouldn't succeed in creating stored procedure with unnamed parameter // Shouldn't succeed in creating stored procedure with unnamed parameter
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
@@ -234,14 +233,14 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testMissingParameter() throws Exception { void testMissingParameter() {
this.verifyClosedAfter = false; this.verifyClosedAfter = false;
MissingParameterStoredProcedure mp = new MissingParameterStoredProcedure(dataSource); MissingParameterStoredProcedure mp = new MissingParameterStoredProcedure(dataSource);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(mp::execute); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(mp::execute);
} }
@Test @Test
public void testStoredProcedureExceptionTranslator() throws Exception { void testStoredProcedureExceptionTranslator() throws Exception {
SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000"); SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
given(callableStatement.execute()).willThrow(sqlException); given(callableStatement.execute()).willThrow(sqlException);
given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")).willReturn(callableStatement); given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")).willReturn(callableStatement);
@@ -250,7 +249,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testStoredProcedureWithResultSet() throws Exception { void testStoredProcedureWithResultSet() throws Exception {
ResultSet resultSet = mock(); ResultSet resultSet = mock();
given(resultSet.next()).willReturn(true, true, false); given(resultSet.next()).willReturn(true, true, false);
given(callableStatement.execute()).willReturn(true); given(callableStatement.execute()).willReturn(true);
@@ -331,7 +330,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testStoredProcedureSkippingResultsProcessing() throws Exception { void testStoredProcedureSkippingResultsProcessing() throws Exception {
given(callableStatement.execute()).willReturn(true); given(callableStatement.execute()).willReturn(true);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement); given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
@@ -362,14 +361,12 @@ public class StoredProcedureTests {
assertThat(res.size()).as("incorrect number of returns").isEqualTo(1); assertThat(res.size()).as("incorrect number of returns").isEqualTo(1);
List<String> rs1 = (List<String>) res.get("rs"); List<String> rs1 = (List<String>) res.get("rs");
assertThat(rs1).hasSize(2); assertThat(rs1).containsExactly("Foo", "Bar");
assertThat(rs1).element(0).isEqualTo("Foo");
assertThat(rs1).element(1).isEqualTo("Bar");
verify(resultSet).close(); verify(resultSet).close();
} }
@Test @Test
public void testParameterMapper() throws Exception { void testParameterMapper() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn("OK"); given(callableStatement.getObject(2)).willReturn("OK");
@@ -384,7 +381,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testSqlTypeValue() throws Exception { void testSqlTypeValue() throws Exception {
int[] testVal = new int[] { 1, 2 }; int[] testVal = new int[] { 1, 2 };
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
@@ -399,7 +396,7 @@ public class StoredProcedureTests {
} }
@Test @Test
public void testNumericWithScale() throws Exception { void testNumericWithScale() throws Exception {
given(callableStatement.execute()).willReturn(false); given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(1)).willReturn(new BigDecimal("12345.6789")); given(callableStatement.getObject(1)).willReturn(new BigDecimal("12345.6789"));
@@ -603,7 +600,7 @@ public class StoredProcedureTests {
} }
@Override @Override
public Map<String, ?> createMap(Connection con) throws SQLException { public Map<String, ?> createMap(Connection con) {
Map<String, Object> inParms = new HashMap<>(); Map<String, Object> inParms = new HashMap<>();
String testValue = con.toString(); String testValue = con.toString();
inParms.put("in", testValue); inParms.put("in", testValue);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,10 +32,9 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class CustomSQLExceptionTranslatorRegistrarTests { class CustomSQLExceptionTranslatorRegistrarTests {
@Test @Test
@SuppressWarnings("resource")
public void customErrorCodeTranslation() { public void customErrorCodeTranslation() {
new ClassPathXmlApplicationContext("test-custom-translators-context.xml", new ClassPathXmlApplicationContext("test-custom-translators-context.xml",
CustomSQLExceptionTranslatorRegistrarTests.class); CustomSQLExceptionTranslatorRegistrarTests.class);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.jdbc.support; package org.springframework.jdbc.support;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
@@ -38,7 +37,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 17.12.2003 * @since 17.12.2003
*/ */
public class DefaultLobHandlerTests { class DefaultLobHandlerTests {
private ResultSet rs = mock(); private ResultSet rs = mock();
@@ -50,86 +49,86 @@ public class DefaultLobHandlerTests {
@Test @Test
public void testGetBlobAsBytes() throws SQLException { void testGetBlobAsBytes() throws SQLException {
lobHandler.getBlobAsBytes(rs, 1); lobHandler.getBlobAsBytes(rs, 1);
verify(rs).getBytes(1); verify(rs).getBytes(1);
} }
@Test @Test
public void testGetBlobAsBinaryStream() throws SQLException { void testGetBlobAsBinaryStream() throws SQLException {
lobHandler.getBlobAsBinaryStream(rs, 1); lobHandler.getBlobAsBinaryStream(rs, 1);
verify(rs).getBinaryStream(1); verify(rs).getBinaryStream(1);
} }
@Test @Test
public void testGetClobAsString() throws SQLException { void testGetClobAsString() throws SQLException {
lobHandler.getClobAsString(rs, 1); lobHandler.getClobAsString(rs, 1);
verify(rs).getString(1); verify(rs).getString(1);
} }
@Test @Test
public void testGetClobAsAsciiStream() throws SQLException { void testGetClobAsAsciiStream() throws SQLException {
lobHandler.getClobAsAsciiStream(rs, 1); lobHandler.getClobAsAsciiStream(rs, 1);
verify(rs).getAsciiStream(1); verify(rs).getAsciiStream(1);
} }
@Test @Test
public void testGetClobAsCharacterStream() throws SQLException { void testGetClobAsCharacterStream() throws SQLException {
lobHandler.getClobAsCharacterStream(rs, 1); lobHandler.getClobAsCharacterStream(rs, 1);
verify(rs).getCharacterStream(1); verify(rs).getCharacterStream(1);
} }
@Test @Test
public void testSetBlobAsBytes() throws SQLException { void testSetBlobAsBytes() throws SQLException {
byte[] content = "testContent".getBytes(); byte[] content = "testContent".getBytes();
lobCreator.setBlobAsBytes(ps, 1, content); lobCreator.setBlobAsBytes(ps, 1, content);
verify(ps).setBytes(1, content); verify(ps).setBytes(1, content);
} }
@Test @Test
public void testSetBlobAsBinaryStream() throws SQLException, IOException { void testSetBlobAsBinaryStream() throws SQLException {
InputStream bis = new ByteArrayInputStream("testContent".getBytes()); InputStream bis = new ByteArrayInputStream("testContent".getBytes());
lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11); lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11);
verify(ps).setBinaryStream(1, bis, 11); verify(ps).setBinaryStream(1, bis, 11);
} }
@Test @Test
public void testSetBlobAsBinaryStreamWithoutLength() throws SQLException, IOException { void testSetBlobAsBinaryStreamWithoutLength() throws SQLException {
InputStream bis = new ByteArrayInputStream("testContent".getBytes()); InputStream bis = new ByteArrayInputStream("testContent".getBytes());
lobCreator.setBlobAsBinaryStream(ps, 1, bis, -1); lobCreator.setBlobAsBinaryStream(ps, 1, bis, -1);
verify(ps).setBinaryStream(1, bis); verify(ps).setBinaryStream(1, bis);
} }
@Test @Test
public void testSetClobAsString() throws SQLException, IOException { void testSetClobAsString() throws SQLException {
String content = "testContent"; String content = "testContent";
lobCreator.setClobAsString(ps, 1, content); lobCreator.setClobAsString(ps, 1, content);
verify(ps).setString(1, content); verify(ps).setString(1, content);
} }
@Test @Test
public void testSetClobAsAsciiStream() throws SQLException, IOException { void testSetClobAsAsciiStream() throws SQLException {
InputStream bis = new ByteArrayInputStream("testContent".getBytes()); InputStream bis = new ByteArrayInputStream("testContent".getBytes());
lobCreator.setClobAsAsciiStream(ps, 1, bis, 11); lobCreator.setClobAsAsciiStream(ps, 1, bis, 11);
verify(ps).setAsciiStream(1, bis, 11); verify(ps).setAsciiStream(1, bis, 11);
} }
@Test @Test
public void testSetClobAsAsciiStreamWithoutLength() throws SQLException, IOException { void testSetClobAsAsciiStreamWithoutLength() throws SQLException {
InputStream bis = new ByteArrayInputStream("testContent".getBytes()); InputStream bis = new ByteArrayInputStream("testContent".getBytes());
lobCreator.setClobAsAsciiStream(ps, 1, bis, -1); lobCreator.setClobAsAsciiStream(ps, 1, bis, -1);
verify(ps).setAsciiStream(1, bis); verify(ps).setAsciiStream(1, bis);
} }
@Test @Test
public void testSetClobAsCharacterStream() throws SQLException, IOException { void testSetClobAsCharacterStream() throws SQLException {
Reader str = new StringReader("testContent"); Reader str = new StringReader("testContent");
lobCreator.setClobAsCharacterStream(ps, 1, str, 11); lobCreator.setClobAsCharacterStream(ps, 1, str, 11);
verify(ps).setCharacterStream(1, str, 11); verify(ps).setCharacterStream(1, str, 11);
} }
@Test @Test
public void testSetClobAsCharacterStreamWithoutLength() throws SQLException, IOException { void testSetClobAsCharacterStreamWithoutLength() throws SQLException {
Reader str = new StringReader("testContent"); Reader str = new StringReader("testContent");
lobCreator.setClobAsCharacterStream(ps, 1, str, -1); lobCreator.setClobAsCharacterStream(ps, 1, str, -1);
verify(ps).setCharacterStream(1, str); verify(ps).setCharacterStream(1, str);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify;
* @since 5.3 * @since 5.3
* @see org.springframework.jdbc.datasource.DataSourceTransactionManagerTests * @see org.springframework.jdbc.datasource.DataSourceTransactionManagerTests
*/ */
public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTests<JdbcTransactionManager> { class JdbcTransactionManagerTests extends DataSourceTransactionManagerTests {
@Override @Override
protected JdbcTransactionManager createTransactionManager(DataSource ds) { protected JdbcTransactionManager createTransactionManager(DataSource ds) {
@@ -53,7 +53,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
@Override @Override
@Test @Test
public void testTransactionWithExceptionOnCommit() throws Exception { protected void testTransactionWithExceptionOnCommit() throws Exception {
willThrow(new SQLException("Cannot commit")).given(con).commit(); willThrow(new SQLException("Cannot commit")).given(con).commit();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -71,7 +71,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
} }
@Test @Test
public void testTransactionWithDataAccessExceptionOnCommit() throws Exception { void testTransactionWithDataAccessExceptionOnCommit() throws Exception {
willThrow(new SQLException("Cannot commit")).given(con).commit(); willThrow(new SQLException("Cannot commit")).given(con).commit();
((JdbcTransactionManager) tm).setExceptionTranslator((task, sql, ex) -> new ConcurrencyFailureException(task)); ((JdbcTransactionManager) tm).setExceptionTranslator((task, sql, ex) -> new ConcurrencyFailureException(task));
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -90,7 +90,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
} }
@Test @Test
public void testTransactionWithDataAccessExceptionOnCommitFromLazyExceptionTranslator() throws Exception { void testTransactionWithDataAccessExceptionOnCommitFromLazyExceptionTranslator() throws Exception {
willThrow(new SQLException("Cannot commit", "40")).given(con).commit(); willThrow(new SQLException("Cannot commit", "40")).given(con).commit();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -109,7 +109,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
@Override @Override
@Test @Test
public void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception { protected void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception {
willThrow(new SQLException("Cannot commit")).given(con).commit(); willThrow(new SQLException("Cannot commit")).given(con).commit();
tm.setRollbackOnCommitFailure(true); tm.setRollbackOnCommitFailure(true);
@@ -131,7 +131,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
@Override @Override
@Test @Test
public void testTransactionWithExceptionOnRollback() throws Exception { protected void testTransactionWithExceptionOnRollback() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
willThrow(new SQLException("Cannot rollback")).given(con).rollback(); willThrow(new SQLException("Cannot rollback")).given(con).rollback();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
@@ -163,7 +163,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
} }
@Test @Test
public void testTransactionWithDataAccessExceptionOnRollback() throws Exception { void testTransactionWithDataAccessExceptionOnRollback() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
willThrow(new SQLException("Cannot rollback")).given(con).rollback(); willThrow(new SQLException("Cannot rollback")).given(con).rollback();
((JdbcTransactionManager) tm).setExceptionTranslator((task, sql, ex) -> new ConcurrencyFailureException(task)); ((JdbcTransactionManager) tm).setExceptionTranslator((task, sql, ex) -> new ConcurrencyFailureException(task));
@@ -187,7 +187,7 @@ public class JdbcTransactionManagerTests extends DataSourceTransactionManagerTes
} }
@Test @Test
public void testTransactionWithDataAccessExceptionOnRollbackFromLazyExceptionTranslator() throws Exception { void testTransactionWithDataAccessExceptionOnRollbackFromLazyExceptionTranslator() throws Exception {
given(con.getAutoCommit()).willReturn(true); given(con.getAutoCommit()).willReturn(true);
willThrow(new SQLException("Cannot rollback", "40")).given(con).rollback(); willThrow(new SQLException("Cannot rollback", "40")).given(con).rollback();
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Ben Blinebury * @author Ben Blinebury
*/ */
public class JdbcUtilsTests { class JdbcUtilsTests {
@Test @Test
public void commonDatabaseName() { void commonDatabaseName() {
assertThat(JdbcUtils.commonDatabaseName("Oracle")).isEqualTo("Oracle"); assertThat(JdbcUtils.commonDatabaseName("Oracle")).isEqualTo("Oracle");
assertThat(JdbcUtils.commonDatabaseName("DB2-for-Spring")).isEqualTo("DB2"); assertThat(JdbcUtils.commonDatabaseName("DB2-for-Spring")).isEqualTo("DB2");
assertThat(JdbcUtils.commonDatabaseName("Sybase SQL Server")).isEqualTo("Sybase"); assertThat(JdbcUtils.commonDatabaseName("Sybase SQL Server")).isEqualTo("Sybase");
@@ -42,7 +42,7 @@ public class JdbcUtilsTests {
} }
@Test @Test
public void resolveTypeName() { void resolveTypeName() {
assertThat(JdbcUtils.resolveTypeName(Types.VARCHAR)).isEqualTo("VARCHAR"); assertThat(JdbcUtils.resolveTypeName(Types.VARCHAR)).isEqualTo("VARCHAR");
assertThat(JdbcUtils.resolveTypeName(Types.NUMERIC)).isEqualTo("NUMERIC"); assertThat(JdbcUtils.resolveTypeName(Types.NUMERIC)).isEqualTo("NUMERIC");
assertThat(JdbcUtils.resolveTypeName(Types.INTEGER)).isEqualTo("INTEGER"); assertThat(JdbcUtils.resolveTypeName(Types.INTEGER)).isEqualTo("INTEGER");
@@ -50,7 +50,7 @@ public class JdbcUtilsTests {
} }
@Test @Test
public void convertUnderscoreNameToPropertyName() { void convertUnderscoreNameToPropertyName() {
assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")).isEqualTo("myName"); assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")).isEqualTo("myName");
assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")).isEqualTo("yourName"); assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")).isEqualTo("yourName");
assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("a_name")).isEqualTo("AName"); assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("a_name")).isEqualTo("AName");

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -53,7 +53,7 @@ class KeyHolderTests {
kh.getKeyList().add(singletonMap("key", "ABC")); kh.getKeyList().add(singletonMap("key", "ABC"));
assertThatExceptionOfType(DataRetrievalFailureException.class) assertThatExceptionOfType(DataRetrievalFailureException.class)
.isThrownBy(() -> kh.getKey()) .isThrownBy(kh::getKey)
.withMessage("The generated key type is not supported. Unable to cast [java.lang.String] to [java.lang.Number]."); .withMessage("The generated key type is not supported. Unable to cast [java.lang.String] to [java.lang.Number].");
} }
@@ -62,7 +62,7 @@ class KeyHolderTests {
kh.getKeyList().add(emptyMap()); kh.getKeyList().add(emptyMap());
assertThatExceptionOfType(DataRetrievalFailureException.class) assertThatExceptionOfType(DataRetrievalFailureException.class)
.isThrownBy(() -> kh.getKey()) .isThrownBy(kh::getKey)
.withMessageStartingWith("Unable to retrieve the generated key."); .withMessageStartingWith("Unable to retrieve the generated key.");
} }
@@ -72,7 +72,7 @@ class KeyHolderTests {
assertThat(kh.getKeys()).as("two keys should be in the map").hasSize(2); assertThat(kh.getKeys()).as("two keys should be in the map").hasSize(2);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> kh.getKey()) .isThrownBy(kh::getKey)
.withMessageStartingWith("The getKey method should only be used when a single key is returned."); .withMessageStartingWith("The getKey method should only be used when a single key is returned.");
} }
@@ -103,13 +103,12 @@ class KeyHolderTests {
@Test @Test
void getKeysWithMultipleKeyRows() { void getKeysWithMultipleKeyRows() {
@SuppressWarnings("serial")
Map<String, Object> m = Map.of("key", 1, "seq", 2); Map<String, Object> m = Map.of("key", 1, "seq", 2);
kh.getKeyList().addAll(asList(m, m)); kh.getKeyList().addAll(asList(m, m));
assertThat(kh.getKeyList()).as("two rows should be in the list").hasSize(2); assertThat(kh.getKeyList()).as("two rows should be in the list").hasSize(2);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> kh.getKeys()) .isThrownBy(kh::getKeys)
.withMessageStartingWith("The getKeys method should only be used when keys for a single row are returned."); .withMessageStartingWith("The getKeys method should only be used when keys for a single row are returned.");
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Thomas Risberg * @author Thomas Risberg
* @author Sam Brannen * @author Sam Brannen
*/ */
public class SQLExceptionCustomTranslatorTests { class SQLExceptionCustomTranslatorTests {
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes(); private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
@@ -47,7 +47,7 @@ public class SQLExceptionCustomTranslatorTests {
@Test @Test
public void badSqlGrammarException() { void badSqlGrammarException() {
SQLException badSqlGrammarExceptionEx = new SQLDataException("", "", 1); SQLException badSqlGrammarExceptionEx = new SQLDataException("", "", 1);
DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx); DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx);
assertThat(dae.getCause()).isEqualTo(badSqlGrammarExceptionEx); assertThat(dae.getCause()).isEqualTo(badSqlGrammarExceptionEx);
@@ -55,7 +55,7 @@ public class SQLExceptionCustomTranslatorTests {
} }
@Test @Test
public void dataAccessResourceException() { void dataAccessResourceException() {
SQLException dataAccessResourceEx = new SQLDataException("", "", 2); SQLException dataAccessResourceEx = new SQLDataException("", "", 2);
DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx); DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx);
assertThat(dae.getCause()).isEqualTo(dataAccessResourceEx); assertThat(dae.getCause()).isEqualTo(dataAccessResourceEx);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Thomas Risberg * @author Thomas Risberg
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class SQLExceptionSubclassTranslatorTests { class SQLExceptionSubclassTranslatorTests {
@Test @Test
public void exceptionClassTranslation() { void exceptionClassTranslation() {
doTest(new SQLDataException("", "", 0), DataIntegrityViolationException.class); doTest(new SQLDataException("", "", 0), DataIntegrityViolationException.class);
doTest(new SQLFeatureNotSupportedException("", "", 0), InvalidDataAccessApiUsageException.class); doTest(new SQLFeatureNotSupportedException("", "", 0), InvalidDataAccessApiUsageException.class);
doTest(new SQLIntegrityConstraintViolationException("", "", 0), DataIntegrityViolationException.class); doTest(new SQLIntegrityConstraintViolationException("", "", 0), DataIntegrityViolationException.class);
@@ -72,7 +72,7 @@ public class SQLExceptionSubclassTranslatorTests {
} }
@Test @Test
public void fallbackStateTranslation() { void fallbackStateTranslation() {
// Test fallback. We assume that no database will ever return this error code, // Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator // but 07xxx will be bad grammar picked up by the fallback SQLState translator
doTest(new SQLException("", "07xxx", 666666666), BadSqlGrammarException.class); doTest(new SQLException("", "07xxx", 666666666), BadSqlGrammarException.class);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2022 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -69,7 +69,7 @@ class H2SequenceMaxValueIncrementerTests {
@ParameterizedTest @ParameterizedTest
@EnumSource(ModeEnum.class) @EnumSource(ModeEnum.class)
void incrementsSequenceWithExplicitH2CompatibilityMode(ModeEnum mode) { void incrementsSequenceWithExplicitH2CompatibilityMode(ModeEnum mode) {
String connectionUrl = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;MODE=%s", UUID.randomUUID().toString(), mode); String connectionUrl = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;MODE=%s", UUID.randomUUID(), mode);
DataSource dataSource = new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", ""); DataSource dataSource = new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", "");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("CREATE SEQUENCE SEQ"); jdbcTemplate.execute("CREATE SEQUENCE SEQ");

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2023 the original author or authors. * Copyright 2002-2024 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock;
/** /**
* @author Thomas Risberg * @author Thomas Risberg
*/ */
public class ResultSetWrappingRowSetTests { class ResultSetWrappingRowSetTests {
private ResultSet resultSet = mock(); private ResultSet resultSet = mock();
@@ -45,154 +45,154 @@ public class ResultSetWrappingRowSetTests {
@Test @Test
public void testGetBigDecimalInt() throws Exception { void testGetBigDecimalInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", int.class); Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", int.class);
doTest(rset, rowset, 1, BigDecimal.ONE); doTest(rset, rowset, 1, BigDecimal.ONE);
} }
@Test @Test
public void testGetBigDecimalString() throws Exception { void testGetBigDecimalString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", int.class); Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", String.class);
doTest(rset, rowset, "test", BigDecimal.ONE); doTest(rset, rowset, "test", BigDecimal.ONE);
} }
@Test @Test
public void testGetStringInt() throws Exception { void testGetStringInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", int.class); Method rset = ResultSet.class.getDeclaredMethod("getString", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", int.class);
doTest(rset, rowset, 1, "test"); doTest(rset, rowset, 1, "test");
} }
@Test @Test
public void testGetStringString() throws Exception { void testGetStringString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getString", int.class); Method rset = ResultSet.class.getDeclaredMethod("getString", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", String.class);
doTest(rset, rowset, "test", "test"); doTest(rset, rowset, "test", "test");
} }
@Test @Test
public void testGetTimestampInt() throws Exception { void testGetTimestampInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", int.class); Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", int.class);
doTest(rset, rowset, 1, new Timestamp(1234L)); doTest(rset, rowset, 1, new Timestamp(1234L));
} }
@Test @Test
public void testGetTimestampString() throws Exception { void testGetTimestampString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", int.class); Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", String.class);
doTest(rset, rowset, "test", new Timestamp(1234L)); doTest(rset, rowset, "test", new Timestamp(1234L));
} }
@Test @Test
public void testGetDateInt() throws Exception { void testGetDateInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", int.class); Method rset = ResultSet.class.getDeclaredMethod("getDate", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", int.class);
doTest(rset, rowset, 1, new Date(1234L)); doTest(rset, rowset, 1, new Date(1234L));
} }
@Test @Test
public void testGetDateString() throws Exception { void testGetDateString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDate", int.class); Method rset = ResultSet.class.getDeclaredMethod("getDate", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", String.class);
doTest(rset, rowset, "test", new Date(1234L)); doTest(rset, rowset, "test", new Date(1234L));
} }
@Test @Test
public void testGetTimeInt() throws Exception { void testGetTimeInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", int.class); Method rset = ResultSet.class.getDeclaredMethod("getTime", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", int.class);
doTest(rset, rowset, 1, new Time(1234L)); doTest(rset, rowset, 1, new Time(1234L));
} }
@Test @Test
public void testGetTimeString() throws Exception { void testGetTimeString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getTime", int.class); Method rset = ResultSet.class.getDeclaredMethod("getTime", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", String.class);
doTest(rset, rowset, "test", new Time(1234L)); doTest(rset, rowset, "test", new Time(1234L));
} }
@Test @Test
public void testGetObjectInt() throws Exception { void testGetObjectInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", int.class); Method rset = ResultSet.class.getDeclaredMethod("getObject", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", int.class);
doTest(rset, rowset, 1, new Object()); doTest(rset, rowset, 1, new Object());
} }
@Test @Test
public void testGetObjectString() throws Exception { void testGetObjectString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getObject", int.class); Method rset = ResultSet.class.getDeclaredMethod("getObject", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", String.class);
doTest(rset, rowset, "test", new Object()); doTest(rset, rowset, "test", new Object());
} }
@Test @Test
public void testGetIntInt() throws Exception { void testGetIntInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", int.class); Method rset = ResultSet.class.getDeclaredMethod("getInt", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", int.class);
doTest(rset, rowset, 1, 1); doTest(rset, rowset, 1, 1);
} }
@Test @Test
public void testGetIntString() throws Exception { void testGetIntString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getInt", int.class); Method rset = ResultSet.class.getDeclaredMethod("getInt", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", String.class);
doTest(rset, rowset, "test", 1); doTest(rset, rowset, "test", 1);
} }
@Test @Test
public void testGetFloatInt() throws Exception { void testGetFloatInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", int.class); Method rset = ResultSet.class.getDeclaredMethod("getFloat", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", int.class);
doTest(rset, rowset, 1, 1.0f); doTest(rset, rowset, 1, 1.0f);
} }
@Test @Test
public void testGetFloatString() throws Exception { void testGetFloatString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getFloat", int.class); Method rset = ResultSet.class.getDeclaredMethod("getFloat", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", String.class);
doTest(rset, rowset, "test", 1.0f); doTest(rset, rowset, "test", 1.0f);
} }
@Test @Test
public void testGetDoubleInt() throws Exception { void testGetDoubleInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", int.class); Method rset = ResultSet.class.getDeclaredMethod("getDouble", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", int.class);
doTest(rset, rowset, 1, 1.0d); doTest(rset, rowset, 1, 1.0d);
} }
@Test @Test
public void testGetDoubleString() throws Exception { void testGetDoubleString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getDouble", int.class); Method rset = ResultSet.class.getDeclaredMethod("getDouble", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", String.class);
doTest(rset, rowset, "test", 1.0d); doTest(rset, rowset, "test", 1.0d);
} }
@Test @Test
public void testGetLongInt() throws Exception { void testGetLongInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", int.class); Method rset = ResultSet.class.getDeclaredMethod("getLong", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", int.class);
doTest(rset, rowset, 1, 1L); doTest(rset, rowset, 1, 1L);
} }
@Test @Test
public void testGetLongString() throws Exception { void testGetLongString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getLong", int.class); Method rset = ResultSet.class.getDeclaredMethod("getLong", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", String.class);
doTest(rset, rowset, "test", 1L); doTest(rset, rowset, "test", 1L);
} }
@Test @Test
public void testGetBooleanInt() throws Exception { void testGetBooleanInt() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", int.class); Method rset = ResultSet.class.getDeclaredMethod("getBoolean", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", int.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", int.class);
doTest(rset, rowset, 1, true); doTest(rset, rowset, 1, true);
} }
@Test @Test
public void testGetBooleanString() throws Exception { void testGetBooleanString() throws Exception {
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", int.class); Method rset = ResultSet.class.getDeclaredMethod("getBoolean", int.class);
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", String.class); Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", String.class);
doTest(rset, rowset, "test", true); doTest(rset, rowset, "test", true);