Skip to content

Commit cfd8ef9

Browse files
committed
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.
1 parent 48597dc commit cfd8ef9

33 files changed

+195
-201
lines changed

src/test/java/org/springframework/data/jpa/convert/QueryByExamplePredicateBuilderUnitTests.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
*/
1616
package org.springframework.data.jpa.convert;
1717

18-
import static org.assertj.core.api.AssertionsForInterfaceTypes.*;
18+
import static org.assertj.core.api.Assertions.*;
1919
import static org.mockito.ArgumentMatchers.*;
2020
import static org.mockito.Mockito.*;
2121
import static org.springframework.data.domain.Example.*;
@@ -38,13 +38,12 @@
3838
import javax.persistence.metamodel.Type;
3939

4040
import org.junit.Before;
41-
import org.junit.Rule;
4241
import org.junit.Test;
43-
import org.junit.rules.ExpectedException;
4442
import org.junit.runner.RunWith;
4543
import org.mockito.ArgumentMatchers;
4644
import org.mockito.Mock;
4745
import org.mockito.junit.MockitoJUnitRunner;
46+
4847
import org.springframework.data.domain.Example;
4948
import org.springframework.data.domain.ExampleMatcher;
5049
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
@@ -84,8 +83,6 @@ public class QueryByExamplePredicateBuilderUnitTests {
8483
SingularAttribute<? super Skill, String> skillNameAttribute;
8584
SingularAttribute<? super Skill, Skill> skillNestedAttribute;
8685

87-
public @Rule ExpectedException exception = ExpectedException.none();
88-
8986
@Before
9087
public void setUp() {
9188

@@ -134,19 +131,22 @@ public void setUp() {
134131
doReturn(orPredicate).when(cb).or(ArgumentMatchers.any());
135132
}
136133

137-
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
134+
@Test // DATAJPA-218
138135
public void getPredicateShouldThrowExceptionOnNullRoot() {
139-
QueryByExamplePredicateBuilder.getPredicate(null, cb, of(new Person()), EscapeCharacter.DEFAULT);
136+
assertThatIllegalArgumentException().isThrownBy(
137+
() -> QueryByExamplePredicateBuilder.getPredicate(null, cb, of(new Person()), EscapeCharacter.DEFAULT));
140138
}
141139

142-
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
140+
@Test // DATAJPA-218
143141
public void getPredicateShouldThrowExceptionOnNullCriteriaBuilder() {
144-
QueryByExamplePredicateBuilder.getPredicate(root, null, of(new Person()), EscapeCharacter.DEFAULT);
142+
assertThatIllegalArgumentException().isThrownBy(
143+
() -> QueryByExamplePredicateBuilder.getPredicate(root, null, of(new Person()), EscapeCharacter.DEFAULT));
145144
}
146145

147-
@Test(expected = IllegalArgumentException.class) // DATAJPA-218
146+
@Test // DATAJPA-218
148147
public void getPredicateShouldThrowExceptionOnNullExample() {
149-
QueryByExamplePredicateBuilder.getPredicate(root, null, null, EscapeCharacter.DEFAULT);
148+
assertThatIllegalArgumentException()
149+
.isThrownBy(() -> QueryByExamplePredicateBuilder.getPredicate(root, null, null, EscapeCharacter.DEFAULT));
150150
}
151151

152152
@Test // DATAJPA-218

src/test/java/org/springframework/data/jpa/domain/JpaSortTests.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@
2525

2626
import org.junit.Test;
2727
import org.junit.runner.RunWith;
28+
2829
import org.springframework.data.domain.Sort.Order;
29-
import org.springframework.data.jpa.domain.JpaSort.JpaOrder;
30-
import org.springframework.data.jpa.domain.JpaSort.Path;
30+
import org.springframework.data.jpa.domain.JpaSort.*;
3131
import org.springframework.data.jpa.domain.sample.Address_;
3232
import org.springframework.data.jpa.domain.sample.MailMessage_;
3333
import org.springframework.data.jpa.domain.sample.MailSender_;
@@ -57,24 +57,24 @@ public class JpaSortTests {
5757
private static final @Nullable PluralAttribute<?, ?, ?> NULL_PLURAL_ATTRIBUTE = null;
5858
private static final PluralAttribute<?, ?, ?>[] EMPTY_PLURAL_ATTRIBUTES = new PluralAttribute<?, ?, ?>[0];
5959

60-
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
60+
@Test // DATAJPA-12
6161
public void rejectsNullAttribute() {
62-
JpaSort.of(NULL_ATTRIBUTE);
62+
assertThatIllegalArgumentException().isThrownBy(() -> of(NULL_ATTRIBUTE));
6363
}
6464

65-
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
65+
@Test // DATAJPA-12
6666
public void rejectsEmptyAttributes() {
67-
JpaSort.of(EMPTY_ATTRIBUTES);
67+
assertThatIllegalArgumentException().isThrownBy(() -> of(EMPTY_ATTRIBUTES));
6868
}
6969

70-
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
70+
@Test // DATAJPA-12
7171
public void rejectsNullPluralAttribute() {
72-
JpaSort.of(NULL_PLURAL_ATTRIBUTE);
72+
assertThatIllegalArgumentException().isThrownBy(() -> of(NULL_PLURAL_ATTRIBUTE));
7373
}
7474

75-
@Test(expected = IllegalArgumentException.class) // DATAJPA-12
75+
@Test // DATAJPA-12
7676
public void rejectsEmptyPluralAttributes() {
77-
JpaSort.of(EMPTY_PLURAL_ATTRIBUTES);
77+
assertThatIllegalArgumentException().isThrownBy(() -> of(EMPTY_PLURAL_ATTRIBUTES));
7878
}
7979

8080
@Test // DATAJPA-12
@@ -140,14 +140,14 @@ public void combiningSortByMultiplePathsWithDifferentSortUsingSimpleAnd() {
140140
.containsExactly(Order.asc("firstname"), Order.desc("mailSender.name"));
141141
}
142142

143-
@Test(expected = IllegalArgumentException.class) // DATAJPA-702
143+
@Test // DATAJPA-702
144144
public void rejectsNullAttributesForCombiningCriterias() {
145-
JpaSort.of(User_.firstname).and(DESC, (Attribute<?, ?>[]) null);
145+
assertThatIllegalArgumentException().isThrownBy(() -> of(User_.firstname).and(DESC, (Attribute<?, ?>[]) null));
146146
}
147147

148-
@Test(expected = IllegalArgumentException.class) // DATAJPA-702
148+
@Test // DATAJPA-702
149149
public void rejectsNullPathsForCombiningCriterias() {
150-
JpaSort.of(User_.firstname).and(DESC, (Path<?, ?>[]) null);
150+
assertThatIllegalArgumentException().isThrownBy(() -> of(User_.firstname).and(DESC, (Path<?, ?>[]) null));
151151
}
152152

153153
@Test // DATAJPA-702

src/test/java/org/springframework/data/jpa/domain/support/AuditingBeanFactoryPostProcessorUnitTests.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,10 @@ public void beanConfigurerAspectShouldBeConfiguredAfterPostProcessing() throws E
6666
assertThat(beanFactory.isBeanNameInUse(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME)).isTrue();
6767
}
6868

69-
@Test(expected = IllegalStateException.class) // DATAJPA-265
69+
@Test // DATAJPA-265
7070
public void rejectsConfigurationWithoutSpringConfigured() {
71-
processor.postProcessBeanFactory(new DefaultListableBeanFactory());
71+
assertThatIllegalStateException()
72+
.isThrownBy(() -> processor.postProcessBeanFactory(new DefaultListableBeanFactory()));
7273
}
7374

7475
@Test // DATAJPA-265

src/test/java/org/springframework/data/jpa/repository/JavaConfigUserRepositoryTests.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import javax.persistence.EntityManager;
2222
import javax.persistence.PersistenceContext;
2323

24+
import org.assertj.core.api.Assertions;
2425
import org.junit.Test;
2526
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
2627
import org.springframework.beans.factory.annotation.Autowired;
@@ -97,12 +98,14 @@ private NamedQueries namedQueries() throws IOException {
9798
}
9899
}
99100

100-
@Test(expected = NoSuchBeanDefinitionException.class) // DATAJPA-317
101+
@Test // DATAJPA-317
101102
public void doesNotPickUpJpaRepository() {
102103

103-
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(JpaRepositoryConfig.class);
104-
context.getBean("jpaRepository");
105-
context.close();
104+
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(JpaRepositoryConfig.class)) {
105+
Assertions.assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
106+
.isThrownBy(() -> context.getBean("jpaRepository"));
107+
context.close();
108+
}
106109
}
107110

108111
@Configuration

src/test/java/org/springframework/data/jpa/repository/RepositoryWithCompositeKeyTests.java

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,10 @@
2020
import java.util.Arrays;
2121
import java.util.List;
2222

23-
import org.junit.Rule;
2423
import org.junit.Test;
25-
import org.junit.rules.ExpectedException;
2624
import org.junit.runner.RunWith;
25+
2726
import org.springframework.beans.factory.annotation.Autowired;
28-
import org.springframework.dao.InvalidDataAccessApiUsageException;
2927
import org.springframework.data.domain.Page;
3028
import org.springframework.data.domain.PageRequest;
3129
import org.springframework.data.jpa.domain.sample.EmbeddedIdExampleDepartment;
@@ -55,8 +53,6 @@
5553
@Transactional
5654
public class RepositoryWithCompositeKeyTests {
5755

58-
@Rule public ExpectedException expectedException = ExpectedException.none();
59-
6056
@Autowired EmployeeRepositoryWithIdClass employeeRepositoryWithIdClass;
6157
@Autowired EmployeeRepositoryWithEmbeddedId employeeRepositoryWithEmbeddedId;
6258

@@ -116,13 +112,6 @@ public void shouldSupportSavingEntitiesWithCompositeKeyClassesWithEmbeddedIdsAnd
116112
@Test // DATAJPA-472, DATAJPA-912
117113
public void shouldSupportFindAllWithPageableAndEntityWithIdClass() throws Exception {
118114

119-
if (Package.getPackage("org.hibernate.cfg").getImplementationVersion().startsWith("4.1.")) {
120-
121-
// 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.
122-
expectedException.expect(InvalidDataAccessApiUsageException.class);
123-
expectedException.expectMessage("No supertype found");
124-
}
125-
126115
IdClassExampleDepartment dep = new IdClassExampleDepartment();
127116
dep.setName("TestDepartment");
128117
dep.setDepartmentId(-1);

src/test/java/org/springframework/data/jpa/repository/RepositoryWithIdClassKeyTests.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,9 @@
1919

2020
import java.util.Optional;
2121

22-
import org.junit.Rule;
2322
import org.junit.Test;
24-
import org.junit.rules.ExpectedException;
2523
import org.junit.runner.RunWith;
24+
2625
import org.springframework.beans.factory.annotation.Autowired;
2726
import org.springframework.context.annotation.Configuration;
2827
import org.springframework.context.annotation.ImportResource;
@@ -51,8 +50,6 @@
5150
@Transactional
5251
public class RepositoryWithIdClassKeyTests {
5352

54-
@Rule public ExpectedException expectedException = ExpectedException.none();
55-
5653
@Autowired private SiteRepository siteRepository;
5754

5855
@Autowired private ItemRepository itemRepository;

src/test/java/org/springframework/data/jpa/repository/UserRepositoryFinderTests.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,10 +271,12 @@ public void executesQueryWithProjectionContainingReferenceToPluralAttribute() {
271271
.isNotNull();
272272
}
273273

274-
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-1023, DATACMNS-959
274+
@Test // DATAJPA-1023, DATACMNS-959
275275
@Transactional(propagation = Propagation.NOT_SUPPORTED)
276276
public void rejectsStreamExecutionIfNoSurroundingTransactionActive() {
277-
userRepository.findAllByCustomQueryAndStream();
277+
278+
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
279+
.isThrownBy(() -> userRepository.findAllByCustomQueryAndStream());
278280
}
279281

280282
@Test // DATAJPA-1334

src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -363,12 +363,12 @@ public void testCascadesPersisting() {
363363
/**
364364
* Tests, that persisting a relationsship without cascade attributes throws a {@code DataAccessException}.
365365
*/
366-
@Test(expected = DataAccessException.class)
366+
@Test
367367
public void testPreventsCascadingRolePersisting() {
368368

369369
firstUser.addRole(new Role("USER"));
370370

371-
flushTestUsers();
371+
assertThatExceptionOfType(DataAccessException.class).isThrownBy(this::flushTestUsers);
372372
}
373373

374374
/**
@@ -447,11 +447,13 @@ public void returnsNullIfNoEntityFoundForSingleEntitySpecification() throws Exce
447447
assertThat(repository.findOne(userHasLastname("Beauford"))).isNotPresent();
448448
}
449449

450-
@Test(expected = IncorrectResultSizeDataAccessException.class)
450+
@Test
451451
public void throwsExceptionForUnderSpecifiedSingleEntitySpecification() {
452452

453453
flushTestUsers();
454-
repository.findOne(userHasFirstnameLike("e"));
454+
455+
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
456+
.isThrownBy(() -> repository.findOne(userHasFirstnameLike("e")));
455457
}
456458

457459
@Test
@@ -1698,9 +1700,10 @@ public void findAllByExampleWithEmptyProbe() {
16981700
assertThat(users).hasSize(4);
16991701
}
17001702

1701-
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
1703+
@Test // DATAJPA-218
17021704
public void findAllByNullExample() {
1703-
repository.findAll((Example<User>) null);
1705+
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
1706+
.isThrownBy(() -> repository.findAll((Example<User>) null));
17041707
}
17051708

17061709
@Test // DATAJPA-218
@@ -1790,7 +1793,7 @@ public void findAllByExampleWithEndingStringMatcher() {
17901793
assertThat(users).containsOnly(firstUser);
17911794
}
17921795

1793-
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
1796+
@Test // DATAJPA-218
17941797
public void findAllByExampleWithRegexStringMatcher() {
17951798

17961799
flushTestUsers();
@@ -1799,7 +1802,7 @@ public void findAllByExampleWithRegexStringMatcher() {
17991802
prototype.setFirstname("^Oliver$");
18001803

18011804
Example<User> example = Example.of(prototype, matching().withStringMatcher(StringMatcher.REGEX));
1802-
repository.findAll(example);
1805+
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> repository.findAll(example));
18031806
}
18041807

18051808
@Test // DATAJPA-218
@@ -1922,7 +1925,7 @@ public void findAllByExampleWithPageable() {
19221925
assertThat(users.getTotalElements()).isEqualTo(100L);
19231926
}
19241927

1925-
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
1928+
@Test // DATAJPA-218
19261929
public void findAllByExampleShouldNotAllowCycles() {
19271930

19281931
flushTestUsers();
@@ -1935,10 +1938,11 @@ public void findAllByExampleShouldNotAllowCycles() {
19351938
Example<User> example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")
19361939
.withStringMatcher(StringMatcher.STARTING).withIgnoreCase());
19371940

1938-
repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age")));
1941+
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
1942+
.isThrownBy(() -> repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age"))));
19391943
}
19401944

1941-
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218
1945+
@Test // DATAJPA-218
19421946
public void findAllByExampleShouldNotAllowCyclesOverSeveralInstances() {
19431947

19441948
flushTestUsers();
@@ -1955,7 +1959,8 @@ public void findAllByExampleShouldNotAllowCyclesOverSeveralInstances() {
19551959
Example<User> example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")
19561960
.withStringMatcher(StringMatcher.STARTING).withIgnoreCase());
19571961

1958-
repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age")));
1962+
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
1963+
.isThrownBy(() -> repository.findAll(example, PageRequest.of(0, 10, Sort.by(DESC, "age"))));
19591964
}
19601965

19611966
@Test // DATAJPA-218

src/test/java/org/springframework/data/jpa/repository/config/AuditingBeanDefinitionParserTests.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,13 @@ public void wiresDateTimeProviderIfConfigured() {
6262
assertThat(bean).isNotNull();
6363
}
6464

65-
@Test(expected = BeanDefinitionParsingException.class) // DATAJPA-367
65+
@Test // DATAJPA-367
6666
public void shouldThrowBeanDefinitionParsingExceptionIfClassFromSpringAspectsJarCannotBeFound() {
6767

6868
ShadowingClassLoader scl = new ShadowingClassLoader(getClass().getClassLoader());
6969
scl.excludeClass(AuditingBeanDefinitionParser.AUDITING_ENTITY_LISTENER_CLASS_NAME);
70-
loadFactoryFrom("auditing/auditing-namespace-context.xml", scl);
70+
assertThatExceptionOfType(BeanDefinitionParsingException.class)
71+
.isThrownBy(() -> loadFactoryFrom("auditing/auditing-namespace-context.xml", scl));
7172
}
7273

7374
private void assertSetDatesIsSetTo(String configFile, String value) {

src/test/java/org/springframework/data/jpa/repository/config/CustomRepositoryFactoryConfigTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ public void setup() {
5353
transactionManager.resetCount();
5454
}
5555

56-
@Test(expected = UnsupportedOperationException.class)
56+
@Test
5757
public void testCustomFactoryUsed() {
58-
userRepository.customMethod(1);
58+
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> userRepository.customMethod(1));
5959
}
6060

6161
@Test

0 commit comments

Comments
 (0)