Migrate away from ExpectedException (#22922)

* Add limited checkstyles to test code

Add a limited set of checkstyle rules to the test codebase to improve
code consistency.

* Fix checksyle violations in test code

* Organize imports to fix checkstyle for test code

* Migrate to assertThatExceptionOfType

Migrate aware from ExpectedException rules to AssertJ exception
assertions. Also include a checkstyle rules to ensure that the
the ExpectedException is not accidentally used in the future.

See gh-22894
This commit is contained in:
Phil Webb
2019-05-08 07:25:52 -07:00
committed by Sam Brannen
parent 7e6e3d7027
commit d7320de871
671 changed files with 3861 additions and 4601 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,12 +17,9 @@
package org.springframework.jdbc.config;
import java.util.function.Predicate;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
@@ -39,6 +36,7 @@ import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
@@ -53,9 +51,6 @@ import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFacto
*/
public class JdbcNamespaceIntegrationTests {
@Rule
public ExpectedException expected = ExpectedException.none();
@Test
public void createEmbeddedDatabase() throws Exception {
@@ -78,25 +73,24 @@ public class JdbcNamespaceIntegrationTests {
@Test
public void createWithAnonymousDataSourceAndDefaultDatabaseName() throws Exception {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-default-and-anonymous-datasource.xml",
(url) -> url.endsWith(DEFAULT_DATABASE_NAME));
url -> url.endsWith(DEFAULT_DATABASE_NAME));
}
@Test
public void createWithImplicitDatabaseName() throws Exception {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-implicit.xml", (url) -> url.endsWith("dataSource"));
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-implicit.xml", url -> url.endsWith("dataSource"));
}
@Test
public void createWithExplicitDatabaseName() throws Exception {
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-explicit.xml", (url) -> url.endsWith("customDbName"));
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-explicit.xml", url -> url.endsWith("customDbName"));
}
@Test
public void createWithGeneratedDatabaseName() throws Exception {
Predicate<String> urlPredicate = (url) -> url.startsWith("jdbc:hsqldb:mem:");
urlPredicate.and((url) -> !url.endsWith("dataSource"));
urlPredicate.and((url) -> !url.endsWith("shouldBeOverriddenByGeneratedName"));
Predicate<String> urlPredicate = url -> url.startsWith("jdbc:hsqldb:mem:");
urlPredicate.and(url -> !url.endsWith("dataSource"));
urlPredicate.and(url -> !url.endsWith("shouldBeOverriddenByGeneratedName"));
assertCorrectSetupForSingleDataSource("jdbc-config-db-name-generated.xml", urlPredicate);
}
@@ -118,8 +112,9 @@ public class JdbcNamespaceIntegrationTests {
JdbcTemplate template = new JdbcTemplate(dataSource);
assertNumRowsInTestTable(template, 1);
context.getBean(DataSourceInitializer.class).destroy();
expected.expect(BadSqlGrammarException.class); // Table has been dropped
assertNumRowsInTestTable(template, 1);
// Table has been dropped
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
assertNumRowsInTestTable(template, 1));
}
finally {
context.close();
@@ -134,8 +129,9 @@ public class JdbcNamespaceIntegrationTests {
JdbcTemplate template = new JdbcTemplate(dataSource);
assertNumRowsInTestTable(template, 1);
context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
expected.expect(BadSqlGrammarException.class); // Table has been dropped
assertNumRowsInTestTable(template, 1);
// Table has been dropped
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
assertNumRowsInTestTable(template, 1));
}
finally {
context.close();
@@ -150,8 +146,9 @@ public class JdbcNamespaceIntegrationTests {
JdbcTemplate template = new JdbcTemplate(dataSource);
assertNumRowsInTestTable(template, 1);
context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
expected.expect(BadSqlGrammarException.class); // Table has been dropped
assertNumRowsInTestTable(template, 1);
// Table has been dropped
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
assertNumRowsInTestTable(template, 1));
}
finally {
context.close();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,7 @@ import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,9 +18,7 @@ package org.springframework.jdbc.core;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -30,6 +28,7 @@ import org.springframework.jdbc.core.test.ExtendedPerson;
import org.springframework.jdbc.core.test.Person;
import org.springframework.jdbc.core.test.SpacePerson;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
/**
@@ -38,16 +37,13 @@ import static org.junit.Assert.*;
*/
public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testOverridingDifferentClassDefinedForMapping() {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
thrown.expect(InvalidDataAccessApiUsageException.class);
mapper.setMappedClass(Long.class);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
mapper.setMappedClass(Long.class));
}
@Test
@@ -104,19 +100,17 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
@Test
public void testMappingWithUnpopulatedFieldsNotAccepted() throws Exception {
Mock mock = new Mock();
thrown.expect(InvalidDataAccessApiUsageException.class);
mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<>(ExtendedPerson.class, true));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
mock.getJdbcTemplate().query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<>(ExtendedPerson.class, true)));
}
@Test
public void testMappingNullValue() throws Exception {
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<>(Person.class);
Mock mock = new Mock(MockType.TWO);
thrown.expect(TypeMismatchException.class);
mock.getJdbcTemplate().query(
"select name, null as age, birth_date, balance from people", mapper);
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
mock.getJdbcTemplate().query("select name, null as age, birth_date, balance from people", mapper));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,13 +29,13 @@ import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**
@@ -46,9 +46,6 @@ import static org.mockito.BDDMockito.*;
*/
public class JdbcTemplateQueryTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private Connection connection;
private DataSource dataSource;
@@ -147,14 +144,10 @@ public class JdbcTemplateQueryTests {
String sql = "select pass from t_account where first_name='Alef'";
given(this.resultSet.next()).willReturn(true, true, false);
given(this.resultSet.getString(1)).willReturn("pass");
this.thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
this.template.queryForObject(sql, String.class);
}
finally {
verify(this.resultSet).close();
verify(this.statement).close();
}
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
this.template.queryForObject(sql, String.class));
verify(this.resultSet).close();
verify(this.statement).close();
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,9 +36,7 @@ import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -54,11 +52,12 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.tests.Matchers.*;
/**
* Mock object based tests for JdbcTemplate.
@@ -84,9 +83,6 @@ public class JdbcTemplateTests {
private CallableStatement callableStatement;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() throws Exception {
@@ -140,16 +136,12 @@ public class JdbcTemplateTests {
given(this.preparedStatement.executeUpdate()).willThrow(sqlException);
Dispatcher d = new Dispatcher(idParam, sql);
this.thrown.expect(UncategorizedSQLException.class);
this.thrown.expect(exceptionCause(equalTo(sqlException)));
try {
this.template.update(d);
}
finally {
verify(this.preparedStatement).setInt(1, idParam);
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
assertThatExceptionOfType(UncategorizedSQLException.class).isThrownBy(() ->
this.template.update(d))
.withCause(sqlException);
verify(this.preparedStatement).setInt(1, idParam);
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
@Test
@@ -171,9 +163,8 @@ public class JdbcTemplateTests {
@Test
public void testStringsWithPreparedStatementSetter() throws Exception {
final Integer argument = 99;
doTestStrings(null, null, null, argument, (template, sql, rch) -> template.query(sql, ps -> {
ps.setObject(1, argument);
}, rch));
doTestStrings(null, null, null, argument, (template, sql, rch) ->
template.query(sql, ps -> ps.setObject(1, argument), rch));
}
@Test
@@ -326,11 +317,12 @@ public class JdbcTemplateTests {
given(this.resultSet.next()).willReturn(true);
given(this.connection.createStatement()).willReturn(this.preparedStatement);
this.thrown.expect(sameInstance(runtimeException));
try {
this.template.query(sql, (RowCallbackHandler) rs -> {
throw runtimeException;
});
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
this.template.query(sql, (RowCallbackHandler) rs -> {
throw runtimeException;
}))
.withMessage(runtimeException.getMessage());
}
finally {
verify(this.resultSet).close();
@@ -382,14 +374,11 @@ public class JdbcTemplateTests {
given(this.statement.executeUpdate(sql)).willThrow(sqlException);
given(this.connection.createStatement()).willReturn(this.statement);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
this.template.update(sql);
}
finally {
verify(this.statement).close();
verify(this.connection, atLeastOnce()).close();
}
assertThatExceptionOfType(DataAccessException.class).isThrownBy(() ->
this.template.update(sql))
.withCause(sqlException);
verify(this.statement).close();
verify(this.connection, atLeastOnce()).close();
}
@Test
@@ -478,15 +467,11 @@ public class JdbcTemplateTests {
given(this.connection.createStatement()).willReturn(this.statement);
JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
this.thrown.expect(InvalidDataAccessApiUsageException.class);
try {
template.batchUpdate(sql);
}
finally {
verify(this.statement, never()).addBatch(anyString());
verify(this.statement).close();
verify(this.connection, atLeastOnce()).close();
}
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
template.batchUpdate(sql));
verify(this.statement, never()).addBatch(anyString());
verify(this.statement).close();
verify(this.connection, atLeastOnce()).close();
}
@Test
@@ -689,10 +674,10 @@ public class JdbcTemplateTests {
}
};
this.thrown.expect(DataAccessException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
this.template.batchUpdate(sql, setter);
assertThatExceptionOfType(DataAccessException.class).isThrownBy(() ->
this.template.batchUpdate(sql, setter))
.withCause(sqlException);
}
finally {
verify(this.preparedStatement, times(2)).addBatch();
@@ -795,9 +780,9 @@ public class JdbcTemplateTests {
JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
RowCountCallbackHandler rcch = new RowCountCallbackHandler();
this.thrown.expect(CannotGetJdbcConnectionException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
.withCause(sqlException);
}
@Test
@@ -810,9 +795,9 @@ public class JdbcTemplateTests {
this.template.afterPropertiesSet();
RowCountCallbackHandler rcch = new RowCountCallbackHandler();
this.thrown.expect(CannotGetJdbcConnectionException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
.withCause(sqlException);
}
@Test
@@ -851,9 +836,9 @@ public class JdbcTemplateTests {
this.template.afterPropertiesSet();
}
RowCountCallbackHandler rcch = new RowCountCallbackHandler();
this.thrown.expect(CannotGetJdbcConnectionException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
.withCause(sqlException);
}
@Test
@@ -880,16 +865,12 @@ public class JdbcTemplateTests {
given(this.preparedStatement.executeUpdate()).willThrow(sqlException);
PreparedStatementSetter pss = ps -> ps.setString(1, name);
this.thrown.expect(DataAccessException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
new JdbcTemplate(this.dataSource).update(sql, pss);
}
finally {
verify(this.preparedStatement).setString(1, name);
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
assertThatExceptionOfType(DataAccessException.class).isThrownBy(() ->
new JdbcTemplate(this.dataSource).update(sql, pss))
.withCause(sqlException);
verify(this.preparedStatement).setString(1, name);
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
@Test
@@ -920,18 +901,14 @@ public class JdbcTemplateTests {
JdbcTemplate t = new JdbcTemplate(this.dataSource);
t.setIgnoreWarnings(false);
this.thrown.expect(SQLWarningException.class);
this.thrown.expect(exceptionCause(sameInstance(warnings)));
try {
t.query(sql, rs -> {
rs.getByte(1);
});
}
finally {
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
ResultSetExtractor<Byte> extractor = rs -> rs.getByte(1);
assertThatExceptionOfType(SQLWarningException.class).isThrownBy(() ->
t.query(sql, extractor))
.withCause(warnings);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
@Test
@@ -946,9 +923,8 @@ public class JdbcTemplateTests {
// Too long: truncation
this.template.setIgnoreWarnings(true);
this.template.query(sql, rs -> {
rs.getByte(1);
});
RowCallbackHandler rch = rs -> rs.getByte(1);
this.template.query(sql, rch);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
@@ -964,19 +940,14 @@ public class JdbcTemplateTests {
mockDatabaseMetaData(false);
given(this.connection.createStatement()).willReturn(this.preparedStatement);
this.thrown.expect(BadSqlGrammarException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
this.template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
});
fail("Should have thrown BadSqlGrammarException");
}
finally {
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
this.template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
}))
.withCause(sqlException);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection, atLeastOnce()).close();
}
@Test
@@ -992,18 +963,14 @@ public class JdbcTemplateTests {
template.setDatabaseProductName("MySQL");
template.afterPropertiesSet();
this.thrown.expect(BadSqlGrammarException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
});
}
finally {
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
}))
.withCause(sqlException);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
/**
@@ -1026,18 +993,14 @@ public class JdbcTemplateTests {
template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
template.afterPropertiesSet();
this.thrown.expect(BadSqlGrammarException.class);
this.thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
});
}
finally {
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
template.query(sql, (RowCallbackHandler) rs -> {
throw sqlException;
}))
.withCause(sqlException);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}
@Test
@@ -1047,25 +1010,14 @@ public class JdbcTemplateTests {
given(this.preparedStatement.executeQuery()).willReturn(resultSet2);
given(this.connection.createStatement()).willReturn(this.statement);
try {
this.template.query("my query", (ResultSetExtractor<Object>) rs -> {
throw new InvalidDataAccessApiUsageException("");
});
fail("Should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
// ok
}
try {
this.template.query(con -> con.prepareStatement("my query"), (ResultSetExtractor<Object>) rs2 -> {
throw new InvalidDataAccessApiUsageException("");
});
fail("Should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
// ok
}
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
this.template.query("my query", (ResultSetExtractor<Object>) rs -> {
throw new InvalidDataAccessApiUsageException("");
}));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
this.template.query(con -> con.prepareStatement("my query"), (ResultSetExtractor<Object>) rs2 -> {
throw new InvalidDataAccessApiUsageException("");
}));
verify(this.resultSet).close();
verify(resultSet2).close();
@@ -1083,15 +1035,11 @@ public class JdbcTemplateTests {
throw new InvalidDataAccessApiUsageException("");
});
this.thrown.expect(InvalidDataAccessApiUsageException.class);
try {
this.template.call(conn -> conn.prepareCall("my query"), Collections.singletonList(param));
}
finally {
verify(this.resultSet).close();
verify(this.callableStatement).close();
verify(this.connection).close();
}
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
this.template.call(conn -> conn.prepareCall("my query"), Collections.singletonList(param)));
verify(this.resultSet).close();
verify(this.callableStatement).close();
verify(this.connection).close();
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,6 +33,7 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,9 +32,7 @@ import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.InOrder;
import org.springframework.jdbc.Customer;
@@ -43,7 +41,9 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.SqlParameterValue;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**
@@ -75,9 +75,6 @@ public class NamedParameterJdbcTemplateTests {
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
@Rule
public ExpectedException thrown = ExpectedException.none();
private Connection connection;
private DataSource dataSource;
@@ -112,14 +109,14 @@ public class NamedParameterJdbcTemplateTests {
@Test
public void testNullDataSourceProvidedToCtor() {
thrown.expect(IllegalArgumentException.class);
new NamedParameterJdbcTemplate((DataSource) null);
assertThatIllegalArgumentException().isThrownBy(() ->
new NamedParameterJdbcTemplate((DataSource) null));
}
@Test
public void testNullJdbcTemplateProvidedToCtor() {
thrown.expect(IllegalArgumentException.class);
new NamedParameterJdbcTemplate((JdbcOperations) null);
assertThatIllegalArgumentException().isThrownBy(() ->
new NamedParameterJdbcTemplate((JdbcOperations) null));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,6 +37,7 @@ import org.junit.Test;
import org.springframework.jdbc.core.RowMapper;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,9 +26,7 @@ import javax.sql.DataSource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.BadSqlGrammarException;
@@ -36,10 +34,9 @@ import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import static org.hamcrest.Matchers.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.tests.Matchers.*;
/**
* Tests for {@link SimpleJdbcCall}.
@@ -57,9 +54,6 @@ public class SimpleJdbcCallTests {
private CallableStatement callableStatement;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() throws Exception {
@@ -83,10 +77,10 @@ public class SimpleJdbcCallTests {
given(callableStatement.execute()).willThrow(sqlException);
given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
thrown.expect(BadSqlGrammarException.class);
thrown.expect(exceptionCause(sameInstance(sqlException)));
try {
sproc.execute();
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() ->
sproc.execute())
.withCause(sqlException);
}
finally {
verify(callableStatement).close();
@@ -99,8 +93,8 @@ public class SimpleJdbcCallTests {
final String MY_PROC = "my_proc";
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC);
// Shouldn't succeed in adding unnamed parameter
thrown.expect(InvalidDataAccessApiUsageException.class);
sproc.addDeclaredParameter(new SqlParameter(1));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
sproc.addDeclaredParameter(new SqlParameter(1)));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,12 +24,11 @@ import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.*;
/**
@@ -45,9 +44,6 @@ public class SimpleJdbcInsertTests {
private DataSource dataSource;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() throws Exception {
@@ -77,13 +73,9 @@ public class SimpleJdbcInsertTests {
SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource).withTableName("x");
// Shouldn't succeed in inserting into table which doesn't exist
thrown.expect(InvalidDataAccessApiUsageException.class);
try {
insert.execute(new HashMap<>());
}
finally {
verify(resultSet).close();
}
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
insert.execute(new HashMap<>()));
verify(resultSet).close();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.*;
/**
* @author Juergen Hoeller

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,9 +21,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
@@ -31,6 +29,7 @@ import org.springframework.jdbc.LobRetrievalFailureException;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
@@ -39,9 +38,6 @@ import static org.mockito.BDDMockito.*;
*/
public class LobSupportTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testCreatingPreparedStatementCallback() throws SQLException {
LobHandler handler = mock(LobHandler.class);
@@ -77,13 +73,9 @@ public class LobSupportTests {
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
ResultSet rset = mock(ResultSet.class);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
lobRse.extractData(rset);
}
finally {
verify(rset).next();
}
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
lobRse.extractData(rset));
verify(rset).next();
}
@Test
@@ -101,13 +93,9 @@ public class LobSupportTests {
ResultSet rset = mock(ResultSet.class);
given(rset.next()).willReturn(true, true, false);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
lobRse.extractData(rset);
}
finally {
verify(rset).clearWarnings();
}
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
lobRse.extractData(rset));
verify(rset).clearWarnings();
}
@Test
@@ -116,8 +104,8 @@ public class LobSupportTests {
ResultSet rset = mock(ResultSet.class);
given(rset.next()).willReturn(true);
AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(true);
thrown.expect(LobRetrievalFailureException.class);
lobRse.extractData(rset);
assertThatExceptionOfType(LobRetrievalFailureException.class).isThrownBy(() ->
lobRse.extractData(rset));
}
private AbstractLobStreamingResultSetExtractor<Void> getResultSetExtractor(final boolean ex) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,9 +24,7 @@ import java.sql.SQLException;
import java.sql.Types;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
@@ -34,9 +32,11 @@ import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**
@@ -57,9 +57,6 @@ import static org.mockito.BDDMockito.*;
*/
public class SqlLobValueTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private PreparedStatement preparedStatement;
private LobHandler handler;
private LobCreator creator;
@@ -95,8 +92,8 @@ public class SqlLobValueTests {
@Test
public void test3() throws SQLException {
SqlLobValue lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test"));
}
@Test
@@ -131,8 +128,8 @@ public class SqlLobValueTests {
@Test
public void test7() throws SQLException {
SqlLobValue lob = new SqlLobValue("bla".getBytes());
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test"));
}
@Test
@@ -192,8 +189,8 @@ public class SqlLobValueTests {
@Test
public void testOtherSqlType() throws SQLException {
SqlLobValue lob = new SqlLobValue("Bla", handler);
thrown.expect(IllegalArgumentException.class);
lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test");
assertThatIllegalArgumentException().isThrownBy(() ->
lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -210,7 +210,7 @@ public class DataSourceTransactionManagerTests {
final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds);
tm = new DataSourceTransactionManager(dsToUse);
TransactionTemplate tt = new TransactionTemplate(tm);
TransactionTemplate tt = new TransactionTemplate(tm);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@ import javax.sql.DataSource;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.*;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@ import java.util.Properties;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.*;
/**
* @author Rod Johnson

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource;
import java.sql.Connection;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.jdbc.datasource.embedded;
import org.junit.Test;
import org.springframework.core.io.ClassRelativeResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.CannotReadScriptException;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,8 +24,8 @@ import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,9 +17,10 @@
package org.springframework.jdbc.datasource.init;
import org.junit.Test;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -183,7 +183,7 @@ public class ScriptUtilsUnitTests {
assertFalse(containsSqlScriptDelimiters("select 1; select '\\n\n';", "\n"));
assertTrue(containsSqlScriptDelimiters("select 1\n select 2", "\n"));
assertFalse(containsSqlScriptDelimiters("select 1\n select 2", "\n\n"));
assertTrue(containsSqlScriptDelimiters("select 1\n\n select 2", "\n\n"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,10 +20,9 @@ import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
/**
@@ -34,9 +33,6 @@ public class MapDataSourceLookupTests {
private static final String DATA_SOURCE_NAME = "dataSource";
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
@@ -44,8 +40,8 @@ public class MapDataSourceLookupTests {
MapDataSourceLookup lookup = new MapDataSourceLookup();
Map dataSources = lookup.getDataSources();
exception.expect(UnsupportedOperationException.class);
dataSources.put("", "");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
dataSources.put("", ""));
}
@Test
@@ -94,16 +90,16 @@ public class MapDataSourceLookupTests {
dataSources.put(DATA_SOURCE_NAME, new Object());
MapDataSourceLookup lookup = new MapDataSourceLookup(dataSources);
exception.expect(ClassCastException.class);
lookup.getDataSource(DATA_SOURCE_NAME);
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
lookup.getDataSource(DATA_SOURCE_NAME));
}
@Test
public void getDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() throws Exception {
MapDataSourceLookup lookup = new MapDataSourceLookup();
exception.expect(DataSourceLookupFailureException.class);
lookup.getDataSource(DATA_SOURCE_NAME);
assertThatExceptionOfType(DataSourceLookupFailureException.class).isThrownBy(() ->
lookup.getDataSource(DATA_SOURCE_NAME));
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.object;
import java.sql.ResultSet;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,12 +19,9 @@ package org.springframework.jdbc.object;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -33,8 +30,7 @@ import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import static org.hamcrest.CoreMatchers.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
/**
@@ -46,14 +42,11 @@ public class RdbmsOperationTests {
private final TestRdbmsOperation operation = new TestRdbmsOperation();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void emptySql() {
exception.expect(InvalidDataAccessApiUsageException.class);
operation.compile();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
operation::compile);
}
@Test
@@ -61,8 +54,8 @@ public class RdbmsOperationTests {
operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable");
operation.compile();
exception.expect(InvalidDataAccessApiUsageException.class);
operation.setTypes(new int[] { Types.INTEGER });
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.setTypes(new int[] { Types.INTEGER }));
}
@Test
@@ -70,40 +63,39 @@ public class RdbmsOperationTests {
operation.setDataSource(new DriverManagerDataSource());
operation.setSql("select * from mytable");
operation.compile();
exception.expect(InvalidDataAccessApiUsageException.class);
operation.declareParameter(new SqlParameter(Types.INTEGER));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.declareParameter(new SqlParameter(Types.INTEGER)));
}
@Test
public void tooFewParameters() {
operation.setSql("select * from mytable");
operation.setTypes(new int[] { Types.INTEGER });
exception.expect(InvalidDataAccessApiUsageException.class);
operation.validateParameters((Object[]) null);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateParameters((Object[]) null));
}
@Test
public void tooFewMapParameters() {
operation.setSql("select * from mytable");
operation.setTypes(new int[] { Types.INTEGER });
exception.expect(InvalidDataAccessApiUsageException.class);
operation.validateNamedParameters((Map<String, String>) null);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateNamedParameters((Map<String, String>) null));
}
@Test
public void operationConfiguredViaJdbcTemplateMustGetDataSource() throws Exception {
operation.setSql("foo");
exception.expect(InvalidDataAccessApiUsageException.class);
exception.expectMessage(containsString("ataSource"));
operation.compile();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.compile())
.withMessageContaining("ataSource");
}
@Test
public void tooManyParameters() {
operation.setSql("select * from mytable");
exception.expect(InvalidDataAccessApiUsageException.class);
operation.validateParameters(new Object[] { 1, 2 });
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateParameters(new Object[] { 1, 2 }));
}
@Test
@@ -111,8 +103,8 @@ public class RdbmsOperationTests {
operation.setSql("select * from mytable");
Map<String, String> params = new HashMap<>();
params.put("col1", "value");
exception.expect(InvalidDataAccessApiUsageException.class);
operation.validateNamedParameters(params);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
operation.validateNamedParameters(params));
}
@Test
@@ -128,8 +120,8 @@ public class RdbmsOperationTests {
public void emptyDataSource() {
SqlOperation operation = new SqlOperation() {};
operation.setSql("select * from mytable");
exception.expect(InvalidDataAccessApiUsageException.class);
operation.compile();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
operation::compile);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,9 +30,7 @@ import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -41,9 +39,11 @@ import org.springframework.jdbc.core.SqlParameter;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**
@@ -82,9 +82,6 @@ public class SqlQueryTests {
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
private static final int[] COLUMN_TYPES = new int[] {Types.INTEGER, Types.VARCHAR};
@Rule
public ExpectedException thrown = ExpectedException.none();
private Connection connection;
private DataSource dataSource;
private PreparedStatement preparedStatement;
@@ -141,8 +138,8 @@ public class SqlQueryTests {
query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1]));
query.compile();
thrown.expect(InvalidDataAccessApiUsageException.class);
query.execute();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
query::execute);
}
@Test
@@ -159,8 +156,8 @@ public class SqlQueryTests {
query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1]));
query.compile();
thrown.expect(InvalidDataAccessApiUsageException.class);
query.executeByNamedParam(Collections.singletonMap(COLUMN_NAMES[0], "value"));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
query.executeByNamedParam(Collections.singletonMap(COLUMN_NAMES[0], "value")));
}
@Test
@@ -353,17 +350,13 @@ public class SqlQueryTests {
}
CustomerQuery query = new CustomerQuery(dataSource);
thrown.expect(IncorrectResultSizeDataAccessException.class);
try {
query.findCustomer("rod");
}
finally {
verify(preparedStatement).setString(1, "rod");
verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE);
verify(resultSet).close();
verify(preparedStatement).close();
verify(connection).close();
}
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
query.findCustomer("rod"));
verify(preparedStatement).setString(1, "rod");
verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE);
verify(resultSet).close();
verify(preparedStatement).close();
verify(connection).close();
}
@Test
@@ -509,8 +502,8 @@ public class SqlQueryTests {
// Query should not succeed since parameter declaration did not specify parameter name
CustomerQuery query = new CustomerQuery(dataSource);
thrown.expect(InvalidDataAccessApiUsageException.class);
query.findCustomer(1);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
query.findCustomer(1));
}
@Test
@@ -711,8 +704,8 @@ public class SqlQueryTests {
}
CustomerQuery query = new CustomerQuery(dataSource);
thrown.expect(InvalidDataAccessApiUsageException.class);
query.findCustomers(1);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
query.findCustomers(1));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,15 +28,14 @@ import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
@@ -68,9 +67,6 @@ public class SqlUpdateTests {
private static final String INSERT_GENERATE_KEYS =
"insert into show (name) values(?)";
@Rule
public ExpectedException thrown = ExpectedException.none();
private DataSource dataSource;
private Connection connection;
@@ -275,8 +271,8 @@ public class SqlUpdateTests {
MaxRowsUpdater pc = new MaxRowsUpdater();
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
pc.run();
assertThatExceptionOfType(JdbcUpdateAffectedIncorrectNumberOfRowsException.class).isThrownBy(
pc::run);
}
@Test
@@ -294,9 +290,9 @@ public class SqlUpdateTests {
public void testNotRequiredRows() throws SQLException {
given(preparedStatement.executeUpdate()).willReturn(2);
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
RequiredRowsUpdater pc = new RequiredRowsUpdater();
pc.run();
assertThatExceptionOfType(JdbcUpdateAffectedIncorrectNumberOfRowsException.class).isThrownBy(
pc::run);
}
private class Updater extends SqlUpdate {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,9 +30,7 @@ import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -52,7 +50,9 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import org.springframework.lang.Nullable;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;
/**
@@ -62,9 +62,6 @@ import static org.mockito.BDDMockito.*;
*/
public class StoredProcedureTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private DataSource dataSource;
private Connection connection;
private CallableStatement callableStatement;
@@ -97,8 +94,8 @@ public class StoredProcedureTests {
callableStatement);
NoSuchStoredProcedure sproc = new NoSuchStoredProcedure(dataSource);
thrown.expect(BadSqlGrammarException.class);
sproc.execute();
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(
sproc::execute);
}
private void testAddInvoice(final int amount, final int custid) throws Exception {
@@ -164,8 +161,6 @@ public class StoredProcedureTests {
/**
* Confirm no connection was used to get metadata. Does not use superclass replay
* mechanism.
*
* @throws Exception
*/
@Test
public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator()
@@ -203,8 +198,6 @@ public class StoredProcedureTests {
/**
* Confirm our JdbcTemplate is used
*
* @throws Exception
*/
@Test
public void testStoredProcedureConfiguredViaJdbcTemplate() throws Exception {
@@ -235,17 +228,16 @@ public class StoredProcedureTests {
public void testUnnamedParameter() throws Exception {
this.verifyClosedAfter = false;
// Shouldn't succeed in creating stored procedure with unnamed parameter
thrown.expect(InvalidDataAccessApiUsageException.class);
new UnnamedParameterStoredProcedure(dataSource);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
new UnnamedParameterStoredProcedure(dataSource));
}
@Test
public void testMissingParameter() throws Exception {
this.verifyClosedAfter = false;
MissingParameterStoredProcedure mp = new MissingParameterStoredProcedure(dataSource);
thrown.expect(InvalidDataAccessApiUsageException.class);
mp.execute();
fail("Shouldn't succeed in running stored procedure with missing required parameter");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
mp::execute);
}
@Test
@@ -256,8 +248,8 @@ public class StoredProcedureTests {
given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")
).willReturn(callableStatement);
StoredProcedureExceptionTranslator sproc = new StoredProcedureExceptionTranslator(dataSource);
thrown.expect(CustomDataException.class);
sproc.execute();
assertThatExceptionOfType(CustomDataException.class).isThrownBy(
sproc::execute);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.*;
/**
* @author Juergen Hoeller

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,16 +19,14 @@ package org.springframework.jdbc.support;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import static java.util.Arrays.asList;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static org.hamcrest.CoreMatchers.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
/**
@@ -43,9 +41,6 @@ public class KeyHolderTests {
private final KeyHolder kh = new GeneratedKeyHolder();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void singleKey() {
@@ -58,18 +53,18 @@ public class KeyHolderTests {
public void singleKeyNonNumeric() {
kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));
exception.expect(DataRetrievalFailureException.class);
exception.expectMessage(startsWith("The generated key is not of a supported numeric type."));
kh.getKey().intValue();
assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
kh.getKey().intValue())
.withMessageStartingWith("The generated key is not of a supported numeric type.");
}
@Test
public void noKeyReturnedInMap() {
kh.getKeyList().addAll(singletonList(emptyMap()));
exception.expect(DataRetrievalFailureException.class);
exception.expectMessage(startsWith("Unable to retrieve the generated key."));
kh.getKey();
assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
kh.getKey())
.withMessageStartingWith("Unable to retrieve the generated key.");
}
@Test
@@ -81,9 +76,9 @@ public class KeyHolderTests {
kh.getKeyList().addAll(singletonList(m));
assertEquals("two keys should be in the map", 2, kh.getKeys().size());
exception.expect(InvalidDataAccessApiUsageException.class);
exception.expectMessage(startsWith("The getKey method should only be used when a single key is returned."));
kh.getKey();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
kh.getKey())
.withMessageStartingWith("The getKey method should only be used when a single key is returned.");
}
@Test
@@ -95,9 +90,9 @@ public class KeyHolderTests {
kh.getKeyList().addAll(asList(m, m));
assertEquals("two rows should be in the list", 2, kh.getKeyList().size());
exception.expect(InvalidDataAccessApiUsageException.class);
exception.expectMessage(startsWith("The getKeys method should only be used when keys for a single row are returned."));
kh.getKeys();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
kh.getKeys())
.withMessageStartingWith("The getKeys method should only be used when keys for a single row are returned.");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,9 +20,7 @@ import java.sql.BatchUpdateException;
import java.sql.DataTruncation;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.CannotSerializeTransactionException;
@@ -35,6 +33,7 @@ import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.InvalidResultSetAccessException;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.*;
/**
@@ -56,9 +55,6 @@ public class SQLErrorCodeSQLExceptionTranslatorTests {
ERROR_CODES.setCannotSerializeTransactionCodes(new String[] { "9" });
}
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void errorCodeTranslation() {
@@ -177,8 +173,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests {
assertEquals(invResEx, diex.getCause());
// Shouldn't custom translate this - invalid class
exception.expect(IllegalArgumentException.class);
customTranslation.setExceptionClass(String.class);
assertThatIllegalArgumentException().isThrownBy(() ->
customTranslation.setExceptionClass(String.class));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.jdbc.support;
import java.sql.SQLException;
import org.junit.Test;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.UncategorizedSQLException;