DATAJPA-1783 - Migrate off ExpectedException and Test(expected=…) to AssertJ's assertThatExceptionOfType(…) and assertThat…Exception(…).

We now no longer use the ExpectedException rule and JUnit's built-in exception assertion on Test-method level. Instead we use AssertJ's functional exception assertions.
This commit is contained in:
Mark Paluch
2020-09-23 10:09:05 +02:00
parent 48597dca24
commit cfd8ef9cde
33 changed files with 195 additions and 201 deletions

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.convert;
import static org.assertj.core.api.AssertionsForInterfaceTypes.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.domain.Example.*;
@@ -38,13 +38,12 @@ import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.Type;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
@@ -84,8 +83,6 @@ public class QueryByExamplePredicateBuilderUnitTests {
SingularAttribute<? super Skill, String> skillNameAttribute;
SingularAttribute<? super Skill, Skill> skillNestedAttribute;
public @Rule ExpectedException exception = ExpectedException.none();
@Before
public void setUp() {
@@ -134,19 +131,22 @@ public class QueryByExamplePredicateBuilderUnitTests {
doReturn(orPredicate).when(cb).or(ArgumentMatchers.any());
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
@Test // DATAJPA-218
public void getPredicateShouldThrowExceptionOnNullRoot() {
QueryByExamplePredicateBuilder.getPredicate(null, cb, of(new Person()), EscapeCharacter.DEFAULT);
assertThatIllegalArgumentException().isThrownBy(
() -> QueryByExamplePredicateBuilder.getPredicate(null, cb, of(new Person()), EscapeCharacter.DEFAULT));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
@Test // DATAJPA-218
public void getPredicateShouldThrowExceptionOnNullCriteriaBuilder() {
QueryByExamplePredicateBuilder.getPredicate(root, null, of(new Person()), EscapeCharacter.DEFAULT);
assertThatIllegalArgumentException().isThrownBy(
() -> QueryByExamplePredicateBuilder.getPredicate(root, null, of(new Person()), EscapeCharacter.DEFAULT));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
@Test // DATAJPA-218
public void getPredicateShouldThrowExceptionOnNullExample() {
QueryByExamplePredicateBuilder.getPredicate(root, null, null, EscapeCharacter.DEFAULT);
assertThatIllegalArgumentException()
.isThrownBy(() -> QueryByExamplePredicateBuilder.getPredicate(root, null, null, EscapeCharacter.DEFAULT));
}
@Test // DATAJPA-218

View File

@@ -25,9 +25,9 @@ import javax.persistence.metamodel.PluralAttribute;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.JpaSort.JpaOrder;
import org.springframework.data.jpa.domain.JpaSort.Path;
import org.springframework.data.jpa.domain.JpaSort.*;
import org.springframework.data.jpa.domain.sample.Address_;
import org.springframework.data.jpa.domain.sample.MailMessage_;
import org.springframework.data.jpa.domain.sample.MailSender_;
@@ -57,24 +57,24 @@ public class JpaSortTests {
private static final @Nullable PluralAttribute<?, ?, ?> NULL_PLURAL_ATTRIBUTE = null;
private static final PluralAttribute<?, ?, ?>[] EMPTY_PLURAL_ATTRIBUTES = new PluralAttribute<?, ?, ?>[0];
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
@Test // DATAJPA-12
public void rejectsNullAttribute() {
JpaSort.of(NULL_ATTRIBUTE);
assertThatIllegalArgumentException().isThrownBy(() -> of(NULL_ATTRIBUTE));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
@Test // DATAJPA-12
public void rejectsEmptyAttributes() {
JpaSort.of(EMPTY_ATTRIBUTES);
assertThatIllegalArgumentException().isThrownBy(() -> of(EMPTY_ATTRIBUTES));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
@Test // DATAJPA-12
public void rejectsNullPluralAttribute() {
JpaSort.of(NULL_PLURAL_ATTRIBUTE);
assertThatIllegalArgumentException().isThrownBy(() -> of(NULL_PLURAL_ATTRIBUTE));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
@Test // DATAJPA-12
public void rejectsEmptyPluralAttributes() {
JpaSort.of(EMPTY_PLURAL_ATTRIBUTES);
assertThatIllegalArgumentException().isThrownBy(() -> of(EMPTY_PLURAL_ATTRIBUTES));
}
@Test // DATAJPA-12
@@ -140,14 +140,14 @@ public class JpaSortTests {
.containsExactly(Order.asc("firstname"), Order.desc("mailSender.name"));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-702
@Test // DATAJPA-702
public void rejectsNullAttributesForCombiningCriterias() {
JpaSort.of(User_.firstname).and(DESC, (Attribute<?, ?>[]) null);
assertThatIllegalArgumentException().isThrownBy(() -> of(User_.firstname).and(DESC, (Attribute<?, ?>[]) null));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-702
@Test // DATAJPA-702
public void rejectsNullPathsForCombiningCriterias() {
JpaSort.of(User_.firstname).and(DESC, (Path<?, ?>[]) null);
assertThatIllegalArgumentException().isThrownBy(() -> of(User_.firstname).and(DESC, (Path<?, ?>[]) null));
}
@Test // DATAJPA-702

View File

@@ -66,9 +66,10 @@ public class AuditingBeanFactoryPostProcessorUnitTests {
assertThat(beanFactory.isBeanNameInUse(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME)).isTrue();
}
@Test(expected = IllegalStateException.class) // DATAJPA-265
@Test // DATAJPA-265
public void rejectsConfigurationWithoutSpringConfigured() {
processor.postProcessBeanFactory(new DefaultListableBeanFactory());
assertThatIllegalStateException()
.isThrownBy(() -> processor.postProcessBeanFactory(new DefaultListableBeanFactory()));
}
@Test // DATAJPA-265

View File

@@ -21,6 +21,7 @@ import java.util.Collections;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
@@ -97,12 +98,14 @@ public class JavaConfigUserRepositoryTests extends UserRepositoryTests {
}
}
@Test(expected = NoSuchBeanDefinitionException.class) // DATAJPA-317
@Test // DATAJPA-317
public void doesNotPickUpJpaRepository() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(JpaRepositoryConfig.class);
context.getBean("jpaRepository");
context.close();
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(JpaRepositoryConfig.class)) {
Assertions.assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean("jpaRepository"));
context.close();
}
}
@Configuration

View File

@@ -20,12 +20,10 @@ import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.sample.EmbeddedIdExampleDepartment;
@@ -55,8 +53,6 @@ import org.springframework.transaction.annotation.Transactional;
@Transactional
public class RepositoryWithCompositeKeyTests {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Autowired EmployeeRepositoryWithIdClass employeeRepositoryWithIdClass;
@Autowired EmployeeRepositoryWithEmbeddedId employeeRepositoryWithEmbeddedId;
@@ -116,13 +112,6 @@ public class RepositoryWithCompositeKeyTests {
@Test // DATAJPA-472, DATAJPA-912
public void shouldSupportFindAllWithPageableAndEntityWithIdClass() throws Exception {
if (Package.getPackage("org.hibernate.cfg").getImplementationVersion().startsWith("4.1.")) {
// we expect this test to fail on 4.1.x - due to a bug in hibernate - remove as soon as 4.1.x fixes the issue.
expectedException.expect(InvalidDataAccessApiUsageException.class);
expectedException.expectMessage("No supertype found");
}
IdClassExampleDepartment dep = new IdClassExampleDepartment();
dep.setName("TestDepartment");
dep.setDepartmentId(-1);

View File

@@ -19,10 +19,9 @@ import static org.assertj.core.api.Assertions.*;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@@ -51,8 +50,6 @@ import org.springframework.transaction.annotation.Transactional;
@Transactional
public class RepositoryWithIdClassKeyTests {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Autowired private SiteRepository siteRepository;
@Autowired private ItemRepository itemRepository;

View File

@@ -271,10 +271,12 @@ public class UserRepositoryFinderTests {
.isNotNull();
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-1023, DATACMNS-959
@Test // DATAJPA-1023, DATACMNS-959
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void rejectsStreamExecutionIfNoSurroundingTransactionActive() {
userRepository.findAllByCustomQueryAndStream();
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> userRepository.findAllByCustomQueryAndStream());
}
@Test // DATAJPA-1334

View File

@@ -363,12 +363,12 @@ public class UserRepositoryTests {
/**
* Tests, that persisting a relationsship without cascade attributes throws a {@code DataAccessException}.
*/
@Test(expected = DataAccessException.class)
@Test
public void testPreventsCascadingRolePersisting() {
firstUser.addRole(new Role("USER"));
flushTestUsers();
assertThatExceptionOfType(DataAccessException.class).isThrownBy(this::flushTestUsers);
}
/**
@@ -447,11 +447,13 @@ public class UserRepositoryTests {
assertThat(repository.findOne(userHasLastname("Beauford"))).isNotPresent();
}
@Test(expected = IncorrectResultSizeDataAccessException.class)
@Test
public void throwsExceptionForUnderSpecifiedSingleEntitySpecification() {
flushTestUsers();
repository.findOne(userHasFirstnameLike("e"));
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
.isThrownBy(() -> repository.findOne(userHasFirstnameLike("e")));
}
@Test
@@ -1698,9 +1700,10 @@ public class UserRepositoryTests {
assertThat(users).hasSize(4);
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
@Test // DATAJPA-218
public void findAllByNullExample() {
repository.findAll((Example<User>) null);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> repository.findAll((Example<User>) null));
}
@Test // DATAJPA-218
@@ -1790,7 +1793,7 @@ public class UserRepositoryTests {
assertThat(users).containsOnly(firstUser);
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
@Test // DATAJPA-218
public void findAllByExampleWithRegexStringMatcher() {
flushTestUsers();
@@ -1799,7 +1802,7 @@ public class UserRepositoryTests {
prototype.setFirstname("^Oliver$");
Example<User> example = Example.of(prototype, matching().withStringMatcher(StringMatcher.REGEX));
repository.findAll(example);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> repository.findAll(example));
}
@Test // DATAJPA-218
@@ -1922,7 +1925,7 @@ public class UserRepositoryTests {
assertThat(users.getTotalElements()).isEqualTo(100L);
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
@Test // DATAJPA-218
public void findAllByExampleShouldNotAllowCycles() {
flushTestUsers();
@@ -1935,10 +1938,11 @@ public class UserRepositoryTests {
Example<User> example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")
.withStringMatcher(StringMatcher.STARTING).withIgnoreCase());
repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age")));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age"))));
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
@Test // DATAJPA-218
public void findAllByExampleShouldNotAllowCyclesOverSeveralInstances() {
flushTestUsers();
@@ -1955,7 +1959,8 @@ public class UserRepositoryTests {
Example<User> example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")
.withStringMatcher(StringMatcher.STARTING).withIgnoreCase());
repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age")));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age"))));
}
@Test // DATAJPA-218

View File

@@ -62,12 +62,13 @@ public class AuditingBeanDefinitionParserTests {
assertThat(bean).isNotNull();
}
@Test(expected = BeanDefinitionParsingException.class) // DATAJPA-367
@Test // DATAJPA-367
public void shouldThrowBeanDefinitionParsingExceptionIfClassFromSpringAspectsJarCannotBeFound() {
ShadowingClassLoader scl = new ShadowingClassLoader(getClass().getClassLoader());
scl.excludeClass(AuditingBeanDefinitionParser.AUDITING_ENTITY_LISTENER_CLASS_NAME);
loadFactoryFrom("auditing/auditing-namespace-context.xml", scl);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> loadFactoryFrom("auditing/auditing-namespace-context.xml", scl));
}
private void assertSetDatesIsSetTo(String configFile, String value) {

View File

@@ -53,9 +53,9 @@ public class CustomRepositoryFactoryConfigTests {
transactionManager.resetCount();
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void testCustomFactoryUsed() {
userRepository.customMethod(1);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> userRepository.customMethod(1));
}
@Test

View File

@@ -24,12 +24,11 @@ import java.util.Collections;
import javax.persistence.EntityManagerFactory;
import javax.persistence.metamodel.Metamodel;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@@ -52,7 +51,6 @@ import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcesso
@RunWith(MockitoJUnitRunner.class)
public class JpaRepositoryConfigExtensionUnitTests {
public @Rule ExpectedException exception = ExpectedException.none();
@Mock RepositoryConfigurationSource configSource;
@Test
@@ -147,7 +145,8 @@ public class JpaRepositoryConfigExtensionUnitTests {
extension.registerBeansForRoot(factory, configSource);
assertThat(factory.getBean(expectedBeanName)).isNotNull();
exception.expect(NoSuchBeanDefinitionException.class);
factory.getBeanDefinition("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#1");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> factory
.getBeanDefinition("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#1"));
}
}

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.data.jpa.support.EntityManagerTestUtils.*;
@@ -154,13 +155,14 @@ public class Jpa21UtilsTests {
assertThat(colleaguesOfColleagues).terminatesGraphWith("roles");
}
@Test(expected = Exception.class) // DATAJPA-1041, DATAJPA-1075
@Test // DATAJPA-1041, DATAJPA-1075
public void errorsOnUnknownProperties() {
assumeTrue(currentEntityManagerIsAJpa21EntityManager(em));
Jpa21Utils.configureFetchGraphFrom(new JpaEntityGraph("name", EntityGraphType.FETCH, new String[] { "¯\\_(ツ)_/¯" }),
em.createEntityGraph(User.class));
assertThatExceptionOfType(Exception.class).isThrownBy(() -> Jpa21Utils.configureFetchGraphFrom(
new JpaEntityGraph("name", EntityGraphType.FETCH, new String[] { "¯\\_(ツ)_/¯" }),
em.createEntityGraph(User.class)));
}
/**

View File

@@ -69,16 +69,16 @@ public class JpaQueryExecutionUnitTests {
when(jpaQuery.getQueryMethod()).thenReturn(method);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullQuery() {
new StubQueryExecution().execute(null, accessor);
assertThatIllegalArgumentException().isThrownBy(() -> new StubQueryExecution().execute(null, accessor));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullBinder() throws Exception {
@Test
public void rejectsNullBinder() {
new StubQueryExecution().execute(jpaQuery, null);
assertThatIllegalArgumentException().isThrownBy(() -> new StubQueryExecution().execute(jpaQuery, null));
}
@Test
@@ -124,7 +124,7 @@ public class JpaQueryExecutionUnitTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void allowsMethodReturnTypesForModifyingQuery() throws Exception {
public void allowsMethodReturnTypesForModifyingQuery() {
when(method.getReturnType()).thenReturn((Class) void.class, (Class) int.class, (Class) Integer.class);
@@ -134,11 +134,11 @@ public class JpaQueryExecutionUnitTests {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(expected = IllegalArgumentException.class)
public void modifyingExecutionRejectsNonIntegerOrVoidReturnType() throws Exception {
@Test
public void modifyingExecutionRejectsNonIntegerOrVoidReturnType() {
when(method.getReturnType()).thenReturn((Class) Long.class);
new ModifyingExecution(method, em);
assertThatIllegalArgumentException().isThrownBy(() -> new ModifyingExecution(method, em));
}
@Test // DATAJPA-124, DATAJPA-912

View File

@@ -32,8 +32,8 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -113,17 +113,17 @@ public class JpaQueryMethodUnitTests {
assertThat(method.isNativeQuery()).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void preventsNullRepositoryMethod() {
new JpaQueryMethod(null, metadata, factory, extractor);
assertThatIllegalArgumentException().isThrownBy(() -> new JpaQueryMethod(null, metadata, factory, extractor));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void preventsNullQueryExtractor() throws Exception {
Method method = UserRepository.class.getMethod("findByLastname", String.class);
new JpaQueryMethod(method, metadata, factory, null);
assertThatIllegalArgumentException().isThrownBy(() -> new JpaQueryMethod(method, metadata, factory, null));
}
@Test
@@ -143,28 +143,30 @@ public class JpaQueryMethodUnitTests {
assertThat(method.getAnnotatedQuery()).isNotNull();
}
@Test(expected = IllegalStateException.class)
@Test
public void rejectsInvalidReturntypeOnPagebleFinder() {
new JpaQueryMethod(invalidReturnType, metadata, factory, extractor);
assertThatIllegalStateException()
.isThrownBy(() -> new JpaQueryMethod(invalidReturnType, metadata, factory, extractor));
}
@Test(expected = IllegalStateException.class)
@Test
public void rejectsPageableAndSortInFinderMethod() {
new JpaQueryMethod(pageableAndSort, metadata, factory, extractor);
assertThatIllegalStateException()
.isThrownBy(() -> new JpaQueryMethod(pageableAndSort, metadata, factory, extractor));
}
@Test(expected = IllegalStateException.class)
@Test
public void rejectsTwoPageableParameters() {
new JpaQueryMethod(pageableTwice, metadata, factory, extractor);
assertThatIllegalStateException().isThrownBy(() -> new JpaQueryMethod(pageableTwice, metadata, factory, extractor));
}
@Test(expected = IllegalStateException.class)
@Test
public void rejectsTwoSortableParameters() {
new JpaQueryMethod(sortableTwice, metadata, factory, extractor);
assertThatIllegalStateException().isThrownBy(() -> new JpaQueryMethod(sortableTwice, metadata, factory, extractor));
}
@Test
@@ -174,20 +176,20 @@ public class JpaQueryMethodUnitTests {
assertThat(method.isModifyingQuery()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsModifyingMethodWithPageable() throws Exception {
Method method = InvalidRepository.class.getMethod("updateMethod", String.class, Pageable.class);
new JpaQueryMethod(method, metadata, factory, extractor);
assertThatIllegalArgumentException().isThrownBy(() -> new JpaQueryMethod(method, metadata, factory, extractor));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsModifyingMethodWithSort() throws Exception {
Method method = InvalidRepository.class.getMethod("updateMethod", String.class, Sort.class);
new JpaQueryMethod(method, metadata, factory, extractor);
assertThatIllegalArgumentException().isThrownBy(() -> new JpaQueryMethod(method, metadata, factory, extractor));
}
@Test

View File

@@ -36,29 +36,29 @@ public class LikeBindingUnitTests {
assertThat(binding.prepare("value")).isEqualTo(value);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullName() {
new LikeParameterBinding(null, Type.CONTAINING);
assertThatIllegalArgumentException().isThrownBy(() -> new LikeParameterBinding(null, Type.CONTAINING));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsEmptyName() {
new LikeParameterBinding("", Type.CONTAINING);
assertThatIllegalArgumentException().isThrownBy(() -> new LikeParameterBinding("", Type.CONTAINING));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullType() {
new LikeParameterBinding("foo", null);
assertThatIllegalArgumentException().isThrownBy(() -> new LikeParameterBinding("foo", null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsInvalidType() {
new LikeParameterBinding("foo", Type.SIMPLE_PROPERTY);
assertThatIllegalArgumentException().isThrownBy(() -> new LikeParameterBinding("foo", Type.SIMPLE_PROPERTY));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsInvalidPosition() {
new LikeParameterBinding(0, Type.CONTAINING);
assertThatIllegalArgumentException().isThrownBy(() -> new LikeParameterBinding(0, Type.CONTAINING));
}
@Test

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@@ -30,6 +31,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.provider.QueryExtractor;
@@ -75,14 +77,14 @@ public class NamedQueryUnitTests {
when(emf.createEntityManager()).thenReturn(em);
}
@Test(expected = QueryCreationException.class)
@Test
public void rejectsPersistenceProviderIfIncapableOfExtractingQueriesAndPagebleBeingUsed() {
when(extractor.canExtractQuery()).thenReturn(false);
JpaQueryMethod queryMethod = new JpaQueryMethod(method, metadata, projectionFactory, extractor);
when(em.createNamedQuery(queryMethod.getNamedCountQueryName())).thenThrow(new IllegalArgumentException());
NamedQuery.lookupFrom(queryMethod, em);
assertThatExceptionOfType(QueryCreationException.class).isThrownBy(() -> NamedQuery.lookupFrom(queryMethod, em));
}
@Test // DATAJPA-142

View File

@@ -17,6 +17,7 @@ package org.springframework.data.jpa.repository.query;
import static java.util.Collections.*;
import static javax.persistence.TemporalType.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.any;
@@ -181,13 +182,12 @@ public class ParameterBinderUnitTests {
verify(query).setParameter(eq(1), eq(date), eq(TemporalType.TIMESTAMP));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-107
@Test // DATAJPA-107
public void shouldThrowIllegalArgumentExceptionIfIsAnnotatedWithTemporalParamAndParameterTypeIsNotDate()
throws Exception {
Method method = SampleRepository.class.getMethod("invalidWithTemporalTypeParameter", String.class);
JpaParameters parameters = new JpaParameters(method);
ParameterBinderFactory.createBinder(parameters);
assertThatIllegalArgumentException().isThrownBy(() -> new JpaParameters(method));
}
@Test // DATAJPA-461

View File

@@ -34,10 +34,9 @@ import javax.persistence.TemporalType;
import org.hibernate.Version;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -67,8 +66,6 @@ public class PartTreeJpaQueryIntegrationTests {
private static String PROPERTY = "h.target." + getQueryProperty();
@Rule public ExpectedException thrown = ExpectedException.none();
@PersistenceContext EntityManager entityManager;
PersistenceProvider provider;
@@ -89,11 +86,11 @@ public class PartTreeJpaQueryIntegrationTests {
}
@Test
public void cannotIgnoreCaseIfNotString() throws Exception {
public void cannotIgnoreCaseIfNotString() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Unable to ignore case of java.lang.Integer types, the property 'id' must reference a String");
testIgnoreCase("findByIdIgnoringCase", 3);
assertThatIllegalArgumentException().isThrownBy(() -> testIgnoreCase("findByIdIgnoringCase", 3))
.withMessageContaining(
"Unable to ignore case of java.lang.Integer types, the property 'id' must reference a String");
}
@Test
@@ -161,13 +158,12 @@ public class PartTreeJpaQueryIntegrationTests {
assertThat(HibernateUtils.getHibernateQuery(getValue(query, PROPERTY))).endsWith("roles is not empty");
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-1074
@Test // DATAJPA-1074
public void rejectsIsEmptyOnNonCollectionProperty() throws Exception {
JpaQueryMethod method = getQueryMethod("findByFirstnameIsEmpty");
AbstractJpaQuery jpaQuery = new PartTreeJpaQuery(method, entityManager);
jpaQuery.createQuery((getAccessor(method, new Object[] { "Oliver" })));
assertThatIllegalArgumentException().isThrownBy(() -> new PartTreeJpaQuery(method, entityManager));
}
@Test // DATAJPA-1182

View File

@@ -192,11 +192,12 @@ public class QueryUtilsUnitTests {
"select count(o) from Foo o where cb.id in (select b from Bar b)");
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-148
@Test // DATAJPA-148
public void doesNotPrefixSortsIfFunction() {
Sort sort = Sort.by("sum(foo)");
assertThat(applySorting("select p from Person p", sort, "p")).endsWith("order by sum(foo) asc");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> applySorting("select p from Person p", sort, "p"));
}
@Test // DATAJPA-377
@@ -283,11 +284,12 @@ public class QueryUtilsUnitTests {
assertThat(applySorting("from mytable where ?1 is null", Sort.by("firstname"))).endsWith("order by firstname asc");
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-965, DATAJPA-970
@Test // DATAJPA-965, DATAJPA-970
public void doesNotAllowWhitespaceInSort() {
Sort sort = Sort.by("case when foo then bar");
applySorting("select p from Person p", sort, "p");
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> applySorting("select p from Person p", sort, "p"));
}
@Test // DATAJPA-965, DATAJPA-970

View File

@@ -30,9 +30,7 @@ import javax.persistence.TypedQuery;
import javax.persistence.metamodel.Metamodel;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -83,8 +81,6 @@ public class SimpleJpaQueryUnitTests {
ProjectionFactory factory = new SpelAwareProxyProjectionFactory();
public @Rule ExpectedException exception = ExpectedException.none();
@Before
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setUp() throws SecurityException, NoSuchMethodException {
@@ -154,11 +150,11 @@ public class SimpleJpaQueryUnitTests {
verify(em).createNativeQuery("SELECT u FROM User u WHERE u.lastname = ?1", User.class);
}
@Test(expected = InvalidJpaQueryMethodException.class) // DATAJPA-554
@Test // DATAJPA-554
public void rejectsNativeQueryWithDynamicSort() throws Exception {
Method method = SampleRepository.class.getMethod("findNativeByLastname", String.class, Sort.class);
createJpaQuery(method);
assertThatExceptionOfType(InvalidJpaQueryMethodException.class).isThrownBy(() -> createJpaQuery(method));
}
@Test // DATAJPA-352
@@ -178,11 +174,9 @@ public class SimpleJpaQueryUnitTests {
Method method = SampleRepository.class.getMethod("pageByAnnotatedQuery", Pageable.class);
when(em.createQuery(Mockito.contains("count"))).thenThrow(IllegalArgumentException.class);
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Count");
exception.expectMessage(method.getName());
createJpaQuery(method);
assertThatIllegalArgumentException().isThrownBy(() -> createJpaQuery(method)).withMessageContaining("Count")
.withMessageContaining(method.getName());
}
@Test

View File

@@ -22,9 +22,8 @@ import java.util.List;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.SoftAssertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.data.jpa.repository.query.StringQuery.InParameterBinding;
import org.springframework.data.jpa.repository.query.StringQuery.LikeParameterBinding;
import org.springframework.data.jpa.repository.query.StringQuery.ParameterBinding;
@@ -41,8 +40,6 @@ import org.springframework.data.repository.query.parser.Part.Type;
*/
public class StringQueryUnitTests {
public @Rule ExpectedException exception = ExpectedException.none();
SoftAssertions softly = new SoftAssertions();
@Test // DATAJPA-341
@@ -180,9 +177,10 @@ public class StringQueryUnitTests {
new StringQuery("select u from User u where u.firstname like %:firstname or foo like :bar");
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-292, DATAJPA-362
@Test // DATAJPA-292, DATAJPA-362
public void rejectsDifferentBindingsForRepeatedParameter() {
new StringQuery("select u from User u where u.firstname like %?1 and u.lastname like ?1%");
assertThatIllegalArgumentException()
.isThrownBy(() -> new StringQuery("select u from User u where u.firstname like %?1 and u.lastname like ?1%"));
}
@Test // DATAJPA-461
@@ -281,9 +279,10 @@ public class StringQueryUnitTests {
softly.assertAll();
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-362
@Test // DATAJPA-362
public void rejectsDifferentBindingsForRepeatedParameter2() {
new StringQuery("select u from User u where u.firstname like ?1 and u.lastname like %?1");
assertThatIllegalArgumentException()
.isThrownBy(() -> new StringQuery("select u from User u where u.firstname like ?1 and u.lastname like %?1"));
}
@Test // DATAJPA-712

View File

@@ -28,9 +28,8 @@ import javax.sql.DataSource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -62,7 +61,6 @@ import org.springframework.stereotype.Component;
public class DefaultJpaContextIntegrationTests {
static EntityManagerFactory firstEmf, secondEmf;
public @Rule ExpectedException exception = ExpectedException.none();
EntityManager firstEm, secondEm;
JpaContext jpaContext;
@@ -105,10 +103,8 @@ public class DefaultJpaContextIntegrationTests {
@Test // DATAJPA-669
public void rejectsUnmanagedType() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage(Object.class.getSimpleName());
jpaContext.getEntityManagerByManagedType(Object.class);
assertThatIllegalArgumentException().isThrownBy(() -> jpaContext.getEntityManagerByManagedType(Object.class))
.withMessageContaining(Object.class.getSimpleName());
}
@Test // DATAJPA-669
@@ -119,10 +115,8 @@ public class DefaultJpaContextIntegrationTests {
@Test // DATAJPA-669
public void rejectsRequestForTypeManagedByMultipleEntityManagers() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage(User.class.getSimpleName());
jpaContext.getEntityManagerByManagedType(User.class);
assertThatIllegalArgumentException().isThrownBy(() -> jpaContext.getEntityManagerByManagedType(User.class))
.withMessageContaining(User.class.getSimpleName());
}
@Test // DATAJPA-813, DATAJPA-956

View File

@@ -15,6 +15,8 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
import javax.persistence.EntityManager;
@@ -30,13 +32,14 @@ import org.junit.Test;
*/
public class DefaultJpaContextUnitTests {
@Test(expected = IllegalArgumentException.class) // DATAJPA-669
@Test // DATAJPA-669
public void rejectsNullEntityManagers() {
new DefaultJpaContext(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DefaultJpaContext(null));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-669
@Test // DATAJPA-669
public void rejectsEmptyEntityManagers() {
new DefaultJpaContext(Collections.<EntityManager> emptySet());
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultJpaContext(Collections.<EntityManager> emptySet()));
}
}

View File

@@ -35,10 +35,10 @@ import org.springframework.data.jpa.repository.query.DefaultJpaEntityMetadata;
*/
public class DefaultJpaEntityMetadataUnitTest {
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void rejectsNullDomainType() {
new DefaultJpaEntityMetadata(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DefaultJpaEntityMetadata(null));
}
@Test

View File

@@ -19,10 +19,9 @@ import static org.assertj.core.api.Assertions.*;
import javax.persistence.TransactionRequiredException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.PageRequest;
@@ -41,8 +40,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class DefaultTransactionDisablingIntegrationTests {
public @Rule ExpectedException exception = ExpectedException.none();
@Autowired UserRepository repository;
@Autowired DelegatingTransactionManager txManager;

View File

@@ -53,11 +53,12 @@ public class JpaEntityInformationSupportUnitTests {
assertThat(second.getEntityName()).isEqualTo("AnotherNamedUser");
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-93
@Test // DATAJPA-93
public void rejectsClassNotBeingFoundInMetamodel() {
when(em.getMetamodel()).thenReturn(metaModel);
JpaEntityInformationSupport.getEntityInformation(User.class, em);
assertThatIllegalArgumentException()
.isThrownBy(() -> JpaEntityInformationSupport.getEntityInformation(User.class, em));
}
static class User {

View File

@@ -87,7 +87,7 @@ public class JpaRepositoryFactoryBeanUnitTests {
* @throws Exception
*/
@Test
public void setsUpBasicInstanceCorrectly() throws Exception {
public void setsUpBasicInstanceCorrectly() {
factoryBean.setBeanFactory(beanFactory);
factoryBean.afterPropertiesSet();
@@ -95,19 +95,20 @@ public class JpaRepositoryFactoryBeanUnitTests {
assertThat(factoryBean.getObject()).isNotNull();
}
@Test(expected = IllegalArgumentException.class)
public void requiresListableBeanFactory() throws Exception {
@Test
public void requiresListableBeanFactory() {
factoryBean.setBeanFactory(mock(BeanFactory.class));
assertThatIllegalArgumentException().isThrownBy(() -> factoryBean.setBeanFactory(mock(BeanFactory.class)));
}
/**
* Assert that the factory rejects calls to {@code JpaRepositoryFactoryBean#setRepositoryInterface(Class)} with
* {@literal null} or any other parameter instance not implementing {@code Repository}.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void preventsNullRepositoryInterface() {
new JpaRepositoryFactoryBean<Repository<Object, Long>, Object, Long>(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new JpaRepositoryFactoryBean<Repository<Object, Long>, Object, Long>(null));
}
public interface SimpleSampleRepository extends JpaRepository<User, Integer> {

View File

@@ -119,28 +119,28 @@ public class JpaRepositoryFactoryUnitTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void handlesRuntimeExceptionsCorrectly() {
SampleRepository repository = factory.getRepository(SampleRepository.class, new SampleCustomRepositoryImpl());
repository.throwingRuntimeException();
assertThatIllegalArgumentException().isThrownBy(repository::throwingRuntimeException);
}
@Test(expected = IOException.class)
public void handlesCheckedExceptionsCorrectly() throws Exception {
@Test
public void handlesCheckedExceptionsCorrectly() {
SampleRepository repository = factory.getRepository(SampleRepository.class, new SampleCustomRepositoryImpl());
repository.throwingCheckedException();
assertThatExceptionOfType(IOException.class).isThrownBy(repository::throwingCheckedException);
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void createsProxyWithCustomBaseClass() {
JpaRepositoryFactory factory = new CustomGenericJpaRepositoryFactory(entityManager);
factory.setQueryLookupStrategyKey(Key.CREATE_IF_NOT_FOUND);
UserCustomExtendedRepository repository = factory.getRepository(UserCustomExtendedRepository.class);
repository.customMethod(1);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> repository.customMethod(1));
}
@Test // DATAJPA-710, DATACMNS-542

View File

@@ -310,8 +310,9 @@ public class QuerydslJpaPredicateExecutorUnitTests {
assertThat(predicateExecutor.findOne(user.firstname.eq("batman"))).isNotPresent();
}
@Test(expected = IncorrectResultSizeDataAccessException.class) // DATAJPA-1115
@Test // DATAJPA-1115
public void findOneWithPredicateThrowsExceptionForNonUniqueResults() {
predicateExecutor.findOne(user.emailAddress.contains("com"));
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
.isThrownBy(() -> predicateExecutor.findOne(user.emailAddress.contains("com")));
}
}

View File

@@ -318,8 +318,9 @@ public class QuerydslJpaRepositoryTests {
assertThat(repository.findOne(user.firstname.eq("batman"))).isNotPresent();
}
@Test(expected = IncorrectResultSizeDataAccessException.class) // DATAJPA-1115
@Test // DATAJPA-1115
public void findOneWithPredicateThrowsExceptionForNonUniqueResults() {
repository.findOne(user.emailAddress.contains("com"));
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
.isThrownBy(() -> repository.findOne(user.emailAddress.contains("com")));
}
}

View File

@@ -94,7 +94,7 @@ public class QuerydslRepositorySupportTests {
}
@Test
public void deletesAllWithLastnameCorrectly() throws Exception {
public void deletesAllWithLastnameCorrectly() {
long updates = repository.deleteAllWithLastname("Matthews");
assertThat(updates).isEqualTo(1L);
@@ -107,11 +107,11 @@ public class QuerydslRepositorySupportTests {
assertThat(result.get(0)).isEqualTo(carter);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsUnsetEntityManager() throws Exception {
@Test
public void rejectsUnsetEntityManager() {
UserRepositoryImpl repositoryImpl = new UserRepositoryImpl();
repositoryImpl.validate();
assertThatIllegalArgumentException().isThrownBy(repositoryImpl::validate);
}
interface UserRepository {

View File

@@ -16,6 +16,7 @@
package org.springframework.data.jpa.repository.support;
import static java.util.Collections.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
@@ -114,10 +115,10 @@ public class SimpleJpaRepositoryUnitTests {
verify(countQuery, never()).getSingleResult();
}
@Test(expected = EmptyResultDataAccessException.class) // DATAJPA-177
@Test // DATAJPA-177
public void throwsExceptionIfEntityToDeleteDoesNotExist() {
repo.deleteById(4711);
assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> repo.deleteById(4711));
}
@Test // DATAJPA-689, DATAJPA-696

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.jpa.support;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
@@ -50,28 +51,28 @@ public class ClasspathScanningPersistenceUnitPostProcessorUnitTests {
@Mock MutablePersistenceUnitInfo pui;
String basePackage = getClass().getPackage().getName();
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullBasePackage() {
new ClasspathScanningPersistenceUnitPostProcessor(null);
assertThatIllegalArgumentException().isThrownBy(() -> new ClasspathScanningPersistenceUnitPostProcessor(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsEmptyBasePackage() {
new ClasspathScanningPersistenceUnitPostProcessor("");
assertThatIllegalArgumentException().isThrownBy(() -> new ClasspathScanningPersistenceUnitPostProcessor(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullMappingFileNamePattern() {
ClasspathScanningPersistenceUnitPostProcessor processor = new ClasspathScanningPersistenceUnitPostProcessor(
basePackage);
processor.setMappingFileNamePattern(null);
assertThatIllegalArgumentException().isThrownBy(() -> processor.setMappingFileNamePattern(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsEmptyMappingFileNamePattern() {
ClasspathScanningPersistenceUnitPostProcessor processor = new ClasspathScanningPersistenceUnitPostProcessor(
basePackage);
processor.setMappingFileNamePattern("");
assertThatIllegalArgumentException().isThrownBy(() -> processor.setMappingFileNamePattern(""));
}
@Test