Browse Source

Constently use assertThatExceptionOf... assertions

Closes gh-37964
pull/38228/head
Phillip Webb 2 years ago
parent
commit
abdad1cabe
  1. 8
      buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java
  2. 6
      spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java
  3. 6
      spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentationTests.java
  4. 16
      spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java
  5. 10
      spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java
  6. 8
      spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java
  7. 12
      spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java
  8. 10
      spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java
  9. 9
      spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java
  10. 6
      spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java
  11. 6
      spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java
  12. 7
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java
  13. 14
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java
  14. 4
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java
  15. 6
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java
  16. 9
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java
  17. 37
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java
  18. 14
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java
  19. 4
      spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java
  20. 6
      spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java

8
buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java

@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.boot.build.mavenplugin.PluginXmlParser.Plugin; import org.springframework.boot.build.mavenplugin.PluginXmlParser.Plugin;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link PluginXmlParser}. * Tests for {@link PluginXmlParser}.
@ -50,9 +50,9 @@ class PluginXmlParserTests {
@Test @Test
void parseNonExistingFileThrowException() { void parseNonExistingFileThrowException() {
assertThatThrownBy(() -> this.parser.parse(new File("src/test/resources/nonexistent.xml"))) assertThatExceptionOfType(RuntimeException.class)
.isInstanceOf(RuntimeException.class) .isThrownBy(() -> this.parser.parse(new File("src/test/resources/nonexistent.xml")))
.hasCauseInstanceOf(FileNotFoundException.class); .withCauseInstanceOf(FileNotFoundException.class);
} }
} }

6
spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java

@ -50,7 +50,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -117,8 +117,8 @@ class HibernateMetricsAutoConfigurationTests {
.withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class) .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class)
.run((context) -> { .run((context) -> {
// ensure EntityManagerFactory is not a Hibernate SessionFactory // ensure EntityManagerFactory is not a Hibernate SessionFactory
assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) assertThatExceptionOfType(PersistenceException.class)
.isInstanceOf(PersistenceException.class); .isThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class));
MeterRegistry registry = context.getBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("hibernate.statements").meter()).isNull(); assertThat(registry.find("hibernate.statements").meter()).isNull();
}); });

6
spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/graphql/GraphQlMetricsInstrumentationTests.java

@ -43,7 +43,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.metrics.AutoTimer; import org.springframework.boot.actuate.metrics.AutoTimer;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -143,11 +143,9 @@ class GraphQlMetricsInstrumentationTests {
DataFetcher<CompletionStage<String>> dataFetcher = mock(DataFetcher.class); DataFetcher<CompletionStage<String>> dataFetcher = mock(DataFetcher.class);
given(dataFetcher.get(any())).willThrow(new IllegalStateException("test")); given(dataFetcher.get(any())).willThrow(new IllegalStateException("test"));
InstrumentationFieldFetchParameters fieldFetchParameters = mockFieldFetchParameters(false); InstrumentationFieldFetchParameters fieldFetchParameters = mockFieldFetchParameters(false);
DataFetcher<?> instrumented = this.instrumentation.instrumentDataFetcher(dataFetcher, fieldFetchParameters); DataFetcher<?> instrumented = this.instrumentation.instrumentDataFetcher(dataFetcher, fieldFetchParameters);
DataFetchingEnvironment environment = DataFetchingEnvironmentImpl.newDataFetchingEnvironment().build(); DataFetchingEnvironment environment = DataFetchingEnvironmentImpl.newDataFetchingEnvironment().build();
assertThatThrownBy(() -> instrumented.get(environment)).isInstanceOf(IllegalStateException.class); assertThatIllegalArgumentException().isThrownBy(() -> instrumented.get(environment));
Timer timer = this.registry.find("graphql.datafetcher").timer(); Timer timer = this.registry.find("graphql.datafetcher").timer();
assertThat(timer).isNotNull(); assertThat(timer).isNotNull();
assertThat(timer.count()).isEqualTo(1); assertThat(timer.count()).isEqualTo(1);

16
spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java

@ -43,7 +43,7 @@ import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -145,9 +145,10 @@ class MetricsWebClientFilterFunctionTests {
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR")
.timer() .timer()
.count()).isEqualTo(1); .count()).isEqualTo(1);
assertThatThrownBy(() -> this.registry.get("http.client.requests") assertThatExceptionOfType(MeterNotFoundException.class)
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") .isThrownBy(() -> this.registry.get("http.client.requests")
.timer()).isInstanceOf(MeterNotFoundException.class); .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200")
.timer());
} }
@Test @Test
@ -162,9 +163,10 @@ class MetricsWebClientFilterFunctionTests {
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "200") .tags("method", "GET", "uri", "/projects/spring-boot", "status", "200")
.timer() .timer()
.count()).isEqualTo(1); .count()).isEqualTo(1);
assertThatThrownBy(() -> this.registry.get("http.client.requests") assertThatExceptionOfType(MeterNotFoundException.class)
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR") .isThrownBy(() -> this.registry.get("http.client.requests")
.timer()).isInstanceOf(MeterNotFoundException.class); .tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR")
.timer());
} }
@Test @Test

10
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java

@ -31,13 +31,14 @@ import com.datastax.oss.driver.internal.core.session.throttling.PassThroughReque
import com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler; import com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link CassandraAutoConfiguration} * Tests for {@link CassandraAutoConfiguration}
@ -217,9 +218,10 @@ class CassandraAutoConfigurationTests {
@Test @Test
void driverConfigLoaderWithRateLimitingRequiresExtraConfiguration() { void driverConfigLoaderWithRateLimitingRequiresExtraConfiguration() {
this.contextRunner.withPropertyValues("spring.data.cassandra.request.throttler.type=rate-limiting") this.contextRunner.withPropertyValues("spring.data.cassandra.request.throttler.type=rate-limiting")
.run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) .run((context) -> assertThatExceptionOfType(BeanCreationException.class)
.hasMessageContaining("Error instantiating class RateLimitingRequestThrottler") .isThrownBy(() -> context.getBean(CqlSession.class))
.hasMessageContaining("No configuration setting found for key")); .withMessageContaining("Error instantiating class RateLimitingRequestThrottler")
.withMessageContaining("No configuration setting found for key"));
} }
@Test @Test

8
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java

@ -34,13 +34,14 @@ import org.testcontainers.images.builder.Transferable;
import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.testsupport.testcontainers.CassandraContainer; import org.springframework.boot.testsupport.testcontainers.CassandraContainer;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link CassandraAutoConfiguration} that only uses password authentication. * Tests for {@link CassandraAutoConfiguration} that only uses password authentication.
@ -79,8 +80,9 @@ class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.data.cassandra.username=not-a-user", .withPropertyValues("spring.data.cassandra.username=not-a-user",
"spring.data.cassandra.password=invalid-password") "spring.data.cassandra.password=invalid-password")
.run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) .run((context) -> assertThatExceptionOfType(BeanCreationException.class)
.hasMessageContaining("Authentication error")); .isThrownBy(() -> context.getBean(CqlSession.class))
.withMessageContaining("Authentication error"));
} }
static final class PasswordAuthenticatorCassandraContainer extends CassandraContainer { static final class PasswordAuthenticatorCassandraContainer extends CassandraContainer {

12
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java

@ -34,7 +34,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -69,11 +69,11 @@ class IntegrationPropertiesEnvironmentPostProcessorTests {
void registerIntegrationPropertiesPropertySourceWithUnknownResourceThrowsException() { void registerIntegrationPropertiesPropertySourceWithUnknownResourceThrowsException() {
ConfigurableEnvironment environment = new StandardEnvironment(); ConfigurableEnvironment environment = new StandardEnvironment();
ClassPathResource unknown = new ClassPathResource("does-not-exist.properties", getClass()); ClassPathResource unknown = new ClassPathResource("does-not-exist.properties", getClass());
assertThatThrownBy(() -> new IntegrationPropertiesEnvironmentPostProcessor() assertThatIllegalStateException()
.registerIntegrationPropertiesPropertySource(environment, unknown)) .isThrownBy(() -> new IntegrationPropertiesEnvironmentPostProcessor()
.isInstanceOf(IllegalStateException.class) .registerIntegrationPropertiesPropertySource(environment, unknown))
.hasCauseInstanceOf(FileNotFoundException.class) .withCauseInstanceOf(FileNotFoundException.class)
.hasMessageContaining(unknown.toString()); .withMessageContaining(unknown.toString());
} }
@Test @Test

10
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java

@ -64,7 +64,7 @@ import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -328,10 +328,10 @@ class JacksonAutoConfigurationTests {
void disableDefaultLeniency() { void disableDefaultLeniency() {
this.contextRunner.withPropertyValues("spring.jackson.default-leniency:false").run((context) -> { this.contextRunner.withPropertyValues("spring.jackson.default-leniency:false").run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThatThrownBy(() -> mapper.readValue("{\"birthDate\": \"2010-12-30\"}", Person.class)) assertThatExceptionOfType(InvalidFormatException.class)
.isInstanceOf(InvalidFormatException.class) .isThrownBy(() -> mapper.readValue("{\"birthDate\": \"2010-12-30\"}", Person.class))
.hasMessageContaining("expected format") .withMessageContaining("expected format")
.hasMessageContaining("yyyyMMdd"); .withMessageContaining("yyyyMMdd");
}); });
} }

9
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java

@ -36,6 +36,7 @@ import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@ -51,7 +52,7 @@ import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link EmbeddedMongoAutoConfiguration}. * Tests for {@link EmbeddedMongoAutoConfiguration}.
@ -82,8 +83,10 @@ class EmbeddedMongoAutoConfigurationTests {
TestPropertyValues.of("spring.data.mongodb.port=0").applyTo(this.context); TestPropertyValues.of("spring.data.mongodb.port=0").applyTo(this.context);
this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class,
EmbeddedMongoAutoConfiguration.class); EmbeddedMongoAutoConfiguration.class);
assertThatThrownBy(() -> this.context.refresh()).hasRootCauseExactlyInstanceOf(IllegalStateException.class) assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.context.refresh())
.hasRootCauseMessage("Set the spring.mongodb.embedded.version property or define your own MongodConfig " .withRootCauseExactlyInstanceOf(IllegalStateException.class)
.havingRootCause()
.withMessage("Set the spring.mongodb.embedded.version property or define your own MongodConfig "
+ "bean to use embedded MongoDB"); + "bean to use embedded MongoDB");
} }

6
spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java

@ -24,8 +24,8 @@ import org.mockito.InOrder;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; 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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then; import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
@ -59,8 +59,8 @@ class ContextConsumerTests {
given(predicate.test(24)).willReturn(false); given(predicate.test(24)).willReturn(false);
ContextConsumer<ApplicationContext> firstConsumer = (context) -> assertThat(predicate.test(42)).isFalse(); ContextConsumer<ApplicationContext> firstConsumer = (context) -> assertThat(predicate.test(42)).isFalse();
ContextConsumer<ApplicationContext> secondConsumer = (context) -> assertThat(predicate.test(24)).isFalse(); ContextConsumer<ApplicationContext> secondConsumer = (context) -> assertThat(predicate.test(24)).isFalse();
assertThatThrownBy(() -> firstConsumer.andThen(secondConsumer).accept(mock(ApplicationContext.class))) assertThatExceptionOfType(AssertionError.class)
.isInstanceOf(AssertionError.class); .isThrownBy(() -> firstConsumer.andThen(secondConsumer).accept(mock(ApplicationContext.class)));
then(predicate).should().test(42); then(predicate).should().test(42);
then(predicate).shouldHaveNoMoreInteractions(); then(predicate).shouldHaveNoMoreInteractions();
} }

6
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java

@ -33,7 +33,7 @@ import org.springframework.boot.gradle.junit.GradleProjectBuilder;
import org.springframework.boot.testsupport.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.classpath.ClassPathExclusions;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link BuildInfo}. * Tests for {@link BuildInfo}.
@ -191,8 +191,8 @@ class BuildInfoTests {
void nullAdditionalPropertyProducesInformativeFailure() { void nullAdditionalPropertyProducesInformativeFailure() {
BuildInfo task = createTask(createProject("test")); BuildInfo task = createTask(createProject("test"));
task.getProperties().getAdditional().put("a", null); task.getProperties().getAdditional().put("a", null);
assertThatThrownBy(() -> buildInfoProperties(task)) assertThatExceptionOfType(Throwable.class).isThrownBy(() -> buildInfoProperties(task))
.hasMessage("Additional property 'a' is illegal as its value is null"); .withMessage("Additional property 'a' is illegal as its value is null");
} }
private Project createProject(String projectName) { private Project createProject(String projectName) {

7
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java

@ -35,9 +35,9 @@ import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.GenericApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; 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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** /**
* Tests for {@link SpringApplicationShutdownHook}. * Tests for {@link SpringApplicationShutdownHook}.
@ -163,8 +163,7 @@ class SpringApplicationShutdownHookTests {
ConfigurableApplicationContext context = new GenericApplicationContext(); ConfigurableApplicationContext context = new GenericApplicationContext();
shutdownHook.registerApplicationContext(context); shutdownHook.registerApplicationContext(context);
context.refresh(); context.refresh();
assertThatThrownBy(() -> shutdownHook.deregisterFailedApplicationContext(context)) assertThatIllegalStateException().isThrownBy(() -> shutdownHook.deregisterFailedApplicationContext(context));
.isInstanceOf(IllegalStateException.class);
assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue(); assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue();
} }
@ -174,7 +173,7 @@ class SpringApplicationShutdownHookTests {
GenericApplicationContext context = new GenericApplicationContext(); GenericApplicationContext context = new GenericApplicationContext();
shutdownHook.registerApplicationContext(context); shutdownHook.registerApplicationContext(context);
context.registerBean(FailingBean.class); context.registerBean(FailingBean.class);
assertThatThrownBy(context::refresh).isInstanceOf(BeanCreationException.class); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(context::refresh);
assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue(); assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue();
shutdownHook.deregisterFailedApplicationContext(context); shutdownHook.deregisterFailedApplicationContext(context);
assertThat(shutdownHook.isApplicationContextRegistered(context)).isFalse(); assertThat(shutdownHook.isApplicationContextRegistered(context)).isFalse();

14
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java

@ -27,7 +27,8 @@ import org.springframework.boot.context.metrics.buffering.StartupTimeline.Timeli
import org.springframework.core.metrics.StartupStep; import org.springframework.core.metrics.StartupStep;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* Tests for {@link BufferingApplicationStartup}. * Tests for {@link BufferingApplicationStartup}.
@ -86,8 +87,8 @@ class BufferingApplicationStartupTests {
void startRecordingShouldFailIfEventsWereRecorded() { void startRecordingShouldFailIfEventsWereRecorded() {
BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2); BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2);
applicationStartup.start("first").end(); applicationStartup.start("first").end();
assertThatThrownBy(applicationStartup::startRecording).isInstanceOf(IllegalStateException.class) assertThatIllegalStateException().isThrownBy(applicationStartup::startRecording)
.hasMessage("Cannot restart recording once steps have been buffered."); .withMessage("Cannot restart recording once steps have been buffered.");
} }
@Test @Test
@ -95,8 +96,8 @@ class BufferingApplicationStartupTests {
BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2); BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2);
StartupStep step = applicationStartup.start("first"); StartupStep step = applicationStartup.start("first");
step.end(); step.end();
assertThatThrownBy(() -> step.tag("name", "value")).isInstanceOf(IllegalStateException.class) assertThatIllegalStateException().isThrownBy(() -> step.tag("name", "value"))
.hasMessage("StartupStep has already ended."); .withMessage("StartupStep has already ended.");
} }
@Test @Test
@ -104,7 +105,8 @@ class BufferingApplicationStartupTests {
BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2); BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2);
StartupStep step = applicationStartup.start("first"); StartupStep step = applicationStartup.start("first");
step.tag("name", "value"); step.tag("name", "value");
assertThatThrownBy(() -> step.getTags().iterator().remove()).isInstanceOf(UnsupportedOperationException.class); assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> step.getTags().iterator().remove());
} }
@Test // gh-25792 @Test // gh-25792

4
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java

@ -34,7 +34,7 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptStatementFailedException; import org.springframework.jdbc.datasource.init.ScriptStatementFailedException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link DataSourceScriptDatabaseInitializer}. * Tests for {@link DataSourceScriptDatabaseInitializer}.
@ -82,7 +82,7 @@ class DataSourceScriptDatabaseInitializerTests
populator.setContinueOnError(false); populator.setContinueOnError(false);
} }
}; };
assertThatThrownBy(initializer::initializeDatabase).isInstanceOf(ScriptStatementFailedException.class); assertThatExceptionOfType(ScriptStatementFailedException.class).isThrownBy(initializer::initializeDatabase);
} }
@Override @Override

6
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java

@ -33,7 +33,7 @@ import org.springframework.context.support.StaticMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Integration tests for {@link MessageSourceMessageInterpolator}. * Integration tests for {@link MessageSourceMessageInterpolator}.
@ -86,8 +86,8 @@ class MessageSourceMessageInterpolatorIntegrationTests {
@Test @Test
void recursion() { void recursion() {
assertThatThrownBy(() -> validate("recursion")) assertThatExceptionOfType(Throwable.class).isThrownBy(() -> validate("recursion"))
.hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); .withStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'");
} }
@Test @Test

9
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java

@ -77,7 +77,7 @@ import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException; import org.springframework.web.reactive.function.client.WebClientRequestException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Base for testing classes that extends {@link AbstractReactiveWebServerFactory}. * Base for testing classes that extends {@link AbstractReactiveWebServerFactory}.
@ -210,7 +210,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
} }
protected void assertThatSslWithInvalidAliasCallFails(ThrowingCallable call) { protected void assertThatSslWithInvalidAliasCallFails(ThrowingCallable call) {
assertThatThrownBy(call).hasStackTraceContaining("Keystore does not contain specified alias 'test-alias-404'"); assertThatExceptionOfType(Exception.class).isThrownBy(call)
.withStackTraceContaining("Keystore does not contain specified alias 'test-alias-404'");
} }
protected ReactorClientHttpConnector buildTrustAllSslConnector() { protected ReactorClientHttpConnector buildTrustAllSslConnector() {
@ -399,8 +400,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
@Test @Test
void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() { void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() {
assertThatThrownBy(() -> testBasicSslWithKeyStore(null, null)) assertThatExceptionOfType(Exception.class).isThrownBy(() -> testBasicSslWithKeyStore(null, null))
.hasMessageContaining("Could not load key store 'null'"); .withMessageContaining("Could not load key store 'null'");
} }
@Test @Test

37
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java

@ -28,7 +28,6 @@ import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** /**
* Tests for {@link PrivateKeyParser}. * Tests for {@link PrivateKeyParser}.
@ -75,12 +74,12 @@ class PrivateKeyParserTests {
}) })
// @formatter:on // @formatter:on
void shouldNotParseUnsupportedTraditionalPkcs1(String file) { void shouldNotParseUnsupportedTraditionalPkcs1(String file) {
assertThatThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/pkcs1/" + file)) assertThatIllegalStateException()
.isInstanceOf(IllegalStateException.class) .isThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/pkcs1/" + file))
.hasMessageContaining("Error loading private key file") .withMessageContaining("Error loading private key file")
.hasCauseInstanceOf(IllegalStateException.class) .withCauseInstanceOf(IllegalStateException.class)
.getCause() .havingCause()
.hasMessageContaining("Unrecognized private key format"); .withMessageContaining("Unrecognized private key format");
} }
@ParameterizedTest @ParameterizedTest
@ -118,12 +117,12 @@ class PrivateKeyParserTests {
}) })
// @formatter:on // @formatter:on
void shouldNotParseUnsupportedEcPkcs8(String file) { void shouldNotParseUnsupportedEcPkcs8(String file) {
assertThatThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/pkcs8/" + file)) assertThatIllegalStateException()
.isInstanceOf(IllegalStateException.class) .isThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/pkcs8/" + file))
.hasMessageContaining("Error loading private key file") .withMessageContaining("Error loading private key file")
.hasCauseInstanceOf(IllegalStateException.class) .withCauseInstanceOf(IllegalStateException.class)
.getCause() .havingCause()
.hasMessageContaining("Unrecognized private key format"); .withMessageContaining("Unrecognized private key format");
} }
@EnabledForJreRange(min = JRE.JAVA_17, disabledReason = "EdDSA is only supported since Java 17") @EnabledForJreRange(min = JRE.JAVA_17, disabledReason = "EdDSA is only supported since Java 17")
@ -191,12 +190,12 @@ class PrivateKeyParserTests {
}) })
// @formatter:on // @formatter:on
void shouldNotParseUnsupportedEcSec1(String file) { void shouldNotParseUnsupportedEcSec1(String file) {
assertThatThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/sec1/" + file)) assertThatIllegalStateException()
.isInstanceOf(IllegalStateException.class) .isThrownBy(() -> PrivateKeyParser.parse("classpath:org/springframework/boot/web/server/sec1/" + file))
.hasMessageContaining("Error loading private key file") .withMessageContaining("Error loading private key file")
.hasCauseInstanceOf(IllegalStateException.class) .withCauseInstanceOf(IllegalStateException.class)
.getCause() .havingCause()
.hasMessageContaining("Unrecognized private key format"); .withMessageContaining("Unrecognized private key format");
} }
@Test @Test

14
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java

@ -24,7 +24,7 @@ import java.security.KeyStoreException;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* Tests for {@link SslConfigurationValidator}. * Tests for {@link SslConfigurationValidator}.
@ -65,17 +65,17 @@ class SslConfigurationValidatorTests {
@Test @Test
void validateKeyAliasWhenAliasNotFoundShouldThrowException() { void validateKeyAliasWhenAliasNotFoundShouldThrowException() {
assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(this.keyStore, INVALID_ALIAS)) assertThatIllegalStateException()
.isInstanceOf(IllegalStateException.class) .isThrownBy(() -> SslConfigurationValidator.validateKeyAlias(this.keyStore, INVALID_ALIAS))
.hasMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'"); .withMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'");
} }
@Test @Test
void validateKeyAliasWhenKeyStoreThrowsExceptionOnContains() throws KeyStoreException { void validateKeyAliasWhenKeyStoreThrowsExceptionOnContains() throws KeyStoreException {
KeyStore uninitializedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore uninitializedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(uninitializedKeyStore, "alias")) assertThatIllegalStateException()
.isInstanceOf(IllegalStateException.class) .isThrownBy(() -> SslConfigurationValidator.validateKeyAlias(uninitializedKeyStore, "alias"))
.hasMessage("Could not determine if keystore contains alias 'alias'"); .withMessage("Could not determine if keystore contains alias 'alias'");
} }
} }

4
spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java

@ -148,7 +148,6 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -482,7 +481,8 @@ public abstract class AbstractServletWebServerFactoryTests {
} }
protected void assertThatSslWithInvalidAliasCallFails(ThrowingCallable call) { protected void assertThatSslWithInvalidAliasCallFails(ThrowingCallable call) {
assertThatThrownBy(call).hasStackTraceContaining("Keystore does not contain specified alias 'test-alias-404'"); assertThatExceptionOfType(Exception.class).isThrownBy(call)
.withStackTraceContaining("Keystore does not contain specified alias 'test-alias-404'");
} }
@Test @Test

6
spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java

@ -16,7 +16,6 @@
package smoketest.test.web; package smoketest.test.web;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import smoketest.test.WelcomeCommandLineRunner; import smoketest.test.WelcomeCommandLineRunner;
import smoketest.test.domain.VehicleIdentificationNumber; import smoketest.test.domain.VehicleIdentificationNumber;
@ -31,6 +30,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -96,8 +96,8 @@ class UserVehicleControllerTests {
@Test @Test
void welcomeCommandLineRunnerShouldNotBeAvailable() { void welcomeCommandLineRunnerShouldNotBeAvailable() {
// Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available. // Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available.
Assertions.assertThatThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)) assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isInstanceOf(NoSuchBeanDefinitionException.class); .isThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class));
} }
} }

Loading…
Cancel
Save