Migrate from ExpectedException rule to AssertJ

Replace ExpectedException JUnit rules with AssertJ exception
assertions.

Closes gh-14336
This commit is contained in:
Phillip Webb
2018-10-01 11:18:16 -07:00
parent 42cb0effc4
commit d76bba5e6f
273 changed files with 2752 additions and 3624 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.context.filtersample.ExampleConfiguration;
@@ -33,6 +31,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link AutoConfigurationExcludeFilter}.
@@ -43,9 +42,6 @@ public class AutoConfigurationExcludeFilterTests {
private static final Class<?> FILTERED = ExampleFilteredAutoConfiguration.class;
@Rule
public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigApplicationContext context;
@After
@@ -60,8 +56,8 @@ public class AutoConfigurationExcludeFilterTests {
this.context = new AnnotationConfigApplicationContext(Config.class);
assertThat(this.context.getBeansOfType(String.class)).hasSize(1);
assertThat(this.context.getBean(String.class)).isEqualTo("test");
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(FILTERED);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(FILTERED));
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,9 +23,7 @@ import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.BeansException;
@@ -43,6 +41,7 @@ import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link AutoConfigurationImportSelector}
@@ -61,9 +60,6 @@ public class AutoConfigurationImportSelectorTests {
private List<AutoConfigurationImportFilter> filters = new ArrayList<>();
@Rule
public ExpectedException expected = ExpectedException.none();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
@@ -173,14 +169,14 @@ public class AutoConfigurationImportSelectorTests {
@Test
public void nonAutoConfigurationClassExclusionsShouldThrowException() {
this.expected.expect(IllegalStateException.class);
selectImports(EnableAutoConfigurationWithFaultyClassExclude.class);
assertThatIllegalStateException().isThrownBy(
() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class));
}
@Test
public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() {
this.expected.expect(IllegalStateException.class);
selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class);
assertThatIllegalStateException().isThrownBy(() -> selectImports(
EnableAutoConfigurationWithFaultyClassNameExclude.class));
}
@Test
@@ -188,8 +184,8 @@ public class AutoConfigurationImportSelectorTests {
this.environment.setProperty("spring.autoconfigure.exclude",
"org.springframework.boot.autoconfigure."
+ "AutoConfigurationImportSelectorTests.TestConfiguration");
this.expected.expect(IllegalStateException.class);
selectImports(BasicEnableAutoConfiguration.class);
assertThatIllegalStateException()
.isThrownBy(() -> selectImports(BasicEnableAutoConfiguration.class));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.boot.autoconfigure;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages.Registrar;
import org.springframework.boot.autoconfigure.packagestest.one.FirstConfiguration;
@@ -30,6 +28,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link AutoConfigurationPackages}.
@@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("resource")
public class AutoConfigurationPackagesTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void setAndGet() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
@@ -55,10 +51,10 @@ public class AutoConfigurationPackagesTests {
public void getWithoutSet() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
EmptyConfig.class);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"Unable to retrieve @EnableAutoConfiguration base packages");
AutoConfigurationPackages.get(context.getBeanFactory());
assertThatIllegalStateException()
.isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory()))
.withMessageContaining(
"Unable to retrieve @EnableAutoConfiguration base packages");
}
@Test

View File

@@ -24,9 +24,7 @@ import java.util.Properties;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.Ordered;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
@@ -36,6 +34,7 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.Mockito.mock;
/**
@@ -74,9 +73,6 @@ public class AutoConfigurationSorterTests {
private static final String W2 = AutoConfigureW2.class.getName();
@Rule
public ExpectedException thrown = ExpectedException.none();
private AutoConfigurationSorter sorter;
private AutoConfigurationMetadata autoConfigurationMetadata = mock(
@@ -144,9 +140,10 @@ public class AutoConfigurationSorterTests {
public void byAutoConfigureAfterWithCycle() {
this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(),
this.autoConfigurationMetadata);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("AutoConfigure cycle detected");
this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D));
assertThatIllegalStateException()
.isThrownBy(
() -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D)))
.withMessageContaining("AutoConfigure cycle detected");
}
@Test
@@ -176,9 +173,9 @@ public class AutoConfigurationSorterTests {
this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D);
this.sorter = new AutoConfigurationSorter(readerFactory,
this.autoConfigurationMetadata);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("AutoConfigure cycle detected");
this.sorter.getInPriorityOrder(Arrays.asList(D, B));
assertThatIllegalStateException()
.isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B)))
.withMessageContaining("AutoConfigure cycle detected");
}
private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames)

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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 javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -44,6 +42,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.jmx.export.MBeanExporter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.fail;
/**
@@ -58,9 +57,6 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
private static final String DEFAULT_JMX_NAME = "org.springframework.boot:type=Admin,name=SpringApplication";
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
@@ -70,10 +66,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
@Test
public void notRegisteredByDefault() {
this.contextRunner.run((context) -> {
this.thrown.expect(InstanceNotFoundException.class);
this.server.getObjectInstance(createDefaultObjectName());
});
this.contextRunner.run((context) -> assertThatExceptionOfType(
InstanceNotFoundException.class).isThrownBy(
() -> this.server.getObjectInstance(createDefaultObjectName())));
}
@Test
@@ -99,9 +94,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
catch (InstanceNotFoundException ex) {
fail("Admin MBean should have been exposed with custom name");
}
this.thrown.expect(InstanceNotFoundException.class); // Should not be
// exposed
this.server.getObjectInstance(createDefaultObjectName());
assertThatExceptionOfType(InstanceNotFoundException.class)
.isThrownBy(() -> this.server
.getObjectInstance(createDefaultObjectName()));
});
}
@@ -139,9 +134,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
.run("--" + ENABLE_ADMIN_PROP)) {
BeanFactoryUtils.beanOfType(parent.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class);
this.thrown.expect(NoSuchBeanDefinitionException.class);
BeanFactoryUtils.beanOfType(child.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> BeanFactoryUtils.beanOfType(child.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class));
}
}

View File

@@ -28,9 +28,7 @@ import com.rabbitmq.client.Connection;
import com.rabbitmq.client.SslContextFactory;
import com.rabbitmq.client.TrustEverythingTrustManager;
import org.aopalliance.aop.Advice;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpAdmin;
@@ -69,6 +67,7 @@ import org.springframework.retry.support.RetryTemplate;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -85,9 +84,6 @@ import static org.mockito.Mockito.verify;
*/
public class RabbitAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class));
@@ -413,15 +409,14 @@ public class RabbitAutoConfigurationTests {
@Test
public void testStaticQueues() {
// There should NOT be an AmqpAdmin bean when dynamic is switch to false
this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.dynamic:false").run((context) -> {
// There should NOT be an AmqpAdmin bean when dynamic is switch to
// false
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.thrown.expectMessage("No qualifying bean of type");
this.thrown.expectMessage(AmqpAdmin.class.getName());
context.getBean(AmqpAdmin.class);
});
.withPropertyValues("spring.rabbitmq.dynamic:false")
.run((context) -> assertThatExceptionOfType(
NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean(AmqpAdmin.class))
.withMessageContaining("No qualifying bean of type '"
+ AmqpAdmin.class.getName() + "'"));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,9 +22,7 @@ import java.util.Collections;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
@@ -62,6 +60,7 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link BatchAutoConfiguration}.
@@ -73,9 +72,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class BatchAutoConfigurationTests {
@Rule
public ExpectedException expected = ExpectedException.none();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class,
TransactionAutoConfiguration.class));
@@ -176,9 +172,9 @@ public class BatchAutoConfigurationTests {
assertThat(
context.getBean(BatchProperties.class).getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.NEVER);
this.expected.expect(BadSqlGrammarException.class);
new JdbcTemplate(context.getBean(DataSource.class))
.queryForList("select * from BATCH_JOB_EXECUTION");
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(
() -> new JdbcTemplate(context.getBean(DataSource.class))
.queryForList("select * from BATCH_JOB_EXECUTION"));
});
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,11 +20,10 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Consumer;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
@@ -36,8 +35,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link ConditionalOnProperty}.
@@ -49,9 +47,6 @@ import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
*/
public class ConditionalOnPropertyTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ConfigurableApplicationContext context;
private ConfigurableEnvironment environment = new StandardEnvironment();
@@ -205,18 +200,22 @@ public class ConditionalOnPropertyTests {
@Test
public void nameOrValueMustBeSpecified() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectCause(hasMessage(containsString("The name or "
+ "value attribute of @ConditionalOnProperty must be specified")));
load(NoNameOrValueAttribute.class, "some.property");
assertThatIllegalStateException()
.isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property"))
.satisfies(causeMessageContaining(
"The name or value attribute of @ConditionalOnProperty must be specified"));
}
@Test
public void nameAndValueMustNotBeSpecified() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectCause(hasMessage(containsString("The name and "
+ "value attributes of @ConditionalOnProperty are exclusive")));
load(NameAndValueAttribute.class, "some.property");
assertThatIllegalStateException()
.isThrownBy(() -> load(NameAndValueAttribute.class, "some.property"))
.satisfies(causeMessageContaining(
"The name and value attributes of @ConditionalOnProperty are exclusive"));
}
private <T extends Exception> Consumer<T> causeMessageContaining(String message) {
return (ex) -> assertThat(ex.getCause()).hasMessageContaining(message);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,7 @@
package org.springframework.boot.autoconfigure.condition;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -27,7 +25,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.isA;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link ConditionalOnSingleCandidate}.
@@ -37,9 +35,6 @@ import static org.hamcrest.CoreMatchers.isA;
*/
public class ConditionalOnSingleCandidateTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@After
@@ -126,20 +121,20 @@ public class ConditionalOnSingleCandidateTests {
@Test
public void invalidAnnotationTwoTypes() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectCause(isA(IllegalArgumentException.class));
this.thrown.expectMessage(
OnBeanSingleCandidateTwoTypesConfiguration.class.getName());
load(OnBeanSingleCandidateTwoTypesConfiguration.class);
assertThatIllegalStateException()
.isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.class))
.withCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining(
OnBeanSingleCandidateTwoTypesConfiguration.class.getName());
}
@Test
public void invalidAnnotationNoType() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectCause(isA(IllegalArgumentException.class));
this.thrown
.expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName());
load(OnBeanSingleCandidateNoTypeConfiguration.class);
assertThatIllegalStateException()
.isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.class))
.withCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining(
OnBeanSingleCandidateNoTypeConfiguration.class.getName());
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@@ -16,9 +16,7 @@
package org.springframework.boot.autoconfigure.condition;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -27,6 +25,8 @@ import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link SpringBootCondition}.
*
@@ -35,23 +35,22 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
@SuppressWarnings("resource")
public class SpringBootConditionTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void sensibleClassException() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"Error processing condition on " + ErrorOnClass.class.getName());
new AnnotationConfigApplicationContext(ErrorOnClass.class);
assertThatIllegalStateException()
.isThrownBy(
() -> new AnnotationConfigApplicationContext(ErrorOnClass.class))
.withMessageContaining(
"Error processing condition on " + ErrorOnClass.class.getName());
}
@Test
public void sensibleMethodException() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Error processing condition on "
+ ErrorOnMethod.class.getName() + ".myBean");
new AnnotationConfigApplicationContext(ErrorOnMethod.class);
assertThatIllegalStateException()
.isThrownBy(
() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class))
.withMessageContaining("Error processing condition on "
+ ErrorOnMethod.class.getName() + ".myBean");
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.util.Collection;
import java.util.Collections;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -30,6 +28,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationConfigurationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link EntityScanPackages}.
@@ -40,9 +40,6 @@ public class EntityScanPackagesTests {
private AnnotationConfigApplicationContext context;
@Rule
public ExpectedException thrown = ExpectedException.none();
@After
public void cleanup() {
if (this.context != null) {
@@ -71,33 +68,36 @@ public class EntityScanPackagesTests {
@Test
public void registerFromArrayWhenRegistryIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Registry must not be null");
EntityScanPackages.register(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> EntityScanPackages.register(null))
.withMessageContaining("Registry must not be null");
}
@Test
public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() {
this.context = new AnnotationConfigApplicationContext();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("PackageNames must not be null");
EntityScanPackages.register(this.context, (String[]) null);
assertThatIllegalArgumentException()
.isThrownBy(
() -> EntityScanPackages.register(this.context, (String[]) null))
.withMessageContaining("PackageNames must not be null");
}
@Test
public void registerFromCollectionWhenRegistryIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Registry must not be null");
EntityScanPackages.register(null, Collections.emptyList());
assertThatIllegalArgumentException()
.isThrownBy(
() -> EntityScanPackages.register(null, Collections.emptyList()))
.withMessageContaining("Registry must not be null");
}
@Test
public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() {
this.context = new AnnotationConfigApplicationContext();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("PackageNames must not be null");
EntityScanPackages.register(this.context, (Collection<String>) null);
assertThatIllegalArgumentException()
.isThrownBy(() -> EntityScanPackages.register(this.context,
(Collection<String>) null))
.withMessageContaining("PackageNames must not be null");
}
@Test
@@ -128,9 +128,9 @@ public class EntityScanPackagesTests {
@Test
public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() {
this.thrown.expect(AnnotationConfigurationException.class);
this.context = new AnnotationConfigApplicationContext(
EntityScanValueAndBasePackagesConfig.class);
assertThatExceptionOfType(AnnotationConfigurationException.class)
.isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(
EntityScanValueAndBasePackagesConfig.class));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.util.Set;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.domain.scan.a.EmbeddableA;
import org.springframework.boot.autoconfigure.domain.scan.a.EntityA;
@@ -35,6 +33,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link EntityScanner}.
@@ -43,14 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class EntityScannerTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenContextIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Context must not be null");
new EntityScanner(null);
assertThatIllegalArgumentException().isThrownBy(() -> new EntityScanner(null))
.withMessageContaining("Context must not be null");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.boot.autoconfigure.h2;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.test.util.TestPropertyValues;
@@ -29,6 +27,7 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link H2ConsoleAutoConfiguration}
@@ -41,9 +40,6 @@ public class H2ConsoleAutoConfigurationTests {
private AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setupContext() {
this.context.setServletContext(new MockServletContext());
@@ -79,13 +75,13 @@ public class H2ConsoleAutoConfigurationTests {
@Test
public void customPathMustBeginWithASlash() {
this.thrown.expect(BeanCreationException.class);
this.thrown.expectMessage("Failed to bind properties under 'spring.h2.console'");
this.context.register(H2ConsoleAutoConfiguration.class);
TestPropertyValues
.of("spring.h2.console.enabled:true", "spring.h2.console.path:custom")
.applyTo(this.context);
this.context.refresh();
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(this.context::refresh).withMessageContaining(
"Failed to bind properties under 'spring.h2.console'");
}
@Test

View File

@@ -16,9 +16,9 @@
package org.springframework.boot.autoconfigure.h2;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link H2ConsoleProperties}.
@@ -27,33 +27,29 @@ import org.junit.rules.ExpectedException;
*/
public class H2ConsolePropertiesTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private H2ConsoleProperties properties;
@Test
public void pathMustNotBeEmpty() {
this.properties = new H2ConsoleProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("");
assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath(""))
.withMessageContaining("Path must have length greater than 1");
}
@Test
public void pathMustHaveLengthGreaterThanOne() {
this.properties = new H2ConsoleProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("/");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.properties.setPath("/"))
.withMessageContaining("Path must have length greater than 1");
}
@Test
public void customPathMustBeginWithASlash() {
this.properties = new H2ConsoleProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must start with '/'");
this.properties.setPath("custom");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.properties.setPath("custom"))
.withMessageContaining("Path must start with '/'");
}
}

View File

@@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.integration;
import javax.management.MBeanServer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@@ -47,6 +45,7 @@ import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jmx.export.MBeanExporter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
@@ -58,9 +57,6 @@ import static org.mockito.Mockito.mock;
*/
public class IntegrationAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class,
IntegrationAutoConfiguration.class));
@@ -189,8 +185,8 @@ public class IntegrationAutoConfigurationTests {
assertThat(properties.getJdbc().getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.NEVER);
JdbcOperations jdbc = context.getBean(JdbcOperations.class);
this.thrown.expect(BadSqlGrammarException.class);
jdbc.queryForList("select * from INT_MESSAGE");
assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(
() -> jdbc.queryForList("select * from INT_MESSAGE"));
});
}

View File

@@ -16,14 +16,13 @@
package org.springframework.boot.autoconfigure.jdbc;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.context.FilteredClassLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link DataSourceProperties}.
@@ -34,9 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class DataSourcePropertiesTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void determineDriver() {
DataSourceProperties properties = new DataSourceProperties();
@@ -71,9 +67,10 @@ public class DataSourcePropertiesTests {
properties.setBeanClassLoader(
new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb"));
properties.afterPropertiesSet();
this.thrown.expect(DataSourceProperties.DataSourceBeanCreationException.class);
this.thrown.expectMessage("Failed to determine suitable jdbc url");
properties.determineUrl();
assertThatExceptionOfType(
DataSourceProperties.DataSourceBeanCreationException.class)
.isThrownBy(properties::determineUrl)
.withMessageContaining("Failed to determine suitable jdbc url");
}
@Test

View File

@@ -38,9 +38,7 @@ import org.jooq.TransactionListenerProvider;
import org.jooq.TransactionalRunnable;
import org.jooq.VisitListener;
import org.jooq.VisitListenerProvider;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -69,9 +67,6 @@ public class JooqAutoConfigurationTests {
.withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class))
.withPropertyValues("spring.datasource.name:jooqtest");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void noDataSource() {
this.contextRunner

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@@ -42,7 +42,7 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.fail;
/**
@@ -155,9 +155,9 @@ public class ConditionEvaluationReportLoggingListenerTests {
@Test
public void listenerSupportsOnlyInfoAndDebug() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
assertThatIllegalArgumentException().isThrownBy(
() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE))
.withMessage("LogLevel must be INFO or DEBUG");
.withMessageContaining("LogLevel must be INFO or DEBUG");
}
@Test

View File

@@ -24,14 +24,13 @@ import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.connection.ClusterSettings;
import com.mongodb.reactivestreams.client.MongoClient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.env.Environment;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -44,9 +43,6 @@ import static org.mockito.Mockito.verify;
*/
public class ReactiveMongoClientFactoryTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private MockEnvironment environment = new MockEnvironment();
@Test
@@ -126,10 +122,9 @@ public class ReactiveMongoClientFactoryTests {
properties.setUri("mongodb://127.0.0.1:1234/mydb");
properties.setUsername("user");
properties.setPassword("secret".toCharArray());
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Invalid mongo configuration, "
+ "either uri or host/port/credentials must be specified");
createMongoClient(properties);
assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties))
.withMessageContaining("Invalid mongo configuration, "
+ "either uri or host/port/credentials must be specified");
}
@Test
@@ -138,10 +133,9 @@ public class ReactiveMongoClientFactoryTests {
properties.setUri("mongodb://127.0.0.1:1234/mydb");
properties.setHost("localhost");
properties.setPort(4567);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Invalid mongo configuration, "
+ "either uri or host/port/credentials must be specified");
createMongoClient(properties);
assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties))
.withMessageContaining("Invalid mongo configuration, "
+ "either uri or host/port/credentials must be specified");
}
@Test

View File

@@ -23,9 +23,7 @@ import java.util.Map;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.LoginClientRegistration;
@@ -40,6 +38,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link OAuth2ClientPropertiesRegistrationAdapter}.
@@ -59,9 +58,6 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests {
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void getClientRegistrationsWhenUsingDefinedProviderShouldAdapt() {
OAuth2ClientProperties properties = new OAuth2ClientProperties();
@@ -195,9 +191,10 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests {
OAuth2ClientProperties.LoginClientRegistration login = new OAuth2ClientProperties.LoginClientRegistration();
login.setProvider("missing");
properties.getRegistration().getLogin().put("registration", login);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unknown provider ID 'missing'");
OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties);
assertThatIllegalStateException()
.isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter
.getClientRegistrations(properties))
.withMessageContaining("Unknown provider ID 'missing'");
}
@Test
@@ -276,10 +273,11 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests {
OAuth2ClientProperties properties = new OAuth2ClientProperties();
OAuth2ClientProperties.LoginClientRegistration login = new OAuth2ClientProperties.LoginClientRegistration();
properties.getRegistration().getLogin().put("missing", login);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"Provider ID must be specified for client registration 'missing'");
OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties);
assertThatIllegalStateException()
.isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter
.getClientRegistrations(properties))
.withMessageContaining(
"Provider ID must be specified for client registration 'missing'");
}
@Test

View File

@@ -16,13 +16,13 @@
package org.springframework.boot.autoconfigure.security.oauth2.client;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.AuthorizationCodeClientRegistration;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.LoginClientRegistration;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link OAuth2ClientProperties}.
*
@@ -33,18 +33,14 @@ public class OAuth2ClientPropertiesTests {
private OAuth2ClientProperties properties = new OAuth2ClientProperties();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void clientIdAbsentForLoginClientsThrowsException() {
LoginClientRegistration registration = new LoginClientRegistration();
registration.setClientSecret("secret");
registration.setProvider("google");
this.properties.getRegistration().getLogin().put("foo", registration);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Client id must not be empty.");
this.properties.validate();
assertThatIllegalStateException().isThrownBy(this.properties::validate)
.withMessageContaining("Client id must not be empty.");
}
@Test
@@ -62,9 +58,8 @@ public class OAuth2ClientPropertiesTests {
registration.setClientSecret("secret");
registration.setProvider("google");
this.properties.getRegistration().getAuthorizationCode().put("foo", registration);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Client id must not be empty.");
this.properties.validate();
assertThatIllegalStateException().isThrownBy(this.properties::validate)
.withMessageContaining("Client id must not be empty.");
}
@Test

View File

@@ -17,9 +17,7 @@
package org.springframework.boot.autoconfigure.security.reactive;
import org.assertj.core.api.AssertDelegateTarget;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.security.StaticResourceLocation;
import org.springframework.boot.autoconfigure.web.ServerProperties;
@@ -35,6 +33,7 @@ import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.HttpWebHandlerAdapter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -46,9 +45,6 @@ public class StaticResourceRequestTests {
private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void atCommonLocationsShouldMatchCommonLocations() {
ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations();
@@ -78,16 +74,17 @@ public class StaticResourceRequestTests {
@Test
public void atLocationsFromSetWhenSetIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Locations must not be null");
this.resourceRequest.at(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.resourceRequest.at(null))
.withMessageContaining("Locations must not be null");
}
@Test
public void excludeFromSetWhenSetIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Locations must not be null");
this.resourceRequest.atCommonLocations().excluding(null);
assertThatIllegalArgumentException()
.isThrownBy(
() -> this.resourceRequest.atCommonLocations().excluding(null))
.withMessageContaining("Locations must not be null");
}
private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher) {

View File

@@ -19,9 +19,7 @@ package org.springframework.boot.autoconfigure.security.servlet;
import javax.servlet.http.HttpServletRequest;
import org.assertj.core.api.AssertDelegateTarget;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.security.StaticResourceLocation;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
@@ -32,6 +30,7 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link StaticResourceRequest}.
@@ -43,9 +42,6 @@ public class StaticResourceRequestTests {
private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void atCommonLocationsShouldMatchCommonLocations() {
RequestMatcher matcher = this.resourceRequest.atCommonLocations();
@@ -81,16 +77,17 @@ public class StaticResourceRequestTests {
@Test
public void atLocationsFromSetWhenSetIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Locations must not be null");
this.resourceRequest.at(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.resourceRequest.at(null))
.withMessageContaining("Locations must not be null");
}
@Test
public void excludeFromSetWhenSetIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Locations must not be null");
this.resourceRequest.atCommonLocations().excluding(null);
assertThatIllegalArgumentException()
.isThrownBy(
() -> this.resourceRequest.atCommonLocations().excluding(null))
.withMessageContaining("Locations must not be null");
}
private RequestMatcherAssert assertMatcher(RequestMatcher matcher) {

View File

@@ -16,9 +16,7 @@
package org.springframework.boot.autoconfigure.session;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@@ -39,6 +37,7 @@ import org.springframework.session.hazelcast.HazelcastSessionRepository;
import org.springframework.session.jdbc.JdbcOperationsSessionRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* JDBC specific tests for {@link SessionAutoConfiguration}.
@@ -49,9 +48,6 @@ import static org.assertj.core.api.Assertions.assertThat;
public class SessionAutoConfigurationJdbcTests
extends AbstractSessionAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
@@ -109,9 +105,9 @@ public class SessionAutoConfigurationJdbcTests
assertThat(context.getBean(JdbcSessionProperties.class)
.getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.NEVER);
this.thrown.expect(BadSqlGrammarException.class);
context.getBean(JdbcOperations.class)
.queryForList("select * from SPRING_SESSION");
assertThatExceptionOfType(BadSqlGrammarException.class)
.isThrownBy(() -> context.getBean(JdbcOperations.class)
.queryForList("select * from SPRING_SESSION"));
});
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.util.Collection;
import java.util.Collections;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -31,6 +29,7 @@ import org.springframework.core.io.ResourceLoader;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -43,9 +42,6 @@ import static org.mockito.Mockito.verify;
*/
public class TemplateAvailabilityProvidersTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private TemplateAvailabilityProviders providers;
@Mock
@@ -69,9 +65,9 @@ public class TemplateAvailabilityProvidersTests {
@Test
public void createWhenApplicationContextIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ClassLoader must not be null");
new TemplateAvailabilityProviders((ApplicationContext) null);
assertThatIllegalArgumentException().isThrownBy(
() -> new TemplateAvailabilityProviders((ApplicationContext) null))
.withMessageContaining("ClassLoader must not be null");
}
@Test
@@ -86,9 +82,9 @@ public class TemplateAvailabilityProvidersTests {
@Test
public void createWhenClassLoaderIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ClassLoader must not be null");
new TemplateAvailabilityProviders((ClassLoader) null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null))
.withMessageContaining("ClassLoader must not be null");
}
@Test
@@ -100,10 +96,10 @@ public class TemplateAvailabilityProvidersTests {
@Test
public void createWhenProvidersIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Providers must not be null");
new TemplateAvailabilityProviders(
(Collection<TemplateAvailabilityProvider>) null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new TemplateAvailabilityProviders(
(Collection<TemplateAvailabilityProvider>) null))
.withMessageContaining("Providers must not be null");
}
@Test
@@ -115,40 +111,41 @@ public class TemplateAvailabilityProvidersTests {
@Test
public void getProviderWhenApplicationContextIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ApplicationContext must not be null");
this.providers.getProvider(this.view, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.providers.getProvider(this.view, null))
.withMessageContaining("ApplicationContext must not be null");
}
@Test
public void getProviderWhenViewIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("View must not be null");
this.providers.getProvider(null, this.environment, this.classLoader,
this.resourceLoader);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.providers.getProvider(null, this.environment,
this.classLoader, this.resourceLoader))
.withMessageContaining("View must not be null");
}
@Test
public void getProviderWhenEnvironmentIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Environment must not be null");
this.providers.getProvider(this.view, null, this.classLoader,
this.resourceLoader);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.providers.getProvider(this.view, null,
this.classLoader, this.resourceLoader))
.withMessageContaining("Environment must not be null");
}
@Test
public void getProviderWhenClassLoaderIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ClassLoader must not be null");
this.providers.getProvider(this.view, this.environment, null,
this.resourceLoader);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.providers.getProvider(this.view, this.environment,
null, this.resourceLoader))
.withMessageContaining("ClassLoader must not be null");
}
@Test
public void getProviderWhenResourceLoaderIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceLoader must not be null");
this.providers.getProvider(this.view, this.environment, this.classLoader, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.providers.getProvider(this.view, this.environment,
this.classLoader, null))
.withMessageContaining("ResourceLoader must not be null");
}
@Test

View File

@@ -36,9 +36,7 @@ import com.atomikos.icatch.jta.UserTransactionManager;
import com.atomikos.jms.AtomikosConnectionFactoryBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
@@ -60,6 +58,7 @@ import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -73,9 +72,6 @@ import static org.mockito.Mockito.mock;
*/
public class JtaAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigApplicationContext context;
@Before
@@ -94,8 +90,8 @@ public class JtaAutoConfigurationTests {
public void customPlatformTransactionManager() {
this.context = new AnnotationConfigApplicationContext(
CustomTransactionManagerConfig.class, JtaAutoConfiguration.class);
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(JtaTransactionManager.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(JtaTransactionManager.class));
}
@Test

View File

@@ -25,9 +25,7 @@ import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
@@ -44,6 +42,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess
import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
@@ -54,9 +53,6 @@ import static org.mockito.Mockito.mock;
*/
public class ValidationAutoConfigurationTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigApplicationContext context;
@After
@@ -161,8 +157,8 @@ public class ValidationAutoConfigurationTests {
assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1);
SampleService service = this.context.getBean(SampleService.class);
service.doSomething("Valid");
this.thrown.expect(ConstraintViolationException.class);
service.doSomething("KO");
assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> service.doSomething("KO"));
}
@Test
@@ -172,8 +168,8 @@ public class ValidationAutoConfigurationTests {
DefaultAnotherSampleService service = this.context
.getBean(DefaultAnotherSampleService.class);
service.doSomething(42);
this.thrown.expect(ConstraintViolationException.class);
service.doSomething(2);
assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> service.doSomething(2));
}
@Test
@@ -185,8 +181,8 @@ public class ValidationAutoConfigurationTests {
.isEmpty();
AnotherSampleService service = this.context.getBean(AnotherSampleService.class);
service.doSomething(42);
this.thrown.expect(ConstraintViolationException.class);
service.doSomething(2);
assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> service.doSomething(2));
}
@Test

View File

@@ -292,7 +292,7 @@ public class ServerPropertiesTests {
jetty.start();
org.eclipse.jetty.server.Connector connector = jetty.getServer()
.getConnectors()[0];
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final AtomicReference<Throwable> failure = new AtomicReference<>();
connector.addBean(new HttpChannel.Listener() {
@Override
@@ -318,14 +318,14 @@ public class ServerPropertiesTests {
});
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
StringBuilder data = new StringBuilder();
for (int i = 0; i < 250000; i++) {
data.append("a");
}
body.add("data", data.toString());
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(
body, headers);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body,
headers);
template.postForEntity(
URI.create("http://localhost:" + jetty.getPort() + "/form"), entity,
Void.class);

View File

@@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.web.reactive.error;
import javax.validation.Valid;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import reactor.core.publisher.Mono;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@@ -43,7 +41,7 @@ import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Integration tests for {@link DefaultErrorWebExceptionHandler}
@@ -63,9 +61,6 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
"server.port=0")
.withUserConfiguration(Application.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void jsonError() {
this.contextRunner.run((context) -> {
@@ -241,9 +236,11 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
this.thrown.expectCause(instanceOf(IllegalStateException.class));
this.thrown.expectMessage("already committed!");
client.get().uri("/commit").exchange().expectStatus();
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(
() -> client.get().uri("/commit").exchange().expectStatus())
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("already committed!");
});
}

View File

@@ -18,13 +18,13 @@ package org.springframework.boot.autoconfigure.web.servlet;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.web.servlet.DispatcherServlet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DispatcherServletRegistrationBean}.
@@ -33,14 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class DispatcherServletRegistrationBeanTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void createWhenPathIsNullThrowsException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must not be null");
new DispatcherServletRegistrationBean(new DispatcherServlet(), null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DispatcherServletRegistrationBean(
new DispatcherServlet(), null))
.withMessageContaining("Path must not be null");
}
@Test
@@ -61,16 +59,16 @@ public class DispatcherServletRegistrationBeanTests {
public void setUrlMappingsCannotBeCalled() {
DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(
new DispatcherServlet(), "/test");
this.thrown.expect(UnsupportedOperationException.class);
bean.setUrlMappings(Collections.emptyList());
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> bean.setUrlMappings(Collections.emptyList()));
}
@Test
public void addUrlMappingsCannotBeCalled() {
DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(
new DispatcherServlet(), "/test");
this.thrown.expect(UnsupportedOperationException.class);
bean.addUrlMappings("/test");
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> bean.addUrlMappings("/test"));
}
}

View File

@@ -25,9 +25,7 @@ import java.util.Map;
import javax.servlet.Filter;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.test.util.TestPropertyValues;
@@ -44,6 +42,7 @@ import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link HttpEncodingAutoConfiguration}
@@ -52,9 +51,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class HttpEncodingAutoConfigurationTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private AnnotationConfigWebApplicationContext context;
@After
@@ -75,8 +71,8 @@ public class HttpEncodingAutoConfigurationTests {
@Test
public void disableConfiguration() {
load(EmptyConfiguration.class, "spring.http.encoding.enabled:false");
this.thrown.expect(NoSuchBeanDefinitionException.class);
this.context.getBean(CharacterEncodingFilter.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.context.getBean(CharacterEncodingFilter.class));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,9 +29,7 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -53,6 +51,7 @@ import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -65,9 +64,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/
public class BasicErrorControllerDirectMockMvcTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private ConfigurableWebApplicationContext wac;
private MockMvc mockMvc;
@@ -110,8 +106,8 @@ public class BasicErrorControllerDirectMockMvcTests {
setup((ConfigurableWebApplicationContext) new SpringApplication(
WebMvcIncludedConfiguration.class).run("--server.port=0",
"--server.error.whitelabel.enabled=false"));
this.thrown.expect(ServletException.class);
this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML));
assertThatExceptionOfType(ServletException.class).isThrownBy(
() -> this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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,9 +23,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -44,6 +42,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -59,9 +58,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class DefaultErrorViewResolverTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private DefaultErrorViewResolver resolver;
@Mock
@@ -87,16 +83,16 @@ public class DefaultErrorViewResolverTests {
@Test
public void createWhenApplicationContextIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ApplicationContext must not be null");
new DefaultErrorViewResolver(null, new ResourceProperties());
assertThatIllegalArgumentException().isThrownBy(
() -> new DefaultErrorViewResolver(null, new ResourceProperties()))
.withMessageContaining("ApplicationContext must not be null");
}
@Test
public void createWhenResourcePropertiesIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ResourceProperties must not be null");
new DefaultErrorViewResolver(mock(ApplicationContext.class), null);
assertThatIllegalArgumentException().isThrownBy(
() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), null))
.withMessageContaining("ResourceProperties must not be null");
}
@Test

View File

@@ -16,9 +16,9 @@
package org.springframework.boot.autoconfigure.webservices;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link WebServicesProperties}.
@@ -27,33 +27,29 @@ import org.junit.rules.ExpectedException;
*/
public class WebServicesPropertiesTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private WebServicesProperties properties;
@Test
public void pathMustNotBeEmpty() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("");
assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath(""))
.withMessageContaining("Path must have length greater than 1");
}
@Test
public void pathMustHaveLengthGreaterThanOne() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("/");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.properties.setPath("/"))
.withMessageContaining("Path must have length greater than 1");
}
@Test
public void customPathMustBeginWithASlash() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must start with '/'");
this.properties.setPath("custom");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.properties.setPath("custom"))
.withMessageContaining("Path must start with '/'");
}
}