From b18fffaf14f9ce3e5651f44745019890e8a899c2 Mon Sep 17 00:00:00 2001 From: Andy Wilkinson Date: Fri, 24 May 2019 11:24:29 +0100 Subject: [PATCH] Move tests to JUnit 5 wherever possible --- .../SpringApplicationHierarchyTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- .../audit/AuditAutoConfigurationTests.java | 14 +- ...tEventsEndpointAutoConfigurationTests.java | 10 +- .../BeansEndpointAutoConfigurationTests.java | 8 +- .../CachesEndpointAutoConfigurationTests.java | 10 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- .../cloudfoundry/AccessLevelTests.java | 10 +- ...oudFoundryAuthorizationExceptionTests.java | 20 +- .../CloudFoundryEndpointFilterTests.java | 6 +- ...loudFoundryWebEndpointDiscovererTests.java | 4 +- .../cloudfoundry/TokenTests.java | 20 +- ...activeHealthEndpointWebExtensionTests.java | 4 +- ...oundryWebFluxEndpointIntegrationTests.java | 14 +- ...FoundryActuatorAutoConfigurationTests.java | 30 +- ...eCloudFoundrySecurityInterceptorTests.java | 18 +- ...ctiveCloudFoundrySecurityServiceTests.java | 22 +- .../reactive/ReactiveTokenValidatorTests.java | 22 +- ...FoundryActuatorAutoConfigurationTests.java | 26 +- ...oundryHealthEndpointWebExtensionTests.java | 4 +- ...dFoundryInfoEndpointWebExtensionTests.java | 6 +- ...FoundryMvcWebEndpointIntegrationTests.java | 14 +- .../CloudFoundrySecurityInterceptorTests.java | 18 +- .../CloudFoundrySecurityServiceTests.java | 26 +- ...slVerificationHttpRequestFactoryTests.java | 4 +- .../servlet/TokenValidatorTests.java | 20 +- ...sReportEndpointAutoConfigurationTests.java | 8 +- .../ConditionsReportEndpointTests.java | 4 +- ...hutdownEndpointAutoConfigurationTests.java | 8 +- ...sReportEndpointAutoConfigurationTests.java | 10 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 8 +- ...ointIdTimeToLivePropertyFunctionTests.java | 8 +- ...oseExcludePropertyEndpointFilterTests.java | 32 +- .../ConditionalOnAvailableEndpointTests.java | 40 +- .../ConditionalOnEnabledEndpointTests.java | 30 +- ...DefaultEndpointObjectNameFactoryTests.java | 14 +- .../MappingWebEndpointPathMapperTests.java | 10 +- ...ntManagementContextConfigurationTests.java | 8 +- .../WebEndpointAutoConfigurationTests.java | 16 +- .../web/WebEndpointPropertiesTests.java | 10 +- ...AuditEventsEndpointDocumentationTests.java | 6 +- .../BeansEndpointDocumentationTests.java | 4 +- .../CachesEndpointDocumentationTests.java | 10 +- ...tionsReportEndpointDocumentationTests.java | 4 +- ...rtiesReportEndpointDocumentationTests.java | 4 +- ...EnvironmentEndpointDocumentationTests.java | 6 +- .../FlywayEndpointDocumentationTests.java | 4 +- .../HealthEndpointDocumentationTests.java | 8 +- ...HeapDumpWebEndpointDocumentationTests.java | 4 +- .../HttpTraceEndpointDocumentationTests.java | 4 +- .../InfoEndpointDocumentationTests.java | 4 +- ...rationGraphEndpointDocumentationTests.java | 6 +- .../LiquibaseEndpointDocumentationTests.java | 4 +- .../LogFileWebEndpointDocumentationTests.java | 6 +- .../LoggersEndpointDocumentationTests.java | 10 +- ...ngsEndpointReactiveDocumentationTests.java | 4 +- ...ingsEndpointServletDocumentationTests.java | 4 +- .../MetricsEndpointDocumentationTests.java | 8 +- ...theusScrapeEndpointDocumentationTests.java | 4 +- ...eduledTasksEndpointDocumentationTests.java | 4 +- .../SessionsEndpointDocumentationTests.java | 8 +- .../ShutdownEndpointDocumentationTests.java | 4 +- .../ThreadDumpEndpointDocumentationTests.java | 4 +- ...ntManagementContextConfigurationTests.java | 8 +- ...ronmentEndpointAutoConfigurationTests.java | 10 +- .../FlywayEndpointAutoConfigurationTests.java | 8 +- .../HealthEndpointAutoConfigurationTests.java | 8 +- .../HealthEndpointWebExtensionTests.java | 56 +-- ...HealthIndicatorAutoConfigurationTests.java | 16 +- ...activeHealthEndpointWebExtensionTests.java | 28 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...InfoContributorAutoConfigurationTests.java | 18 +- .../InfoEndpointAutoConfigurationTests.java | 8 +- ...onGraphEndpointAutoConfigurationTests.java | 10 +- ...rollerEndpointWebFluxIntegrationTests.java | 4 +- ...trollerEndpointWebMvcIntegrationTests.java | 6 +- .../JerseyEndpointIntegrationTests.java | 6 +- .../JmxEndpointIntegrationTests.java | 8 +- ...ointAutoConfigurationIntegrationTests.java | 10 +- ...intsAutoConfigurationIntegrationTests.java | 6 +- .../WebFluxEndpointCorsIntegrationTests.java | 22 +- .../WebFluxEndpointIntegrationTests.java | 4 +- .../WebMvcEndpointCorsIntegrationTests.java | 22 +- ...ebMvcEndpointExposureIntegrationTests.java | 10 +- .../WebMvcEndpointIntegrationTests.java | 10 +- ...HealthIndicatorAutoConfigurationTests.java | 12 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...JolokiaEndpointAutoConfigurationTests.java | 10 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...quibaseEndpointAutoConfigurationTests.java | 12 +- ...FileWebEndpointAutoConfigurationTests.java | 22 +- ...LoggersEndpointAutoConfigurationTests.java | 10 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...DumpWebEndpointAutoConfigurationTests.java | 6 +- ...eadDumpEndpointAutoConfigurationTests.java | 8 +- ...teMeterRegistryAutoConfigurationTests.java | 10 +- .../JvmMetricsAutoConfigurationTests.java | 12 +- .../KafkaMetricsAutoConfigurationTests.java | 8 +- ...4jLoggerContextAutoConfigurationTests.java | 6 +- .../LogbackMetricsAutoConfigurationTests.java | 6 +- ...terRegistryConfigurerIntegrationTests.java | 10 +- .../metrics/MeterRegistryConfigurerTests.java | 20 +- .../metrics/MeterRegistryCustomizerTests.java | 8 +- .../metrics/MeterValueTests.java | 18 +- ...ricsAutoConfigurationIntegrationTests.java | 16 +- .../MetricsAutoConfigurationTests.java | 8 +- ...iredConfigurationFailureAnalyzerTests.java | 6 +- .../metrics/PropertiesMeterFilterTests.java | 64 +-- .../ServiceLevelAgreementBoundaryTests.java | 8 +- .../SystemMetricsAutoConfigurationTests.java | 14 +- .../RabbitMetricsAutoConfigurationTests.java | 6 +- .../CacheMetricsAutoConfigurationTests.java | 8 +- ...csMetricsExportAutoConfigurationTests.java | 14 +- ...AppOpticsPropertiesConfigAdapterTests.java | 8 +- .../appoptics/AppOpticsPropertiesTests.java | 4 +- ...asMetricsExportAutoConfigurationTests.java | 14 +- .../export/atlas/AtlasPropertiesTests.java | 4 +- ...ogMetricsExportAutoConfigurationTests.java | 16 +- .../DatadogPropertiesConfigAdapterTests.java | 4 +- .../datadog/DatadogPropertiesTests.java | 4 +- ...ceMetricsExportAutoConfigurationTests.java | 16 +- ...DynatracePropertiesConfigAdapterTests.java | 10 +- .../dynatrace/DynatracePropertiesTests.java | 4 +- ...icMetricsExportAutoConfigurationTests.java | 14 +- .../ElasticPropertiesConfigAdapterTests.java | 16 +- .../elastic/ElasticPropertiesTests.java | 4 +- ...iaMetricsExportAutoConfigurationTests.java | 14 +- .../ganglia/GangliaPropertiesTests.java | 4 +- ...teMetricsExportAutoConfigurationTests.java | 16 +- .../graphite/GraphitePropertiesTests.java | 4 +- ...ioMetricsExportAutoConfigurationTests.java | 14 +- .../HumioPropertiesConfigAdapterTests.java | 10 +- .../export/humio/HumioPropertiesTests.java | 4 +- ...uxMetricsExportAutoConfigurationTests.java | 14 +- .../export/influx/InfluxPropertiesTests.java | 4 +- ...mxMetricsExportAutoConfigurationTests.java | 14 +- .../export/jmx/JmxPropertiesTests.java | 4 +- ...osMetricsExportAutoConfigurationTests.java | 14 +- .../KairosPropertiesConfigAdapterTests.java | 8 +- .../export/kairos/KairosPropertiesTests.java | 4 +- ...icMetricsExportAutoConfigurationTests.java | 18 +- .../newrelic/NewRelicPropertiesTests.java | 4 +- ...usMetricsExportAutoConfigurationTests.java | 28 +- .../prometheus/PrometheusPropertiesTests.java | 4 +- ...pRegistryPropertiesConfigAdapterTests.java | 8 +- ...FxMetricsExportAutoConfigurationTests.java | 16 +- .../signalfx/SignalFxPropertiesTests.java | 4 +- ...leMetricsExportAutoConfigurationTests.java | 10 +- .../export/simple/SimplePropertiesTests.java | 4 +- ...sdMetricsExportAutoConfigurationTests.java | 14 +- .../export/statsd/StatsdPropertiesTests.java | 4 +- ...ntMetricsExportAutoConfigurationTests.java | 14 +- ...WavefrontPropertiesConfigAdapterTests.java | 10 +- .../wavefront/WavefrontPropertiesTests.java | 4 +- ...urcePoolMetricsAutoConfigurationTests.java | 24 +- ...eyServerMetricsAutoConfigurationTests.java | 12 +- ...ibernateMetricsAutoConfigurationTests.java | 14 +- .../metrics/test/MetricsIntegrationTests.java | 10 +- ...RestTemplateMetricsConfigurationTests.java | 14 +- .../WebClientMetricsConfigurationTests.java | 12 +- .../JettyMetricsAutoConfigurationTests.java | 8 +- .../WebFluxMetricsAutoConfigurationTests.java | 14 +- .../WebMvcMetricsAutoConfigurationTests.java | 18 +- .../TomcatMetricsAutoConfigurationTests.java | 12 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 8 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...edTasksEndpointAutoConfigurationTests.java | 10 +- .../reactive/EndpointRequestTests.java | 36 +- ...mentWebSecurityAutoConfigurationTests.java | 16 +- ...stractEndpointRequestIntegrationTests.java | 8 +- .../servlet/EndpointRequestTests.java | 42 +- ...JerseyEndpointRequestIntegrationTests.java | 8 +- ...mentWebSecurityAutoConfigurationTests.java | 14 +- .../MvcEndpointRequestIntegrationTests.java | 8 +- ...essionsEndpointAutoConfigurationTests.java | 8 +- ...HealthIndicatorAutoConfigurationTests.java | 6 +- ...HealthIndicatorAutoConfigurationTests.java | 10 +- .../ManagementContextConfigurationTests.java | 8 +- ...ReactiveManagementContextFactoryTests.java | 4 +- ...nagementContextAutoConfigurationTests.java | 4 +- ...ntextConfigurationImportSelectorTests.java | 8 +- .../ManagementServerPropertiesTests.java | 10 +- ...ompositeHandlerExceptionResolverTests.java | 6 +- ...ndpointChildContextConfigurationTests.java | 10 +- .../HttpTraceAutoConfigurationTests.java | 16 +- ...tpTraceEndpointAutoConfigurationTests.java | 10 +- .../boot/actuate/AdhocTestSuite.java | 34 -- .../amqp/RabbitHealthIndicatorTests.java | 8 +- .../boot/actuate/audit/AuditEventTests.java | 14 +- .../audit/AuditEventsEndpointTests.java | 8 +- ...uditEventsEndpointWebIntegrationTests.java | 25 +- .../InMemoryAuditEventRepositoryTests.java | 14 +- .../audit/listener/AuditListenerTests.java | 4 +- .../actuate/beans/BeansEndpointTests.java | 10 +- .../actuate/cache/CachesEndpointTests.java | 28 +- .../CachesEndpointWebIntegrationTests.java | 42 +- .../CassandraHealthIndicatorTests.java | 10 +- ...CassandraReactiveHealthIndicatorTests.java | 6 +- .../context/ShutdownEndpointTests.java | 8 +- ...sReportEndpointMethodAnnotationsTests.java | 6 +- ...onPropertiesReportEndpointParentTests.java | 6 +- ...ionPropertiesReportEndpointProxyTests.java | 4 +- ...rtiesReportEndpointSerializationTests.java | 22 +- ...gurationPropertiesReportEndpointTests.java | 30 +- .../CouchbaseHealthIndicatorTests.java | 6 +- ...CouchbaseReactiveHealthIndicatorTests.java | 6 +- .../ElasticsearchHealthIndicatorTests.java | 16 +- ...ElasticsearchJestHealthIndicatorTests.java | 14 +- .../ElasticsearchRestHealthIndicatorTest.java | 12 +- .../actuate/endpoint/EndpointIdTests.java | 28 +- .../boot/actuate/endpoint/SanitizerTests.java | 6 +- .../DiscoveredOperationMethodTests.java | 6 +- .../DiscoveredOperationsFactoryTests.java | 16 +- .../DiscovererEndpointFilterTests.java | 8 +- .../annotation/EndpointDiscovererTests.java | 38 +- ...rsionServiceParameterValueMapperTests.java | 10 +- .../IsoOffsetDateTimeConverterTests.java | 6 +- .../OperationMethodParameterTests.java | 10 +- .../OperationMethodParametersTests.java | 18 +- .../invoke/reflect/OperationMethodTests.java | 12 +- .../ReflectiveOperationInvokerTests.java | 16 +- .../CachingOperationInvokerAdvisorTests.java | 16 +- .../cache/CachingOperationInvokerTests.java | 14 +- .../endpoint/jmx/EndpointMBeanTests.java | 34 +- ...acksonJmxOperationResponseMapperTests.java | 24 +- .../jmx/JmxEndpointExporterTests.java | 24 +- .../endpoint/jmx/MBeanInfoFactoryTests.java | 14 +- .../DiscoveredJmxOperationTests.java | 18 +- .../JmxEndpointDiscovererTests.java | 28 +- .../web/EndpointLinksResolverTests.java | 12 +- .../endpoint/web/EndpointMappingTests.java | 22 +- .../endpoint/web/EndpointMediaTypesTests.java | 10 +- .../endpoint/web/EndpointServletTests.java | 30 +- .../boot/actuate/endpoint/web/LinkTests.java | 10 +- .../web/PathMappedEndpointsTests.java | 26 +- .../web/ServletEndpointRegistrarTests.java | 18 +- .../web/WebEndpointResponseTests.java | 10 +- .../WebOperationRequestPredicateTests.java | 14 +- .../AbstractWebEndpointIntegrationTests.java | 78 ++-- .../ControllerEndpointDiscovererTests.java | 16 +- .../ServletEndpointDiscovererTests.java | 18 +- .../WebEndpointDiscovererTests.java | 32 +- ...ndpointHandlerMappingIntegrationTests.java | 8 +- ...ControllerEndpointHandlerMappingTests.java | 10 +- .../WebFluxEndpointIntegrationTests.java | 6 +- ...ndpointHandlerMappingIntegrationTests.java | 8 +- ...ControllerEndpointHandlerMappingTests.java | 10 +- .../MvcWebEndpointIntegrationTests.java | 10 +- .../endpoint/web/servlet/WebMvcTagsTests.java | 32 +- .../web/test/AbstractWebEndpointRunner.java | 224 ---------- .../web/test/JerseyEndpointsRunner.java | 110 ----- .../endpoint/web/test/WebEndpointRunners.java | 65 --- ...ntextFactory.java => WebEndpointTest.java} | 24 +- ...EndpointTestInvocationContextProvider.java | 325 ++++++++++++++ .../web/test/WebFluxEndpointsRunner.java | 115 ----- .../web/test/WebMvcEndpointRunner.java | 97 ----- .../actuate/env/EnvironmentEndpointTests.java | 30 +- ...nvironmentEndpointWebIntegrationTests.java | 82 ++-- .../actuate/flyway/FlywayEndpointTests.java | 6 +- .../ApplicationHealthIndicatorTests.java | 4 +- .../health/CompositeHealthIndicatorTests.java | 6 +- ...CompositeReactiveHealthIndicatorTests.java | 10 +- .../DefaultHealthIndicatorRegistryTests.java | 14 +- ...tReactiveHealthIndicatorRegistryTests.java | 14 +- .../actuate/health/HealthEndpointTests.java | 14 +- .../HealthEndpointWebIntegrationTests.java | 66 ++- .../HealthIndicatorReactiveAdapterTests.java | 8 +- .../boot/actuate/health/HealthTests.java | 38 +- .../HealthWebEndpointResponseMapperTests.java | 10 +- .../health/OrderedHealthAggregatorTests.java | 10 +- ...veHealthIndicatorRegistryFactoryTests.java | 6 +- .../influx/InfluxDbHealthIndicatorTests.java | 6 +- .../info/EnvironmentInfoContributorTests.java | 8 +- .../actuate/info/GitInfoContributorTests.java | 8 +- .../boot/actuate/info/InfoEndpointTests.java | 6 +- .../info/InfoEndpointWebIntegrationTests.java | 14 +- .../boot/actuate/info/InfoTests.java | 6 +- .../info/SimpleInfoContributorTests.java | 6 +- .../IntegrationGraphEndpointTests.java | 6 +- ...ationGraphEndpointWebIntegrationTests.java | 18 +- .../jdbc/DataSourceHealthIndicatorTests.java | 10 +- .../actuate/jms/JmsHealthIndicatorTests.java | 12 +- .../ldap/LdapHealthIndicatorTests.java | 6 +- .../liquibase/LiquibaseEndpointTests.java | 10 +- .../logging/LogFileWebEndpointTests.java | 12 +- ...LogFileWebEndpointWebIntegrationTests.java | 50 +-- .../actuate/logging/LoggersEndpointTests.java | 10 +- .../LoggersEndpointWebIntegrationTests.java | 84 ++-- .../mail/MailHealthIndicatorTests.java | 6 +- .../management/HeapDumpWebEndpointTests.java | 4 +- ...eapDumpWebEndpointWebIntegrationTests.java | 27 +- .../management/ThreadDumpEndpointTests.java | 4 +- .../actuate/metrics/MetricsEndpointTests.java | 28 +- .../MetricsEndpointWebIntegrationTests.java | 21 +- .../metrics/amqp/RabbitMetricsTests.java | 6 +- .../cache/CacheMetricsRegistrarTests.java | 8 +- ...CaffeineCacheMeterBinderProviderTests.java | 4 +- ...EhCache2CacheMeterBinderProviderTests.java | 4 +- ...azelcastCacheMeterBinderProviderTests.java | 4 +- .../JCacheCacheMeterBinderProviderTests.java | 4 +- .../PrometheusPushGatewayManagerTests.java | 28 +- ...metheusScrapeEndpointIntegrationTests.java | 13 +- .../jdbc/DataSourcePoolMetricsTests.java | 4 +- .../MetricsRestTemplateCustomizerTests.java | 10 +- .../client/RestTemplateExchangeTagsTests.java | 20 +- ...ultWebClientExchangeTagsProviderTests.java | 10 +- .../MetricsWebClientCustomizerTests.java | 6 +- .../MetricsWebClientFilterFunctionTests.java | 12 +- .../client/WebClientExchangeTagsTests.java | 32 +- .../server/MetricsWebFilterTests.java | 10 +- .../web/reactive/server/WebFluxTagsTests.java | 30 +- ...LongTaskTimingHandlerInterceptorTests.java | 6 +- .../WebMvcMetricsFilterAutoTimedTests.java | 4 +- .../web/servlet/WebMvcMetricsFilterTests.java | 36 +- .../WebMvcMetricsIntegrationTests.java | 6 +- .../mongo/MongoHealthIndicatorTests.java | 6 +- .../MongoReactiveHealthIndicatorTests.java | 6 +- .../neo4j/Neo4jHealthIndicatorTests.java | 9 +- .../redis/RedisHealthIndicatorTests.java | 8 +- .../RedisReactiveHealthIndicatorTests.java | 8 +- .../ScheduledTasksEndpointTests.java | 16 +- .../AuthenticationAuditListenerTests.java | 14 +- .../AuthorizationAuditListenerTests.java | 8 +- .../session/SessionsEndpointTests.java | 12 +- .../SessionsEndpointWebIntegrationTests.java | 25 +- .../solr/SolrHealthIndicatorTests.java | 8 +- .../system/DiskSpaceHealthIndicatorTests.java | 6 +- .../trace/http/HttpExchangeTracerTests.java | 58 +-- .../trace/http/HttpTraceEndpointTests.java | 4 +- .../InMemoryHttpTraceRepositoryTests.java | 6 +- .../HttpTraceWebFilterIntegrationTests.java | 8 +- .../reactive/HttpTraceWebFilterTests.java | 10 +- .../http/servlet/HttpTraceFilterTests.java | 12 +- .../web/mappings/MappingsEndpointTests.java | 8 +- ...erverWebExchangeTraceableRequestTests.java | 18 +- .../TraceableHttpServletRequestTests.java | 10 +- .../spring-boot-autoconfigure/pom.xml | 5 + .../boot/autoconfigure/AdhocTestSuite.java | 39 -- .../AutoConfigurationExcludeFilterTests.java | 4 +- ...urationImportSelectorIntegrationTests.java | 10 +- .../AutoConfigurationImportSelectorTests.java | 34 +- .../AutoConfigurationMetadataLoaderTests.java | 26 +- .../AutoConfigurationPackagesTests.java | 6 +- .../AutoConfigurationReproTests.java | 4 +- .../AutoConfigurationSorterTests.java | 26 +- .../AutoConfigurationsTests.java | 4 +- ...tAutoConfigurationImportSelectorTests.java | 30 +- .../ImportAutoConfigurationTests.java | 12 +- ...aReaderFactoryContextInitializerTests.java | 4 +- .../SpringBootApplicationTests.java | 8 +- .../boot/autoconfigure/SpringJUnitTests.java | 6 +- ...icationAdminJmxAutoConfigurationTests.java | 14 +- .../amqp/RabbitAutoConfigurationTests.java | 86 ++-- .../amqp/RabbitPropertiesTests.java | 68 +-- .../aop/AopAutoConfigurationTests.java | 12 +- .../batch/BatchAutoConfigurationTests.java | 26 +- .../JobExecutionExitCodeGeneratorTests.java | 8 +- .../JobLauncherCommandLineRunnerTests.java | 16 +- .../cache/CacheManagerCustomizersTests.java | 8 +- .../CassandraAutoConfigurationTests.java | 16 +- ...rviceConnectorsAutoConfigurationTests.java | 4 +- .../AbstractNestedConditionTests.java | 8 +- .../condition/AllNestedConditionsTests.java | 10 +- .../condition/AnyNestedConditionTests.java | 10 +- ...tAutoConfigurationImportListenerTests.java | 12 +- .../ConditionEvaluationReportTests.java | 26 +- .../condition/ConditionMessageTests.java | 52 +-- .../condition/ConditionalOnBeanTests.java | 42 +- .../condition/ConditionalOnClassTests.java | 12 +- .../ConditionalOnCloudPlatformTests.java | 8 +- .../ConditionalOnExpressionTests.java | 10 +- .../condition/ConditionalOnJavaTests.java | 27 +- .../condition/ConditionalOnJndiTests.java | 14 +- .../ConditionalOnMissingBeanTests.java | 62 +-- ...MissingBeanWithFilteredClasspathTests.java | 4 +- .../ConditionalOnMissingClassTests.java | 6 +- .../ConditionalOnNotWebApplicationTests.java | 8 +- .../condition/ConditionalOnPropertyTests.java | 62 +-- .../condition/ConditionalOnResourceTests.java | 8 +- .../ConditionalOnSingleCandidateTests.java | 24 +- .../ConditionalOnWebApplicationTests.java | 8 +- .../condition/NoneNestedConditionsTests.java | 10 +- ...ionAutoConfigurationImportFilterTests.java | 8 +- .../OnPropertyListConditionTests.java | 12 +- .../condition/ResourceConditionTests.java | 8 +- .../condition/SpringBootConditionTests.java | 6 +- ...ationPropertiesAutoConfigurationTests.java | 6 +- ...urceAutoConfigurationIntegrationTests.java | 4 +- ...geSourceAutoConfigurationProfileTests.java | 4 +- .../MessageSourceAutoConfigurationTests.java | 38 +- ...ertyPlaceholderAutoConfigurationTests.java | 6 +- ...baseAutoConfigurationIntegrationTests.java | 14 +- .../CouchbaseAutoConfigurationTests.java | 22 +- .../couchbase/CouchbaseTestServer.java | 129 ------ .../couchbase/LocalCouchbaseServer.java | 72 ++++ .../OnBootstrapHostsConditionTests.java | 8 +- ...tionTranslationAutoConfigurationTests.java | 10 +- .../ConditionalOnRepositoryTypeTests.java | 24 +- ...DataAutoConfigurationIntegrationTests.java | 21 +- .../CassandraDataAutoConfigurationTests.java | 14 +- ...draReactiveDataAutoConfigurationTests.java | 8 +- ...iveRepositoriesAutoConfigurationTests.java | 12 +- ...draRepositoriesAutoConfigurationTests.java | 12 +- .../CouchbaseDataAutoConfigurationTests.java | 18 +- ...iveRepositoriesAutoConfigurationTests.java | 7 +- ...aseReactiveDataAutoConfigurationTests.java | 12 +- ...iveRepositoriesAutoConfigurationTests.java | 14 +- ...aseRepositoriesAutoConfigurationTests.java | 12 +- .../ElasticsearchAutoConfigurationTests.java | 23 +- ...asticsearchDataAutoConfigurationTests.java | 35 +- ...rchRepositoriesAutoConfigurationTests.java | 18 +- ...rchRepositoriesAutoConfigurationTests.java | 14 +- ...ctiveRestClientAutoConfigurationTests.java | 17 +- ...dbcRepositoriesAutoConfigurationTests.java | 12 +- ...JpaRepositoriesAutoConfigurationTests.java | 16 +- .../jpa/JpaWebAutoConfigurationTests.java | 4 +- ...dapRepositoriesAutoConfigurationTests.java | 8 +- ...ngoRepositoriesAutoConfigurationTests.java | 19 +- .../MongoDataAutoConfigurationTests.java | 28 +- ...ingRepositoriesAutoConfigurationTests.java | 7 +- ...ngoReactiveDataAutoConfigurationTests.java | 8 +- ...iveRepositoriesAutoConfigurationTests.java | 14 +- ...ngoRepositoriesAutoConfigurationTests.java | 14 +- ...o4jRepositoriesAutoConfigurationTests.java | 12 +- .../Neo4jDataAutoConfigurationTests.java | 28 +- .../data/neo4j/Neo4jPropertiesTests.java | 30 +- ...o4jRepositoriesAutoConfigurationTests.java | 10 +- .../redis/RedisAutoConfigurationTests.java | 30 +- .../RedisReactiveAutoConfigurationTests.java | 4 +- ...disRepositoriesAutoConfigurationTests.java | 14 +- ...positoryRestMvcAutoConfigurationTests.java | 12 +- ...olrRepositoriesAutoConfigurationTests.java | 10 +- .../SpringDataWebAutoConfigurationTests.java | 12 +- ...uchBeanDefinitionFailureAnalyzerTests.java | 24 +- .../domain/EntityScanPackagesTests.java | 28 +- .../domain/EntityScannerTests.java | 10 +- .../jest/JestAutoConfigurationTests.java | 24 +- .../RestClientAutoConfigurationTests.java | 27 +- .../flyway/FlywayAutoConfigurationTests.java | 72 ++-- ...tionScriptMissingFailureAnalyzerTests.java | 8 +- .../flyway/FlywayPropertiesTests.java | 6 +- ...ConfigurationReactiveIntegrationTests.java | 30 +- ...oConfigurationServletIntegrationTests.java | 44 +- .../FreeMarkerAutoConfigurationTests.java | 22 +- ...rkerTemplateAvailabilityProviderTests.java | 14 +- .../GroovyTemplateAutoConfigurationTests.java | 28 +- ...oovyTemplateAvailabilityProviderTests.java | 14 +- .../gson/GsonAutoConfigurationTests.java | 38 +- .../h2/H2ConsoleAutoConfigurationTests.java | 14 +- .../h2/H2ConsolePropertiesTests.java | 8 +- .../HypermediaAutoConfigurationTests.java | 12 +- ...HazelcastAutoConfigurationClientTests.java | 18 +- .../HazelcastAutoConfigurationTests.java | 4 +- ...stJpaDependencyAutoConfigurationTests.java | 10 +- ...ssageConvertersAutoConfigurationTests.java | 46 +- ...sAutoConfigurationWithoutJacksonTests.java | 4 +- .../http/HttpMessageConvertersTests.java | 14 +- .../codec/CodecsAutoConfigurationTests.java | 14 +- .../InfluxDbAutoConfigurationTests.java | 10 +- .../ProjectInfoAutoConfigurationTests.java | 24 +- .../IntegrationAutoConfigurationTests.java | 26 +- .../JacksonAutoConfigurationTests.java | 64 +-- .../DataSourceAutoConfigurationTests.java | 32 +- .../DataSourceInitializerInvokerTests.java | 26 +- .../jdbc/DataSourceInitializerTests.java | 10 +- .../jdbc/DataSourceJmxConfigurationTests.java | 18 +- .../DataSourceJsonSerializationTests.java | 6 +- .../jdbc/DataSourcePropertiesTests.java | 26 +- ...nsactionManagerAutoConfigurationTests.java | 16 +- .../EmbeddedDataSourceConfigurationTests.java | 6 +- .../HikariDataSourceConfigurationTests.java | 14 +- ...iverConfigurationFailureAnalyzerTests.java | 6 +- .../JdbcTemplateAutoConfigurationTests.java | 32 +- .../JndiDataSourceAutoConfigurationTests.java | 10 +- .../TomcatDataSourceConfigurationTests.java | 10 +- .../XADataSourceAutoConfigurationTests.java | 8 +- ...toConfigurationCustomApplicationTests.java | 4 +- ...igurationCustomFilterContextPathTests.java | 4 +- ...utoConfigurationCustomFilterPathTests.java | 4 +- ...ConfigurationCustomLoadOnStartupTests.java | 4 +- ...rationCustomObjectMapperProviderTests.java | 4 +- ...gurationCustomServletContextPathTests.java | 4 +- ...toConfigurationCustomServletPathTests.java | 4 +- ...toConfigurationDefaultFilterPathTests.java | 4 +- ...oConfigurationDefaultServletPathTests.java | 4 +- ...onfigurationObjectMapperProviderTests.java | 4 +- ...utoConfigurationServletContainerTests.java | 4 +- .../jersey/JerseyAutoConfigurationTests.java | 16 +- ...figurationWithoutApplicationPathTests.java | 4 +- .../jms/JmsAutoConfigurationTests.java | 58 +-- .../autoconfigure/jms/JmsPropertiesTests.java | 16 +- ...nnectionFactoryAutoConfigurationTests.java | 14 +- .../ActiveMQAutoConfigurationTests.java | 20 +- .../jms/activemq/ActiveMQPropertiesTests.java | 14 +- .../ArtemisAutoConfigurationTests.java | 42 +- ...emisEmbeddedConfigurationFactoryTests.java | 14 +- .../jmx/JmxAutoConfigurationTests.java | 16 +- .../jooq/JooqAutoConfigurationTests.java | 12 +- .../jooq/JooqExceptionTranslatorTests.java | 46 +- .../jooq/JooqPropertiesTests.java | 10 +- .../jooq/SqlDialectLookupTests.java | 24 +- .../jsonb/JsonbAutoConfigurationTests.java | 4 +- ...afkaAutoConfigurationIntegrationTests.java | 6 +- .../kafka/KafkaAutoConfigurationTests.java | 52 +-- .../ldap/LdapAutoConfigurationTests.java | 14 +- .../EmbeddedLdapAutoConfigurationTests.java | 22 +- .../LiquibaseAutoConfigurationTests.java | 49 +-- ...nEvaluationReportLoggingListenerTests.java | 20 +- .../MailSenderAutoConfigurationTests.java | 32 +- .../mongo/MongoAutoConfigurationTests.java | 12 +- .../mongo/MongoClientFactoryTests.java | 16 +- .../mongo/MongoPropertiesTests.java | 16 +- .../MongoReactiveAutoConfigurationTests.java | 14 +- .../ReactiveMongoClientFactoryTests.java | 28 +- .../EmbeddedMongoAutoConfigurationTests.java | 32 +- ...ConfigurationReactiveIntegrationTests.java | 6 +- ...oConfigurationServletIntegrationTests.java | 8 +- .../MustacheAutoConfigurationTests.java | 10 +- .../MustacheStandaloneIntegrationTests.java | 10 +- .../AbstractJpaAutoConfigurationTests.java | 32 +- ...tomHibernateJpaAutoConfigurationTests.java | 10 +- .../orm/jpa/DatabaseLookupTests.java | 26 +- .../HibernateDefaultDdlAutoProviderTests.java | 8 +- .../HibernateJpaAutoConfigurationTests.java | 56 +-- .../orm/jpa/HibernatePropertiesTests.java | 20 +- .../orm/jpa/JpaPropertiesTests.java | 10 +- .../packagestest/one/FirstConfiguration.java | 2 +- .../quartz/QuartzAutoConfigurationTests.java | 36 +- .../QuartzDataSourceInitializerTests.java | 4 +- ...SocketMessagingAutoConfigurationTests.java | 8 +- ...SocketRequesterAutoConfigurationTests.java | 8 +- .../RSocketServerAutoConfigurationTests.java | 14 +- ...ocketStrategiesAutoConfigurationTests.java | 10 +- ...ocketWebSocketNettyRouteProviderTests.java | 4 +- .../security/SecurityPropertiesTests.java | 12 +- .../security/jpa/JpaUserDetailsTests.java | 4 +- ...entPropertiesRegistrationAdapterTests.java | 26 +- .../client/OAuth2ClientPropertiesTests.java | 6 +- ...iveOAuth2ClientAutoConfigurationTests.java | 26 +- ...istrationRepositoryConfigurationTests.java | 6 +- .../OAuth2WebSecurityConfigurationTests.java | 18 +- ...2ResourceServerAutoConfigurationTests.java | 32 +- ...2ResourceServerAutoConfigurationTests.java | 34 +- .../security/reactive/PathRequestTests.java | 4 +- ...eactiveSecurityAutoConfigurationTests.java | 6 +- ...rDetailsServiceAutoConfigurationTests.java | 16 +- .../reactive/StaticResourceRequestTests.java | 12 +- .../security/servlet/PathRequestTests.java | 6 +- .../SecurityAutoConfigurationTests.java | 24 +- ...ConfigurationEarlyInitializationTests.java | 4 +- .../SecurityFilterAutoConfigurationTests.java | 4 +- ...MatcherProviderAutoConfigurationTests.java | 18 +- .../servlet/StaticResourceRequestTests.java | 14 +- ...rDetailsServiceAutoConfigurationTests.java | 22 +- .../SendGridAutoConfigurationTests.java | 10 +- ...SessionRepositoryFailureAnalyzerTests.java | 4 +- ...iveSessionAutoConfigurationMongoTests.java | 8 +- ...iveSessionAutoConfigurationRedisTests.java | 8 +- ...essionAutoConfigurationHazelcastTests.java | 10 +- ...sionAutoConfigurationIntegrationTests.java | 8 +- .../SessionAutoConfigurationJdbcTests.java | 14 +- .../SessionAutoConfigurationMongoTests.java | 8 +- .../SessionAutoConfigurationRedisTests.java | 22 +- .../SessionAutoConfigurationTests.java | 34 +- .../TaskExecutionAutoConfigurationTests.java | 18 +- .../TaskSchedulingAutoConfigurationTests.java | 14 +- .../TemplateAvailabilityProvidersTests.java | 34 +- .../template/ViewResolverPropertiesTests.java | 12 +- ...ymeleafReactiveAutoConfigurationTests.java | 40 +- ...hymeleafServletAutoConfigurationTests.java | 67 ++- ...leafTemplateAvailabilityProviderTests.java | 10 +- .../TransactionAutoConfigurationTests.java | 20 +- .../TransactionManagerCustomizersTests.java | 6 +- .../jta/JtaAutoConfigurationTests.java | 28 +- .../ValidationAutoConfigurationTests.java | 24 +- ...hHibernateValidatorMissingElImplTests.java | 4 +- ...utoConfigurationWithoutValidatorTests.java | 4 +- .../validation/ValidatorAdapterTests.java | 10 +- ...onditionalOnEnabledResourceChainTests.java | 12 +- .../web/ResourcePropertiesBindingTests.java | 4 +- .../web/ResourcePropertiesTests.java | 20 +- .../web/ServerPropertiesTests.java | 66 +-- .../RestTemplateAutoConfigurationTests.java | 18 +- .../JettyWebServerFactoryCustomizerTests.java | 18 +- .../NettyWebServerFactoryCustomizerTests.java | 8 +- ...TomcatWebServerFactoryCustomizerTests.java | 82 ++-- ...dertowWebServerFactoryCustomizerTests.java | 34 +- .../web/format/WebConversionServiceTests.java | 6 +- .../HttpHandlerAutoConfigurationTests.java | 6 +- ...ebServerFactoryAutoConfigurationTests.java | 30 +- ...activeWebServerFactoryCustomizerTests.java | 8 +- .../WebFluxAutoConfigurationTests.java | 54 +-- ...orWebExceptionHandlerIntegrationTests.java | 34 +- .../DefaultErrorWebExceptionHandlerTests.java | 6 +- ...ntHttpConnectorAutoConfigurationTests.java | 8 +- ...ClientHttpConnectorConfigurationTests.java | 8 +- .../WebClientAutoConfigurationTests.java | 12 +- .../ConditionalOnMissingFilterBeanTests.java | 18 +- ...spatcherServletAutoConfigurationTests.java | 26 +- .../servlet/DispatcherServletPathTests.java | 20 +- ...ispatcherServletRegistrationBeanTests.java | 12 +- .../FilterOrderingIntegrationTests.java | 4 +- .../HttpEncodingAutoConfigurationTests.java | 24 +- .../servlet/JerseyApplicationPathTests.java | 22 +- .../JspTemplateAvailabilityProviderTests.java | 8 +- .../MultipartAutoConfigurationTests.java | 30 +- ...ebServerFactoryAutoConfigurationTests.java | 38 +- ...ervletWebServerFactoryCustomizerTests.java | 20 +- ...tWebServerServletContextListenerTests.java | 14 +- ...ervletWebServerFactoryCustomizerTests.java | 10 +- .../servlet/WebMvcAutoConfigurationTests.java | 132 +++--- .../web/servlet/WebMvcPropertiesTests.java | 8 +- .../WelcomePageHandlerMappingTests.java | 24 +- ...asicErrorControllerDirectMockMvcTests.java | 10 +- .../BasicErrorControllerIntegrationTests.java | 26 +- .../BasicErrorControllerMockMvcTests.java | 10 +- .../DefaultErrorViewIntegrationTests.java | 8 +- .../error/DefaultErrorViewResolverTests.java | 28 +- .../error/ErrorMvcAutoConfigurationTests.java | 6 +- .../RemappedErrorViewIntegrationTests.java | 6 +- .../OnWsdlLocationsConditionTests.java | 8 +- .../WebServicesAutoConfigurationTests.java | 18 +- .../WebServicesPropertiesTests.java | 8 +- ...ServiceTemplateAutoConfigurationTests.java | 12 +- ...SocketMessagingAutoConfigurationTests.java | 10 +- ...ebSocketServletAutoConfigurationTests.java | 6 +- .../boot/cli/CommandLineIT.java | 72 ++-- .../boot/cli/JarCommandIT.java | 117 +++-- .../boot/cli/WarCommandIT.java | 28 +- .../infrastructure/CommandLineInvoker.java | 12 +- .../boot/cli/ClassLoaderIntegrationTests.java | 21 +- .../springframework/boot/cli/CliTester.java | 95 ++-- .../cli/DirectorySourcesIntegrationTests.java | 27 +- .../boot/cli/GrabCommandIntegrationTests.java | 42 +- .../boot/cli/ReproIntegrationTests.java | 29 +- .../boot/cli/RunCommandIntegrationTests.java | 32 +- .../boot/cli/SampleIntegrationTests.java | 56 +-- .../app/SpringApplicationLauncherTests.java | 18 +- .../CommandRunnerIntegrationTests.java | 23 +- .../boot/cli/command/CommandRunnerTests.java | 40 +- .../command/OptionParsingCommandTests.java | 6 +- .../command/archive/ResourceMatcherTests.java | 20 +- .../EncodePasswordCommandTests.java | 20 +- .../cli/command/init/InitCommandTests.java | 99 ++--- .../init/InitializrServiceMetadataTests.java | 10 +- .../command/init/InitializrServiceTests.java | 24 +- .../init/ProjectGenerationRequestTests.java | 46 +- ...rviceCapabilitiesReportGeneratorTests.java | 10 +- .../GroovyGrabDependencyResolverTests.java | 16 +- .../cli/command/install/InstallerTests.java | 37 +- .../run/SpringApplicationRunnerTests.java | 6 +- ...AwareWhiteSpaceArgumentDelimiterTests.java | 18 +- .../compiler/DependencyCustomizerTests.java | 26 +- .../ExtendedGroovyClassLoaderTests.java | 24 +- .../GenericBomAstTransformationTests.java | 10 +- .../RepositoryConfigurationFactoryTests.java | 14 +- ...endencyCoordinatesTransformationTests.java | 34 +- .../CompositeDependencyManagementTests.java | 18 +- ...ementArtifactCoordinatesResolverTests.java | 14 +- ...DependenciesDependencyManagementTests.java | 10 +- .../grape/AetherGrapeEngineTests.java | 28 +- .../DependencyResolutionContextTests.java | 11 +- .../grape/DetailedProgressReporterTests.java | 12 +- ...rySystemSessionAutoConfigurationTests.java | 12 +- ...rySystemSessionAutoConfigurationTests.java | 14 +- .../boot/cli/util/ResourceUtilsTests.java | 32 +- .../RemoteUrlPropertyExtractorTests.java | 18 +- ...ToolsDataSourceAutoConfigurationTests.java | 10 +- ...ooledDataSourceAutoConfigurationTests.java | 39 +- .../DevToolsPropertiesTests.java | 10 +- .../LocalDevToolsAutoConfigurationTests.java | 50 ++- .../OnEnabledDevToolsConditionTests.java | 12 +- .../OptionalLiveReloadServerTests.java | 8 +- .../RemoteDevToolsAutoConfigurationTests.java | 36 +- .../autoconfigure/TriggerFileFilterTests.java | 28 +- .../classpath/ClassPathChangedEventTests.java | 10 +- .../ClassPathFileChangeListenerTests.java | 16 +- .../ClassPathFileSystemWatcherTests.java | 15 +- .../PatternClassPathRestartStrategyTests.java | 16 +- .../DevToolPropertiesIntegrationTests.java | 22 +- ...ToolsHomePropertiesPostProcessorTests.java | 22 +- .../devtools/filewatch/ChangedFileTests.java | 44 +- .../devtools/filewatch/FileSnapshotTests.java | 30 +- .../filewatch/FileSystemWatcherTests.java | 77 ++-- .../filewatch/FolderSnapshotTests.java | 45 +- .../HttpTunnelIntegrationTests.java | 8 +- .../ConnectionInputStreamTests.java | 12 +- .../ConnectionOutputStreamTests.java | 10 +- .../boot/devtools/livereload/FrameTests.java | 36 +- .../livereload/LiveReloadServerTests.java | 26 +- .../client/ClassPathChangeUploaderTests.java | 28 +- .../client/DelayedLiveReloadTriggerTests.java | 20 +- .../client/HttpHeaderInterceptorTests.java | 18 +- .../RemoteClientConfigurationTests.java | 40 +- .../remote/server/DispatcherFilterTests.java | 16 +- .../remote/server/DispatcherTests.java | 18 +- .../server/HttpHeaderAccessManagerTests.java | 24 +- .../remote/server/HttpStatusHandlerTests.java | 16 +- .../remote/server/UrlHandlerMapperTests.java | 14 +- .../devtools/restart/ChangeableUrlsTests.java | 41 +- ...aderFilesResourcePatternResolverTests.java | 37 +- .../DefaultRestartInitializerTests.java | 20 +- .../devtools/restart/MainMethodTests.java | 16 +- .../boot/devtools/restart/MockRestarter.java | 48 ++- .../OnInitializedRestarterConditionTests.java | 18 +- .../RestartApplicationListenerTests.java | 31 +- .../restart/RestartScopeInitializerTests.java | 6 +- .../boot/devtools/restart/RestarterTests.java | 43 +- .../SilentExitExceptionHandlerTests.java | 12 +- .../classloader/ClassLoaderFileTests.java | 18 +- .../classloader/ClassLoaderFilesTests.java | 30 +- .../classloader/RestartClassLoaderTests.java | 52 ++- .../DefaultSourceFolderUrlFilterTests.java | 12 +- .../server/HttpRestartServerHandlerTests.java | 8 +- .../server/HttpRestartServerTests.java | 18 +- .../restart/server/RestartServerTests.java | 20 +- .../settings/DevToolsSettingsTests.java | 29 +- .../client/HttpTunnelConnectionTests.java | 38 +- .../tunnel/client/TunnelClientTests.java | 16 +- .../HttpTunnelPayloadForwarderTests.java | 12 +- .../payload/HttpTunnelPayloadTests.java | 24 +- .../server/HttpTunnelServerHandlerTests.java | 8 +- .../tunnel/server/HttpTunnelServerTests.java | 48 +-- .../SocketTargetServerConnectionTests.java | 14 +- .../server/StaticPortProviderTests.java | 8 +- .../restassured/UserDocumentationTests.java | 8 +- .../webclient/UsersDocumentationTests.java | 6 +- .../ApplicationArgumentsExampleTests.java | 8 +- .../docs/test/web/MockMvcExampleTests.java | 8 +- .../web/MockWebTestClientExampleTests.java | 8 +- ...andomPortTestRestTemplateExampleTests.java | 11 +- .../RandomPortWebTestClientExampleTests.java | 8 +- .../UserServiceAutoConfigurationTests.java | 10 +- .../SpringApplicationBuilderExampleTests.java | 30 +- .../EnvironmentPostProcessorExampleTests.java | 6 +- ...mcatLegacyCookieProcessorExampleTests.java | 6 +- .../bind/AppSystemPropertiesTests.java | 10 +- .../jdbc/BasicDataSourceExampleTests.java | 12 +- .../CompleteTwoDataSourcesExampleTests.java | 12 +- .../ConfigurableDataSourceExampleTests.java | 12 +- .../jdbc/SimpleDataSourceExampleTests.java | 12 +- .../SimpleTwoDataSourcesExampleTests.java | 12 +- .../boot/docs/jmx/SampleJmxTests.java | 14 +- .../docs/web/client/SampleWebClientTests.java | 12 +- .../PropertiesMigrationListenerTests.java | 21 +- .../PropertiesMigrationReporterTests.java | 20 +- .../spring-boot-test-autoconfigure/pom.xml | 5 + ...gurationContextCustomizerFactoryTests.java | 12 +- ...ListenerPostConstructIntegrationTests.java | 9 +- ...cyInjectionTestExecutionListenerTests.java | 25 +- ...izerFactoryWithAutoConfigurationTests.java | 55 +-- .../AutoConfigureCacheIntegrationTests.java | 9 +- ...hExistingCacheManagerIntegrationTests.java | 9 +- .../jdbc/DataJdbcTestIntegrationTests.java | 17 +- ...ataJdbcTestPropertiesIntegrationTests.java | 11 +- .../ldap/DataLdapTestIntegrationTests.java | 11 +- ...ataLdapTestPropertiesIntegrationTests.java | 11 +- ...TestWithIncludeFilterIntegrationTests.java | 9 +- .../mongo/DataMongoTestIntegrationTests.java | 13 +- ...taMongoTestPropertiesIntegrationTests.java | 11 +- ...DataMongoTestReactiveIntegrationTests.java | 9 +- ...TestWithIncludeFilterIntegrationTests.java | 9 +- .../neo4j/DataNeo4jTestIntegrationTests.java | 16 +- ...taNeo4jTestPropertiesIntegrationTests.java | 14 +- ...TestWithIncludeFilterIntegrationTests.java | 14 +- .../redis/DataRedisTestIntegrationTests.java | 12 +- ...taRedisTestPropertiesIntegrationTests.java | 12 +- ...TestWithIncludeFilterIntegrationTests.java | 12 +- .../filter/FilterAnnotationsTests.java | 14 +- ...eFiltersContextCustomizerFactoryTests.java | 12 +- ...thMultipleDatasourcesIntegrationTests.java | 9 +- ...atabaseWithNoDatabaseIntegrationTests.java | 12 +- .../jdbc/JdbcTestIntegrationTests.java | 17 +- .../JdbcTestPropertiesIntegrationTests.java | 11 +- ...ReplaceAutoConfiguredIntegrationTests.java | 9 +- ...iguredWithoutOverrideIntegrationTests.java | 9 +- ...tabaseReplaceExplicitIntegrationTests.java | 9 +- ...stDatabaseReplaceNoneIntegrationTests.java | 9 +- ...aseReplacePropertyAnyIntegrationTests.java | 9 +- ...ropertyAutoConfiguredIntegrationTests.java | 9 +- ...seReplacePropertyNoneIntegrationTests.java | 9 +- ...TestWithIncludeFilterIntegrationTests.java | 9 +- .../TestDatabaseAutoConfigurationTests.java | 8 +- .../jooq/JooqTestIntegrationTests.java | 17 +- .../JooqTestPropertiesIntegrationTests.java | 11 +- ...ConfigureTestDatabaseIntegrationTests.java | 9 +- .../json/JsonTestIntegrationTests.java | 19 +- .../JsonTestPropertiesIntegrationTests.java | 11 +- ...TestWithAutoConfigureJsonTestersTests.java | 15 +- ...TestWithAutoConfigureJsonTestersTests.java | 9 +- .../orm/jpa/DataJpaTestIntegrationTests.java | 21 +- ...DataJpaTestPropertiesIntegrationTests.java | 11 +- .../orm/jpa/TestEntityManagerTests.java | 44 +- ...igurationEnabledFalseIntegrationTests.java | 12 +- ...figurationEnabledTrueIntegrationTests.java | 12 +- .../AnnotationsPropertySourceTests.java | 40 +- ...yMappingContextCustomizerFactoryTests.java | 16 +- .../properties/PropertyMappingTests.java | 14 +- ...AdvancedConfigurationIntegrationTests.java | 13 +- ...DocsAutoConfigurationIntegrationTests.java | 13 +- ...AdvancedConfigurationIntegrationTests.java | 13 +- ...DocsAutoConfigurationIntegrationTests.java | 13 +- ...AdvancedConfigurationIntegrationTests.java | 13 +- ...DocsAutoConfigurationIntegrationTests.java | 13 +- .../MockMvcSecurityIntegrationTests.java | 13 +- ...iceServerEnabledFalseIntegrationTests.java | 9 +- ...lientWithRestTemplateIntegrationTests.java | 9 +- .../RestClientRestIntegrationTests.java | 13 +- ...ClientTestNoComponentIntegrationTests.java | 11 +- ...tClientTestPropertiesIntegrationTests.java | 11 +- ...ientTestTwoComponentsIntegrationTests.java | 13 +- ...WebFluxTestPropertiesIntegrationTests.java | 11 +- .../WebFluxTypeExcludeFilterTests.java | 14 +- .../WebTestClientAutoConfigurationTests.java | 14 +- ...luxTestAllControllersIntegrationTests.java | 15 +- ...TestAutoConfigurationIntegrationTests.java | 19 +- .../WebFluxTestConverterIntegrationTests.java | 9 +- ...FluxTestMessageSourceIntegrationTests.java | 9 +- ...FluxTestOneControllerIntegrationTests.java | 11 +- ...entCodecCustomizationIntegrationTests.java | 9 +- ...tClientSpringBootTestIntegrationTests.java | 13 +- .../MockMvcAutoConfigurationTests.java | 6 +- ...ringBootMockMvcBuilderCustomizerTests.java | 6 +- ...TestAutoConfigurationIntegrationTests.java | 19 +- .../WebMvcTestPropertiesIntegrationTests.java | 11 +- .../servlet/WebMvcTypeExcludeFilterTests.java | 14 +- ...MockMvcSpringBootTestIntegrationTests.java | 26 +- ...MvcTestAllControllersIntegrationTests.java | 19 +- .../WebMvcTestConverterIntegrationTests.java | 9 +- ...stomDispatcherServletIntegrationTests.java | 11 +- .../WebMvcTestHateoasIntegrationTests.java | 11 +- ...bMvcTestMessageSourceIntegrationTests.java | 9 +- ...bMvcTestOneControllerIntegrationTests.java | 11 +- .../WebMvcTestPageableIntegrationTests.java | 9 +- ...WebMvcTestPrintAlwaysIntegrationTests.java | 20 +- ...ebMvcTestPrintDefaultIntegrationTests.java | 70 ++- ...tPrintDefaultOverrideIntegrationTests.java | 20 +- .../mockmvc/WebMvcTestPrintDefaultRunner.java | 77 ---- ...bMvcTestPrintOverrideIntegrationTests.java | 20 +- ...bMvcTestServletFilterIntegrationTests.java | 9 +- ...rRegistrationDisabledIntegrationTests.java | 9 +- .../WebMvcTestWebClientIntegrationTests.java | 9 +- ...tWebDriverCustomScopeIntegrationTests.java | 17 +- .../WebMvcTestWebDriverIntegrationTests.java | 17 +- ...hAutoConfigureMockMvcIntegrationTests.java | 13 +- .../boot/test/system/OutputCapture.java | 25 +- .../boot/test/system/OutputCaptureRule.java | 2 +- ...stEmbeddedReactiveWebEnvironmentTests.java | 10 +- ...gBootTestWebServerWebEnvironmentTests.java | 10 +- .../context/AnnotatedClassFinderTests.java | 12 +- ...ileApplicationContextInitializerTests.java | 4 +- .../context/FilteredClassLoaderTests.java | 20 +- ...textCustomizerFactoryIntegrationTests.java | 6 +- .../ImportsContextCustomizerFactoryTests.java | 16 +- .../ImportsContextCustomizerTests.java | 12 +- .../SpringBootContextLoaderMockMvcTests.java | 6 +- .../context/SpringBootContextLoaderTests.java | 16 +- .../SpringBootTestActiveProfileTests.java | 4 +- .../test/context/SpringBootTestArgsTests.java | 4 +- .../SpringBootTestContextHierarchyTests.java | 4 +- .../SpringBootTestCustomConfigNameTests.java | 4 +- .../SpringBootTestCustomPortTests.java | 4 +- ...ringBootTestDefaultConfigurationTests.java | 4 +- ...pringBootTestGroovyConfigurationTests.java | 4 +- ...estGroovyConventionConfigurationTests.java | 4 +- .../test/context/SpringBootTestJmxTests.java | 4 +- ...SpringBootTestMixedConfigurationTests.java | 4 +- ...nmentUserDefinedTestRestTemplateTests.java | 4 +- ...tTestUserDefinedTestRestTemplateTests.java | 4 +- ...stWebEnvironmentContextHierarchyTests.java | 4 +- ...SpringBootTestWebEnvironmentMockTests.java | 10 +- ...nmentMockWithWebAppConfigurationTests.java | 4 +- ...bEnvironmentRandomPortCustomPortTests.java | 4 +- ...BootTestWebEnvironmentRandomPortTests.java | 4 +- ...ngBootTestWithClassesIntegrationTests.java | 4 +- ...hContextConfigurationIntegrationTests.java | 4 +- ...ngBootTestWithTestPropertySourceTests.java | 14 +- ...otTestXmlConventionConfigurationTests.java | 4 +- ...ApplicationContextAssertProviderTests.java | 38 +- .../ApplicationContextAssertTests.java | 102 ++--- .../AssertableApplicationContextTests.java | 4 +- ...bleReactiveWebApplicationContextTests.java | 4 +- .../AssertableWebApplicationContextTests.java | 4 +- ...stContextBootstrapperIntegrationTests.java | 10 +- ...pringBootTestContextBootstrapperTests.java | 6 +- ...strapperWithContextConfigurationTests.java | 6 +- ...textBootstrapperWithInitializersTests.java | 4 +- .../test/context/example/ExampleConfig.java | 5 +- .../test/context/example/scan/Example.java | 6 +- .../example/scan/sub/SubExampleConfig.java | 5 +- .../filter/JupiterRepeatedTestExample.java | 4 +- .../context/filter/JupiterTestExample.java | 4 +- .../filter/JupiterTestFactoryExample.java | 4 +- .../filter/TestTypeExcludeFilterTests.java | 22 +- ...AbstractApplicationContextRunnerTests.java | 36 +- .../WebApplicationContextRunnerTests.java | 4 +- .../json/AbstractJsonMarshalTesterTests.java | 34 +- .../boot/test/json/BasicJsonTesterTests.java | 18 +- .../test/json/GsonTesterIntegrationTests.java | 10 +- .../boot/test/json/GsonTesterTests.java | 8 +- .../json/JacksonTesterIntegrationTests.java | 18 +- .../boot/test/json/JacksonTesterTests.java | 8 +- .../test/json/JsonContentAssertTests.java | 402 ++++++++--------- .../boot/test/json/JsonContentTests.java | 18 +- .../boot/test/json/JsonbTesterTests.java | 8 +- .../test/json/ObjectContentAssertTests.java | 14 +- .../boot/test/json/ObjectContentTests.java | 14 +- .../mock/mockito/DefinitionsParserTests.java | 34 +- ...ockBeanForBeanFactoryIntegrationTests.java | 4 +- ...nClassForExistingBeanIntegrationTests.java | 4 +- ...rationClassForNewBeanIntegrationTests.java | 4 +- ...nFieldForExistingBeanIntegrationTests.java | 4 +- ...rationFieldForNewBeanIntegrationTests.java | 4 +- ...eanOnContextHierarchyIntegrationTests.java | 4 +- .../mockito/MockBeanOnScopedProxyTests.java | 4 +- ...tClassForExistingBeanIntegrationTests.java | 4 +- ...OnTestClassForNewBeanIntegrationTests.java | 4 +- ...dForExistingBeanCacheIntegrationTests.java | 4 +- ...tFieldForExistingBeanIntegrationTests.java | 4 +- ...tingBeanWithQualifierIntegrationTests.java | 6 +- ...OnTestFieldForNewBeanIntegrationTests.java | 4 +- .../mockito/MockBeanWithAopProxyTests.java | 4 +- ...hAsyncInterfaceMethodIntegrationTests.java | 4 +- ...ClassModeBeforeMethodIntegrationTests.java | 4 +- ...OnTestFieldForNewBeanIntegrationTests.java | 4 +- ...BeanWithInjectedFieldIntegrationTests.java | 4 +- .../mock/mockito/MockDefinitionTests.java | 10 +- .../test/mock/mockito/MockResetTests.java | 14 +- .../MockitoContextCustomizerFactoryTests.java | 8 +- .../MockitoContextCustomizerTests.java | 4 +- .../mockito/MockitoPostProcessorTests.java | 16 +- .../MockitoTestExecutionListenerTests.java | 10 +- .../mockito/QualifierDefinitionTests.java | 16 +- .../ResetMocksTestExecutionListenerTests.java | 12 +- ...nClassForExistingBeanIntegrationTests.java | 4 +- ...rationClassForNewBeanIntegrationTests.java | 4 +- ...nFieldForExistingBeanIntegrationTests.java | 4 +- ...rationFieldForNewBeanIntegrationTests.java | 4 +- ...eanOnContextHierarchyIntegrationTests.java | 4 +- ...tClassForExistingBeanIntegrationTests.java | 4 +- ...OnTestClassForNewBeanIntegrationTests.java | 4 +- ...dForExistingBeanCacheIntegrationTests.java | 4 +- ...tFieldForExistingBeanIntegrationTests.java | 4 +- ...tingBeanWithQualifierIntegrationTests.java | 6 +- ...orExistingGenericBeanIntegrationTests.java | 4 +- ...ngBeansWithOnePrimaryIntegrationTests.java | 4 +- ...OnTestFieldForNewBeanIntegrationTests.java | 4 +- ...thAopProxyAndNotProxyTargetAwareTests.java | 4 +- .../mockito/SpyBeanWithAopProxyTests.java | 4 +- ...ClassModeBeforeMethodIntegrationTests.java | 4 +- ...estFieldForMultipleExistingBeansTests.java | 4 +- .../test/mock/mockito/SpyDefinitionTests.java | 16 +- .../SpringBootMockServletContextTests.java | 6 +- .../ApplicationContextTestUtilsTests.java | 8 +- .../test/util/TestPropertyValuesTests.java | 22 +- ...ndomPortEnvironmentPostProcessorTests.java | 30 +- .../LocalHostUriTemplateHandlerTests.java | 18 +- ...MockServerRestTemplateCustomizerTests.java | 28 +- ...RootUriRequestExpectationManagerTests.java | 28 +- ...lateContextCustomizerIntegrationTests.java | 4 +- ...estRestTemplateContextCustomizerTests.java | 4 +- ...ContextCustomizerWithFactoryBeanTests.java | 4 +- ...ustomizerWithOverrideIntegrationTests.java | 4 +- .../web/client/TestRestTemplateTests.java | 58 +-- .../web/htmlunit/LocalHostWebClientTests.java | 8 +- ...lHostWebConnectionHtmlUnitDriverTests.java | 14 +- ...ientContextCustomizerIntegrationTests.java | 4 +- ...ustomizerWithOverrideIntegrationTests.java | 4 +- ...AutoConfigureAnnotationProcessorTests.java | 26 +- .../CompoundConfigurationTableEntryTests.java | 2 +- .../ConfigurationTableTests.java | 2 +- .../SingleConfigurationTableEntryTests.java | 2 +- ...ionMetadataRepositoryJsonBuilderTests.java | 22 +- .../JsonReaderTests.java | 20 +- .../SentenceExtractorTests.java | 16 +- .../AbstractMetadataGenerationTests.java | 14 +- ...ationMetadataAnnotationProcessorTests.java | 58 +-- ...uctorParameterPropertyDescriptorTests.java | 30 +- .../EndpointMetadataGenerationTests.java | 28 +- .../GenericsMetadataGenerationTests.java | 14 +- ...ablePropertiesMetadataGenerationTests.java | 6 +- ...crementalBuildMetadataGenerationTests.java | 16 +- .../JavaBeanPropertyDescriptorTests.java | 36 +- .../LombokMetadataGenerationTests.java | 22 +- .../LombokPropertyDescriptorTests.java | 42 +- .../MergeMetadataGenerationTests.java | 32 +- .../MetadataStoreTests.java | 27 +- .../MethodBasedMetadataGenerationTests.java | 16 +- .../PropertyDescriptorResolverTests.java | 28 +- .../PropertyDescriptorTests.java | 10 +- .../configurationprocessor/TestProject.java | 16 +- .../TypeUtilsTests.java | 20 +- .../AbstractFieldValuesProcessorTests.java | 14 +- ...JavaCompilerFieldValuesProcessorTests.java | 7 +- .../metadata/ConfigurationMetadataTests.java | 24 +- .../metadata/ItemMetadataTests.java | 10 +- .../metadata/JsonMarshallerTests.java | 10 +- ...anagingDependenciesDocumentationTests.java | 11 +- .../tools/DefaultLaunchScriptTests.java | 81 ++-- .../boot/loader/tools/FileUtilsTests.java | 35 +- .../boot/loader/tools/LayoutsTests.java | 14 +- .../loader/tools/MainClassFinderTests.java | 45 +- .../boot/loader/tools/RepackagerTests.java | 163 +++---- .../boot/loader/tools/TestJarFile.java | 11 +- .../tools/ZipHeaderPeekInputStreamTests.java | 22 +- ...bstractExecutableArchiveLauncherTests.java | 12 +- .../boot/loader/JarLauncherTests.java | 8 +- .../loader/LaunchedURLClassLoaderTests.java | 27 +- .../boot/loader/PropertiesLauncherTests.java | 95 ++-- .../boot/loader/WarLauncherTests.java | 8 +- .../loader/archive/ExplodedArchiveTests.java | 44 +- .../loader/archive/JarFileArchiveTests.java | 39 +- .../data/RandomAccessDataFileTests.java | 82 ++-- .../boot/loader/jar/AsciiBytesTests.java | 46 +- .../jar/CentralDirectoryParserTests.java | 22 +- .../boot/loader/jar/HandlerTests.java | 49 +-- .../boot/loader/jar/JarFileTests.java | 95 ++-- .../loader/jar/JarURLConnectionTests.java | 58 ++- .../boot/loader/jar/StringSequenceTests.java | 60 +-- .../loader/util/SystemPropertyUtilsTests.java | 24 +- .../boot/maven/ArtifactsLibrariesTests.java | 14 +- .../boot/maven/DependencyFilterMojoTests.java | 14 +- .../boot/maven/EnvVariablesTests.java | 10 +- .../boot/maven/ExcludeFilterTests.java | 18 +- .../boot/maven/IncludeFilterTests.java | 18 +- ...ertiesMergingResourceTransformerTests.java | 10 +- .../boot/maven/RunArgumentsTests.java | 22 +- .../maven/SystemPropertyFormatterTests.java | 14 +- .../spring-boot-test-support/pom.xml | 5 + .../boot/testsupport/Assume.java | 38 -- .../testsupport/compiler/TestCompiler.java | 11 +- .../AbstractConfigurationClassTests.java | 2 +- .../boot/testsupport/rule/OutputCapture.java | 156 ------- .../testsupport/system/CapturedOutput.java | 71 +++ .../testsupport/system/OutputCapture.java | 273 ++++++++++++ .../system/OutputCaptureExtension.java | 98 +++++ .../testsupport/system/OutputCaptureRule.java | 80 ++++ .../{rule => system}/package-info.java | 6 +- .../testsupport/testcontainers/Container.java | 91 ---- .../DisabledWithoutDockerTestcontainers.java | 39 ++ .../DockerIsAvailableCondition.java | 43 ++ .../ElasticsearchContainer.java | 53 --- .../testcontainers/RedisContainer.java | 5 +- .../testcontainers/SkippableContainer.java | 75 ---- .../testcontainers/package-info.java | 20 - .../testsupport/assertj/MatchedTests.java | 14 +- .../springframework/boot/AdhocTestSuite.java | 34 -- .../org/springframework/boot/BannerTests.java | 39 +- .../boot/BeanDefinitionLoaderTests.java | 34 +- .../DefaultApplicationArgumentsTests.java | 18 +- .../boot/EnvironmentConverterTests.java | 18 +- .../boot/ExitCodeGeneratorsTests.java | 18 +- .../boot/ImageBannerTests.java | 40 +- .../boot/OverrideSourcesTests.java | 12 +- .../org/springframework/boot/ReproTests.java | 32 +- .../boot/ResourceBannerTests.java | 24 +- .../springframework/boot/SimpleMainTests.java | 35 +- .../boot/SpringApplicationTests.java | 216 +++++----- .../boot/SpringBootConfigurationTests.java | 8 +- .../boot/SpringBootExceptionHandlerTests.java | 10 +- .../boot/StartUpLoggerTests.java | 6 +- ...gApplicationAdminMXBeanRegistrarTests.java | 20 +- .../boot/ansi/AnsiColorsTests.java | 10 +- .../boot/ansi/AnsiOutputTests.java | 14 +- .../boot/ansi/AnsiPropertySourceTests.java | 22 +- .../SpringApplicationBuilderTests.java | 48 +-- .../boot/cloud/CloudPlatformTests.java | 20 +- ...ndryVcapEnvironmentPostProcessorTests.java | 16 +- .../ApplicationPidFileWriterTests.java | 62 +-- ...ngsApplicationContextInitializerTests.java | 49 ++- ...tIdApplicationContextInitializerTests.java | 18 +- .../FileEncodingApplicationListenerTests.java | 10 +- .../boot/context/TypeExcludeFilterTests.java | 10 +- .../annotation/ConfigurationsTests.java | 10 +- .../annotation/UserConfigurationsTests.java | 6 +- .../AnsiOutputApplicationListenerTests.java | 18 +- .../ConfigFileApplicationListenerTests.java | 189 ++++---- ...ationListenerYamlProfileNegationTests.java | 26 +- ...ingApplicationContextInitializerTests.java | 16 +- .../DelegatingApplicationListenerTests.java | 14 +- ...ngApplicationListenerIntegrationTests.java | 19 +- .../LoggingApplicationListenerTests.java | 6 +- ...igurationPropertiesBeanRegistrarTests.java | 17 +- ...tionPropertiesBindHandlerAdvisorTests.java | 12 +- ...igurationPropertiesScanRegistrarTests.java | 18 +- .../ConfigurationPropertiesScanTests.java | 20 +- .../ConfigurationPropertiesTests.java | 165 ++++--- .../properties/PropertyMapperTests.java | 82 ++-- .../properties/bind/ArrayBinderTests.java | 52 +-- ...ckCompatibilityBinderIntegrationTests.java | 8 +- .../bind/BeanPropertyNameTests.java | 8 +- .../properties/bind/BindConverterTests.java | 46 +- .../properties/bind/BindResultTests.java | 52 +-- .../properties/bind/BindableTests.java | 40 +- .../context/properties/bind/BinderTests.java | 60 ++- .../bind/CollectionBinderTests.java | 80 ++-- .../ConstructorParametersBinderTests.java | 30 +- .../properties/bind/JavaBeanBinderTests.java | 92 ++-- .../properties/bind/MapBinderTests.java | 96 ++--- ...pertySourcesPlaceholdersResolverTests.java | 14 +- .../handler/IgnoreErrorsBindHandlerTests.java | 12 +- ...evelConverterNotFoundBindHandlerTests.java | 16 +- .../NoUnboundElementsBindHandlerTests.java | 18 +- .../test/PackagePrivateBeanBindingTests.java | 10 +- .../BindValidationExceptionTests.java | 8 +- .../OriginTrackedFieldErrorTests.java | 12 +- .../ValidationBindHandlerTests.java | 30 +- .../validation/ValidationErrorsTests.java | 20 +- ...iasedConfigurationPropertySourceTests.java | 18 +- ...rableConfigurationPropertySourceTests.java | 6 +- ...ConfigurationPropertyNameAliasesTests.java | 24 +- .../ConfigurationPropertyNameTests.java | 140 +++--- ...ionPropertySourcesPropertySourceTests.java | 20 +- .../ConfigurationPropertySourcesTests.java | 18 +- .../ConfigurationPropertyStateTests.java | 12 +- .../source/ConfigurationPropertyTests.java | 18 +- .../source/DefaultPropertyMapperTests.java | 8 +- ...redConfigurationPropertiesSourceTests.java | 16 +- ...bleConfigurationPropertiesSourceTests.java | 8 +- .../MapConfigurationPropertySourceTests.java | 20 +- ...pringConfigurationPropertySourceTests.java | 24 +- ...ringConfigurationPropertySourcesTests.java | 24 +- ...rableConfigurationPropertySourceTests.java | 24 +- .../SystemEnvironmentPropertyMapperTests.java | 12 +- .../UnboundElementsSourceFilterTests.java | 16 +- .../ArrayToDelimitedStringConverterTests.java | 70 ++- .../boot/convert/CharArrayFormatterTests.java | 35 +- ...ectionToDelimitedStringConverterTests.java | 69 ++- .../convert/ConversionServiceArguments.java | 99 +++++ .../convert/ConversionServiceParameters.java | 70 --- .../boot/convert/ConversionServiceTest.java | 44 ++ .../DelimitedStringToArrayConverterTests.java | 91 ++-- ...mitedStringToCollectionConverterTests.java | 109 ++--- .../boot/convert/DurationStyleTests.java | 56 +-- .../DurationToNumberConverterTests.java | 38 +- .../DurationToStringConverterTests.java | 38 +- .../convert/InetAddressFormatterTests.java | 63 ++- .../boot/convert/IsoOffsetFormatterTests.java | 32 +- .../NumberToDataSizeConverterTests.java | 47 +- .../NumberToDurationConverterTests.java | 48 +-- .../StringToDataSizeConverterTests.java | 111 +++-- .../StringToDurationConverterTests.java | 170 ++++---- ...EnumIgnoringCaseConverterFactoryTests.java | 71 ++- .../FailureAnalyzersIntegrationTests.java | 17 +- .../diagnostics/FailureAnalyzersTests.java | 18 +- ...rrentlyInCreationFailureAnalyzerTests.java | 14 +- ...efinitionOverrideFailureAnalyzerTests.java | 6 +- ...NotOfRequiredTypeFailureAnalyzerTests.java | 8 +- .../analyzer/BindFailureAnalyzerTests.java | 14 +- .../BindValidationFailureAnalyzerTests.java | 20 +- ...urationPropertiesFailureAnalyzerTests.java | 6 +- ...ationPropertyNameFailureAnalyzerTests.java | 6 +- ...tionPropertyValueFailureAnalyzerTests.java | 14 +- ...queBeanDefinitionFailureAnalyzerTests.java | 16 +- ...igurationPropertyFailureAnalyzerTests.java | 14 +- .../OriginTrackedMapPropertySourceTests.java | 16 +- .../OriginTrackedPropertiesLoaderTests.java | 62 +-- .../env/OriginTrackedYamlLoaderTests.java | 20 +- .../PropertiesPropertySourceLoaderTests.java | 10 +- .../env/RandomValuePropertySourceTests.java | 26 +- ...tionJsonEnvironmentPostProcessorTests.java | 24 +- ...tySourceEnvironmentPostProcessorTests.java | 20 +- .../env/YamlPropertySourceLoaderTests.java | 14 +- .../boot/info/BuildPropertiesTests.java | 8 +- .../boot/info/GitPropertiesTests.java | 20 +- .../boot/info/InfoPropertiesTests.java | 12 +- .../jackson/JsonComponentModuleTests.java | 24 +- .../jackson/JsonObjectDeserializerTests.java | 38 +- .../jackson/JsonObjectSerializerTests.java | 8 +- .../boot/jdbc/DataSourceBuilderTests.java | 16 +- .../boot/jdbc/DataSourceUnwrapperTests.java | 20 +- .../jdbc/DatabaseDriverClassNameTests.java | 67 ++- .../boot/jdbc/DatabaseDriverTests.java | 18 +- .../jdbc/EmbeddedDatabaseConnectionTests.java | 14 +- .../AbstractDataSourcePoolMetadataTests.java | 18 +- ...mmonsDbcp2DataSourcePoolMetadataTests.java | 18 +- ...teDataSourcePoolMetadataProviderTests.java | 10 +- .../HikariDataSourcePoolMetadataTests.java | 9 +- .../TomcatDataSourcePoolMetadataTests.java | 9 +- .../boot/json/AbstractJsonParserTests.java | 44 +- .../boot/json/JacksonJsonParserTests.java | 8 +- .../AtomikosConnectionFactoryBeanTests.java | 6 +- .../atomikos/AtomikosDataSourceBeanTests.java | 8 +- ...ependsOnBeanFactoryPostProcessorTests.java | 6 +- .../jta/atomikos/AtomikosPropertiesTests.java | 8 +- ...omikosXAConnectionFactoryWrapperTests.java | 6 +- .../AtomikosXADataSourceWrapperTests.java | 6 +- ...ependentBeanFactoryPostProcessorTests.java | 6 +- ...tronixXAConnectionFactoryWrapperTests.java | 6 +- .../BitronixXADataSourceWrapperTests.java | 6 +- .../PoolingConnectionFactoryBeanTests.java | 14 +- .../bitronix/PoolingDataSourceBeanTests.java | 14 +- ...erviceLocatorApplicationListenerTests.java | 12 +- .../SpringPackageScanClassResolverTests.java | 6 +- .../boot/logging/DeferredLogTests.java | 44 +- .../boot/logging/LogFileTests.java | 18 +- .../LoggerConfigurationComparatorTests.java | 18 +- .../logging/LoggingSystemPropertiesTests.java | 22 +- .../boot/logging/LoggingSystemTests.java | 14 +- .../logging/java/JavaLoggingSystemTests.java | 4 +- .../logging/log4j2/ColorConverterTests.java | 48 +-- ...tespaceThrowablePatternConverterTests.java | 8 +- .../log4j2/Log4J2LoggingSystemTests.java | 4 +- .../SpringBootConfigurationFactoryTests.java | 6 +- ...tespaceThrowablePatternConverterTests.java | 8 +- .../logging/logback/ColorConverterTests.java | 47 +- ...hitespaceThrowableProxyConverterTests.java | 10 +- .../logback/LogbackConfigurationTests.java | 8 +- .../logback/LogbackLoggingSystemTests.java | 4 +- .../SpringBootJoranConfiguratorTests.java | 80 ++-- .../logback/SpringProfileActionTests.java | 16 +- ...hitespaceThrowableProxyConverterTests.java | 10 +- .../boot/origin/OriginLookupTests.java | 14 +- .../boot/origin/OriginTests.java | 16 +- .../boot/origin/OriginTrackedValueTests.java | 16 +- .../origin/PropertySourceOriginTests.java | 22 +- .../origin/SystemEnvironmentOriginTests.java | 12 +- .../boot/origin/TextResourceOriginTests.java | 28 +- .../SpringPhysicalNamingStrategyTests.java | 12 +- .../netty/NettyRSocketServerFactoryTests.java | 19 +- ...nContextServerWebExchangeMatcherTests.java | 14 +- ...ApplicationContextRequestMatcherTests.java | 12 +- .../boot/system/ApplicationPidTests.java | 29 +- .../boot/system/ApplicationTempTests.java | 12 +- .../boot/system/JavaVersionTests.java | 26 +- .../boot/task/TaskExecutorBuilderTests.java | 30 +- .../boot/task/TaskSchedulerBuilderTests.java | 28 +- ...enceCachingMetadataReaderFactoryTests.java | 10 +- .../boot/util/LambdaSafeTests.java | 68 +-- .../MessageInterpolatorFactoryTests.java | 8 +- ...ticationClientHttpRequestFactoryTests.java | 12 +- .../web/client/RestTemplateBuilderTests.java | 126 +++--- .../client/RootUriTemplateHandlerTests.java | 22 +- .../context/WebServerPortFileWriterTest.java | 41 +- .../JettyReactiveWebServerFactoryTests.java | 16 +- .../JettyServletWebServerFactoryTests.java | 38 +- .../jetty/SslServerCustomizerTests.java | 12 +- .../NettyReactiveWebServerFactoryTests.java | 10 +- .../netty/SslServerCustomizerTests.java | 10 +- .../CompressionConnectorCustomizerTests.java | 10 +- .../tomcat/SslConnectorCustomizerTests.java | 38 +- .../TomcatEmbeddedWebappClassLoaderTests.java | 17 +- .../TomcatReactiveWebServerFactoryTests.java | 28 +- .../TomcatServletWebServerFactoryTests.java | 94 ++-- .../undertow/FileSessionPersistenceTests.java | 27 +- .../undertow/JarResourceManagerTests.java | 28 +- .../undertow/SslBuilderCustomizerTests.java | 12 +- ...UndertowReactiveWebServerFactoryTests.java | 25 +- .../UndertowServletWebServerFactoryTests.java | 42 +- ...ctiveWebServerApplicationContextTests.java | 16 +- ...ricReactiveWebApplicationContextTests.java | 6 +- ...tiveWebServerApplicationConfiguration.java | 3 +- .../error/DefaultErrorAttributesTests.java | 34 +- .../view/MustacheViewResolverTests.java | 12 +- .../result/view/MustacheViewTests.java | 10 +- ...AbstractReactiveWebServerFactoryTests.java | 37 +- .../boot/web/server/CompressionTests.java | 10 +- .../boot/web/server/LocalServerPortTests.java | 12 +- .../boot/web/server/MimeMappingsTests.java | 26 +- ...ctoryCustomizerBeanPostProcessorTests.java | 26 +- .../AbstractFilterRegistrationBeanTests.java | 38 +- ...atingFilterProxyRegistrationBeanTests.java | 16 +- .../servlet/FilterRegistrationBeanTests.java | 12 +- .../FilterRegistrationIntegrationTests.java | 12 +- .../servlet/MultipartConfigFactoryTests.java | 10 +- .../ServletComponentScanIntegrationTests.java | 12 +- .../ServletComponentScanRegistrarTests.java | 26 +- .../ServletContextInitializerBeansTests.java | 10 +- .../ServletListenerRegistrationBeanTests.java | 14 +- .../servlet/ServletRegistrationBeanTests.java | 36 +- .../web/servlet/WebFilterHandlerTests.java | 22 +- .../web/servlet/WebListenerHandlerTests.java | 6 +- .../web/servlet/WebServletHandlerTests.java | 18 +- ...rvletWebServerApplicationContextTests.java | 26 +- ...rvletWebServerApplicationContextTests.java | 75 ++-- .../ServletWebServerMvcIntegrationTests.java | 16 +- ...rvletWebServerApplicationContextTests.java | 16 +- ...vletWebServerApplicationConfiguration.java | 3 +- .../error/DefaultErrorAttributesTests.java | 34 +- .../AbstractServletWebServerFactoryTests.java | 172 ++++---- .../web/servlet/server/DocumentRootTests.java | 29 +- .../server/StaticResourceJarsTests.java | 23 +- .../ErrorPageFilterIntegrationTests.java | 18 +- .../servlet/support/ErrorPageFilterTests.java | 69 ++- ...extApplicationContextInitializerTests.java | 10 +- .../SpringBootServletInitializerTests.java | 37 +- .../view/MustacheViewResolverTests.java | 14 +- .../web/servlet/view/MustacheViewTests.java | 10 +- ...tpWebServiceMessageSenderBuilderTests.java | 10 +- .../WebServiceTemplateBuilderTests.java | 80 ++-- .../boot/SpringApplicationExtensionsTests.kt | 2 +- ...nfigurationPropertiesBeanRegistrarTests.kt | 2 +- .../KotlinConstructorParametersBinderTests.kt | 2 +- ...mpleIntegrationParentApplicationTests.java | 2 +- .../SampleGlassfishDeployApplicationIT.java | 2 +- .../SampleTomcatDeployApplicationIT.java | 2 +- .../SampleTomEEDeployApplicationIT.java | 2 +- .../SampleWildFlyDeployApplicationIT.java | 2 +- .../sample/SampleWlpDeployApplicationIT.java | 2 +- ...onfigurationProcessorIntegrationTests.java | 10 +- .../tests/DevToolsIntegrationTests.java | 86 ++-- ...ithLazyInitializationIntegrationTests.java | 48 +-- .../boot/devtools/tests/Directories.java | 12 +- .../boot/devtools/tests/JvmLauncher.java | 15 +- .../Hibernate52ApplicationTests.java | 7 +- .../launchscript/SysVinitLaunchScriptIT.java | 406 +++++++++--------- .../embedded/AbstractApplicationLauncher.java | 17 +- ...eddedServletContainerIntegrationTests.java | 118 ----- .../context/embedded/ApplicationBuilder.java | 18 +- ...verContainerInvocationContextProvider.java | 189 ++++++++ ...ntainerJarDevelopmentIntegrationTests.java | 36 +- ...ContainerJarPackagingIntegrationTests.java | 54 +-- .../EmbeddedServletContainerTest.java | 39 ++ ...ntainerWarDevelopmentIntegrationTests.java | 42 +- ...ContainerWarPackagingIntegrationTests.java | 63 ++- 1320 files changed, 13424 insertions(+), 14185 deletions(-) delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/AdhocTestSuite.java delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java rename spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/{ContextFactory.java => WebEndpointTest.java} (50%) create mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java delete mode 100644 spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java delete mode 100644 spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java delete mode 100644 spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java create mode 100644 spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/LocalCouchbaseServer.java delete mode 100644 spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultRunner.java delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/Assume.java delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/OutputCapture.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/CapturedOutput.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureExtension.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureRule.java rename spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/{rule => system}/package-info.java (77%) delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DisabledWithoutDockerTestcontainers.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DockerIsAvailableCondition.java delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java delete mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/package-info.java delete mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AdhocTestSuite.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java delete mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java create mode 100644 spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceTest.java delete mode 100644 spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java create mode 100644 spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java create mode 100644 spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerTest.java diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java index f9b41a7e397..90b536d702f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java @@ -41,7 +41,7 @@ import org.springframework.context.ConfigurableApplicationContext; * * @author Dave Syer */ -public class SpringApplicationHierarchyTests { +class SpringApplicationHierarchyTests { private ConfigurableApplicationContext context; @@ -51,14 +51,14 @@ public class SpringApplicationHierarchyTests { } @Test - public void testParent() { + void testParent() { SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class); builder.parent(Parent.class); this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); } @Test - public void testChild() { + void testChild() { SpringApplicationBuilder builder = new SpringApplicationBuilder(Parent.class); builder.child(Child.class); this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java index 1d171fdb553..9d8fca1a20b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfigurationTests.java @@ -32,20 +32,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class RabbitHealthIndicatorAutoConfigurationTests { +class RabbitHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RabbitHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java index c67b40eabe0..246a1041ef4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java @@ -44,18 +44,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic * @author Madhura Bhave */ -public class AuditAutoConfigurationTests { +class AuditAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); @Test - public void autoConfigurationIsDisabledByDefault() { + void autoConfigurationIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditAutoConfiguration.class)); } @Test - public void autoConfigurationIsEnabledWhenAuditEventRepositoryBeanPresent() { + void autoConfigurationIsEnabledWhenAuditEventRepositoryBeanPresent() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class).run((context) -> { assertThat(context.getBean(AuditEventRepository.class)).isNotNull(); assertThat(context.getBean(AuthenticationAuditListener.class)).isNotNull(); @@ -64,7 +64,7 @@ public class AuditAutoConfigurationTests { } @Test - public void ownAuthenticationAuditListener() { + void ownAuthenticationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) @@ -72,7 +72,7 @@ public class AuditAutoConfigurationTests { } @Test - public void ownAuthorizationAuditListener() { + void ownAuthorizationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) @@ -80,7 +80,7 @@ public class AuditAutoConfigurationTests { } @Test - public void ownAuditListener() { + void ownAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withUserConfiguration(CustomAuditListenerConfiguration.class) .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) @@ -88,7 +88,7 @@ public class AuditAutoConfigurationTests { } @Test - public void backsOffWhenDisabled() { + void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withPropertyValues("management.auditevents.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java index 68d2bc210ca..37cef322bdc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java @@ -34,31 +34,31 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Vedran Pavic */ -public class AuditEventsEndpointAutoConfigurationTests { +class AuditEventsEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(AuditAutoConfiguration.class, AuditEventsEndpointAutoConfiguration.class)); @Test - public void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { + void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=auditevents") .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); } @Test - public void endpointBacksOffWhenRepositoryNotAvailable() { + void endpointBacksOffWhenRepositoryNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents") .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) .withPropertyValues("management.endpoint.auditevents.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java index 565e3bbda16..3f1186b275f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java @@ -29,24 +29,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class BeansEndpointAutoConfigurationTests { +class BeansEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans") .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java index 15c5f1f21e6..8c1bb8e4267 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java @@ -32,32 +32,32 @@ import static org.mockito.Mockito.mock; * @author Johannes Edmeier * @author Stephane Nicoll */ -public class CachesEndpointAutoConfigurationTests { +class CachesEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .withPropertyValues("management.endpoints.web.exposure.include=caches") .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test - public void runWithoutCacheManagerShouldHaveEndpointBean() { + void runWithoutCacheManagerShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") .withBean(CacheManager.class, () -> mock(CacheManager.class)) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java index ce89d84f093..d3b9422f826 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java @@ -36,20 +36,20 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class CassandraHealthIndicatorAutoConfigurationTests { +class CassandraHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class, CassandraHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(CassandraHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java index dab6f68778c..1e9aaa9dc23 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthIndicatorAutoConfigurationTests.java @@ -35,7 +35,7 @@ import static org.mockito.Mockito.mock; * @author Artsiom Yudovin * @author Stephane Nicoll */ -public class CassandraReactiveHealthIndicatorAutoConfigurationTests { +class CassandraReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) @@ -43,13 +43,13 @@ public class CassandraReactiveHealthIndicatorAutoConfigurationTests { HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraReactiveHealthIndicator.class) .doesNotHaveBean(CassandraHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(CassandraReactiveHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AccessLevelTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AccessLevelTests.java index 856955f0fc2..d0ae35b9bbd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AccessLevelTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AccessLevelTests.java @@ -25,28 +25,28 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class AccessLevelTests { +class AccessLevelTests { @Test - public void accessToHealthEndpointShouldNotBeRestricted() { + void accessToHealthEndpointShouldNotBeRestricted() { assertThat(AccessLevel.RESTRICTED.isAccessAllowed("health")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("health")).isTrue(); } @Test - public void accessToInfoEndpointShouldNotBeRestricted() { + void accessToInfoEndpointShouldNotBeRestricted() { assertThat(AccessLevel.RESTRICTED.isAccessAllowed("info")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("info")).isTrue(); } @Test - public void accessToDiscoveryEndpointShouldNotBeRestricted() { + void accessToDiscoveryEndpointShouldNotBeRestricted() { assertThat(AccessLevel.RESTRICTED.isAccessAllowed("")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue(); } @Test - public void accessToAnyOtherEndpointShouldBeRestricted() { + void accessToAnyOtherEndpointShouldBeRestricted() { assertThat(AccessLevel.RESTRICTED.isAccessAllowed("env")).isFalse(); assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java index 2976bcf1054..7ac36ae23e3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java @@ -28,51 +28,51 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CloudFoundryAuthorizationExceptionTests { +class CloudFoundryAuthorizationExceptionTests { @Test - public void statusCodeForInvalidTokenReasonShouldBe401() { + void statusCodeForInvalidTokenReasonShouldBe401() { assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForInvalidIssuerReasonShouldBe401() { + void statusCodeForInvalidIssuerReasonShouldBe401() { assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForInvalidAudienceReasonShouldBe401() { + void statusCodeForInvalidAudienceReasonShouldBe401() { assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForInvalidSignatureReasonShouldBe401() { + void statusCodeForInvalidSignatureReasonShouldBe401() { assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForMissingAuthorizationReasonShouldBe401() { + void statusCodeForMissingAuthorizationReasonShouldBe401() { assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { + void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForTokenExpiredReasonShouldBe401() { + void statusCodeForTokenExpiredReasonShouldBe401() { assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test - public void statusCodeForAccessDeniedReasonShouldBe403() { + void statusCodeForAccessDeniedReasonShouldBe403() { assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test - public void statusCodeForServiceUnavailableReasonShouldBe503() { + void statusCodeForServiceUnavailableReasonShouldBe503() { assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode()) .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java index bb51b9f216a..0c07bb18007 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryEndpointFilterTests.java @@ -29,19 +29,19 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class CloudFoundryEndpointFilterTests { +class CloudFoundryEndpointFilterTests { private CloudFoundryEndpointFilter filter = new CloudFoundryEndpointFilter(); @Test - public void matchIfDiscovererCloudFoundryShouldReturnFalse() { + void matchIfDiscovererCloudFoundryShouldReturnFalse() { DiscoveredEndpoint endpoint = mock(DiscoveredEndpoint.class); given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(true); assertThat(this.filter.match(endpoint)).isTrue(); } @Test - public void matchIfDiscovererNotCloudFoundryShouldReturnFalse() { + void matchIfDiscovererNotCloudFoundryShouldReturnFalse() { DiscoveredEndpoint endpoint = mock(DiscoveredEndpoint.class); given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(false); assertThat(this.filter.match(endpoint)).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java index d01247aa808..97680a87aa2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java @@ -50,10 +50,10 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class CloudFoundryWebEndpointDiscovererTests { +class CloudFoundryWebEndpointDiscovererTests { @Test - public void getEndpointsShouldAddCloudFoundryHealthExtension() { + void getEndpointsShouldAddCloudFoundryHealthExtension() { load(TestConfiguration.class, (discoverer) -> { Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints.size()).isEqualTo(2); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java index 2de8cd82f8a..3599bdea345 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java @@ -31,16 +31,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Madhura Bhave */ -public class TokenTests { +class TokenTests { @Test - public void invalidJwtShouldThrowException() { + void invalidJwtShouldThrowException() { assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token")) .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test - public void invalidJwtClaimsShouldThrowException() { + void invalidJwtClaimsShouldThrowException() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) @@ -50,7 +50,7 @@ public class TokenTests { } @Test - public void invalidJwtHeaderShouldThrowException() { + void invalidJwtHeaderShouldThrowException() { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) @@ -60,7 +60,7 @@ public class TokenTests { } @Test - public void emptyJwtSignatureShouldThrowException() { + void emptyJwtSignatureShouldThrowException() { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token)) @@ -68,7 +68,7 @@ public class TokenTests { } @Test - public void validJwt() { + void validJwt() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; String content = Base64Utils.encodeToString(header.getBytes()) + "." @@ -84,7 +84,7 @@ public class TokenTests { } @Test - public void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() { + void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() { String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); @@ -93,7 +93,7 @@ public class TokenTests { } @Test - public void getIssuerWhenIssIsNullShouldThrowException() { + void getIssuerWhenIssIsNullShouldThrowException() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); @@ -102,7 +102,7 @@ public class TokenTests { } @Test - public void getKidWhenKidIsNullShouldThrowException() { + void getKidWhenKidIsNullShouldThrowException() { String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); @@ -111,7 +111,7 @@ public class TokenTests { } @Test - public void getExpiryWhenExpIsNullShouldThrowException() { + void getExpiryWhenExpIsNullShouldThrowException() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}"; Token token = createToken(header, claims); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java index 53a91f548f5..da109ef8c5a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CloudFoundryReactiveHealthEndpointWebExtensionTests { +class CloudFoundryReactiveHealthEndpointWebExtensionTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") @@ -57,7 +57,7 @@ public class CloudFoundryReactiveHealthEndpointWebExtensionTests { ReactiveCloudFoundryActuatorAutoConfiguration.class)); @Test - public void healthDetailsAlwaysPresent() { + void healthDetailsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryReactiveHealthEndpointWebExtension extension = context .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java index 80c140e241d..ec59a4bca7b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java @@ -68,7 +68,7 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Stephane Nicoll */ -public class CloudFoundryWebFluxEndpointIntegrationTests { +class CloudFoundryWebFluxEndpointIntegrationTests { private static ReactiveTokenValidator tokenValidator = mock(ReactiveTokenValidator.class); @@ -82,7 +82,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { .withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0"); @Test - public void operationWithSecurityInterceptorForbidden() { + void operationWithSecurityInterceptorForbidden() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") @@ -91,7 +91,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { } @Test - public void operationWithSecurityInterceptorSuccess() { + void operationWithSecurityInterceptorSuccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") @@ -100,7 +100,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { } @Test - public void responseToOptionsRequestIncludesCorsHeaders() { + void responseToOptionsRequestIncludesCorsHeaders() { this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test") .accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST") .header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader() @@ -109,7 +109,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsWithFullAccess() { + void linksToOtherEndpointsWithFullAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); this.contextRunner @@ -124,7 +124,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsForbidden() { + void linksToOtherEndpointsForbidden() { CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); @@ -134,7 +134,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsWithRestrictedAccess() { + void linksToOtherEndpointsWithRestrictedAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); this.contextRunner diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java index ece5cdecbec..dcac9ee8d90 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java @@ -78,7 +78,7 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ReactiveCloudFoundryActuatorAutoConfigurationTests { +class ReactiveCloudFoundryActuatorAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, @@ -97,7 +97,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActive() { + void cloudFoundryPlatformActive() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); @@ -115,7 +115,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudfoundryapplicationProducesActuatorMediaType() { + void cloudfoundryapplicationProducesActuatorMediaType() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); @@ -125,7 +125,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveSetsApplicationId() { + void cloudFoundryPlatformActiveSetsApplicationId() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); @@ -136,7 +136,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { + void cloudFoundryPlatformActiveSetsCloudControllerUrl() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); @@ -150,7 +150,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { + void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") .run((context) -> { CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( @@ -165,7 +165,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void cloudFoundryPathsIgnoredBySpringSecurity() { + void cloudFoundryPathsIgnoredBySpringSecurity() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); @@ -189,19 +189,19 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformInactive() { + void cloudFoundryPlatformInactive() { this.contextRunner.run( (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test - public void cloudFoundryManagementEndpointsDisabled() { + void cloudFoundryManagementEndpointsDisabled() { this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run( (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test - public void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { + void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { @@ -214,7 +214,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void endpointPathCustomizationIsNotApplied() { + void endpointPathCustomizationIsNotApplied() { this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { @@ -230,7 +230,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { + void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") @@ -247,7 +247,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void gitFullDetailsAlwaysPresent() { + void gitFullDetailsAlwaysPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context .getBean(CloudFoundryInfoEndpointWebExtension.class); @@ -258,7 +258,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void skipSslValidation() { + void skipSslValidation() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com", @@ -275,7 +275,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { } @Test - public void sslValidationNotSkippedByDefault() { + void sslValidationNotSkippedByDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java index 9ffe2ed2d6b..1628e089583 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java @@ -41,7 +41,7 @@ import static org.mockito.BDDMockito.given; * * @author Madhura Bhave */ -public class ReactiveCloudFoundrySecurityInterceptorTests { +class ReactiveCloudFoundrySecurityInterceptorTests { @Mock private ReactiveTokenValidator tokenValidator; @@ -58,7 +58,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenRequestIsPreFlightShouldBeOk() { + void preHandleWhenRequestIsPreFlightShouldBeOk() { MockServerWebExchange request = MockServerWebExchange .from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); @@ -68,7 +68,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { + void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) @@ -76,7 +76,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { + void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( @@ -85,7 +85,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenApplicationIdIsNullShouldReturnError() { + void preHandleWhenApplicationIdIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); @@ -96,7 +96,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { + void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); MockServerWebExchange request = MockServerWebExchange .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); @@ -107,7 +107,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() { + void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() { given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id")) .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); @@ -120,7 +120,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleSuccessfulWithFullAccess() { + void preHandleSuccessfulWithFullAccess() { String accessToken = mockAccessToken(); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); @@ -133,7 +133,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { } @Test - public void preHandleSuccessfulWithRestrictedAccess() { + void preHandleSuccessfulWithRestrictedAccess() { String accessToken = mockAccessToken(); given(this.securityService.getAccessLevel(accessToken, "my-app-id")) .willReturn(Mono.just(AccessLevel.RESTRICTED)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java index f82f3777ac3..775d8c4e731 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class ReactiveCloudFoundrySecurityServiceTests { +class ReactiveCloudFoundrySecurityServiceTests { private static final String CLOUD_CONTROLLER = "/my-cloud-controller.com"; @@ -66,7 +66,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception { + void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) @@ -79,7 +79,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception { + void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) @@ -92,7 +92,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { + void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(401)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { @@ -107,7 +107,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { + void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(403)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { @@ -122,7 +122,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { + void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) .consumeErrorWith((throwable) -> { @@ -137,7 +137,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception { + void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception { String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" @@ -164,7 +164,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenNoKeysReturnedFromUAA() throws Exception { + void fetchTokenKeysWhenNoKeysReturnedFromUAA() throws Exception { prepareResponse((response) -> { response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}"); response.setHeader("Content-Type", "application/json"); @@ -181,7 +181,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() throws Exception { + void fetchTokenKeysWhenUnsuccessfulShouldThrowException() throws Exception { prepareResponse((response) -> { response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}"); response.setHeader("Content-Type", "application/json"); @@ -197,7 +197,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() throws Exception { + void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() throws Exception { prepareResponse((response) -> { response.setBody("{\"token_endpoint\":\"" + UAA_URL + "\"}"); response.setHeader("Content-Type", "application/json"); @@ -211,7 +211,7 @@ public class ReactiveCloudFoundrySecurityServiceTests { } @Test - public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception { + void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> { assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java index a47392410b8..872a2f9cf56 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java @@ -52,7 +52,7 @@ import static org.mockito.BDDMockito.given; * * @author Madhura Bhave */ -public class ReactiveTokenValidatorTests { +class ReactiveTokenValidatorTests { private static final byte[] DOT = ".".getBytes(); @@ -92,7 +92,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { + void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); @@ -110,7 +110,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { + void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); @@ -125,7 +125,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenCacheIsEmptyShouldFetchTokenKeys() throws Exception { + void validateTokenWhenCacheIsEmptyShouldFetchTokenKeys() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); @@ -139,7 +139,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() throws Exception { + void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); @@ -156,7 +156,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenCacheValidShouldNotFetchTokenKeys() throws Exception { + void validateTokenWhenCacheValidShouldNotFetchTokenKeys() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.empty(); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); @@ -170,7 +170,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { + void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { Map KEYS = Collections.singletonMap("valid-key", INVALID_KEY); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(KEYS)); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); @@ -186,7 +186,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { + void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; @@ -201,7 +201,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenExpiredShouldThrowException() throws Exception { + void validateTokenWhenExpiredShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; @@ -215,7 +215,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { + void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.getUaaUrl()).willReturn(Mono.just("https://other-uaa.com")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; @@ -229,7 +229,7 @@ public class ReactiveTokenValidatorTests { } @Test - public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { + void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java index 51e305d1c9a..f9407209136 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java @@ -64,7 +64,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Madhura Bhave */ -public class CloudFoundryActuatorAutoConfigurationTests { +class CloudFoundryActuatorAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, @@ -75,7 +75,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test - public void cloudFoundryPlatformActive() { + void cloudFoundryPlatformActive() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); @@ -93,7 +93,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudfoundryapplicationProducesActuatorMediaType() throws Exception { + void cloudfoundryapplicationProducesActuatorMediaType() throws Exception { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); @@ -103,7 +103,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveSetsApplicationId() { + void cloudFoundryPlatformActiveSetsApplicationId() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); @@ -114,7 +114,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { + void cloudFoundryPlatformActiveSetsCloudControllerUrl() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); @@ -128,7 +128,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void skipSslValidation() { + void skipSslValidation() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com", "management.cloudfoundry.skip-ssl-validation:true").run((context) -> { @@ -144,7 +144,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { + void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") .run((context) -> { CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); @@ -156,7 +156,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPathsIgnoredBySpringSecurity() { + void cloudFoundryPathsIgnoredBySpringSecurity() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") .run((context) -> { FilterChainProxy securityFilterChain = (FilterChainProxy) context @@ -172,20 +172,20 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void cloudFoundryPlatformInactive() { + void cloudFoundryPlatformInactive() { this.contextRunner.withPropertyValues() .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) .isFalse()); } @Test - public void cloudFoundryManagementEndpointsDisabled() { + void cloudFoundryManagementEndpointsDisabled() { this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); } @Test - public void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { + void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") .run((context) -> { @@ -198,7 +198,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void endpointPathCustomizationIsNotApplied() { + void endpointPathCustomizationIsNotApplied() { this.contextRunner .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com", @@ -216,7 +216,7 @@ public class CloudFoundryActuatorAutoConfigurationTests { } @Test - public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { + void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java index a1c0c4d0c5e..6c50c1f1818 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CloudFoundryHealthEndpointWebExtensionTests { +class CloudFoundryHealthEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") @@ -54,7 +54,7 @@ public class CloudFoundryHealthEndpointWebExtensionTests { HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test - public void healthDetailsAlwaysPresent() { + void healthDetailsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryHealthEndpointWebExtension extension = context .getBean(CloudFoundryHealthEndpointWebExtension.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java index ab5de36220c..18d717f4872 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java @@ -17,7 +17,7 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration; @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CloudFoundryInfoEndpointWebExtensionTests { +class CloudFoundryInfoEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withPropertyValues("VCAP_APPLICATION={}") @@ -61,7 +61,7 @@ public class CloudFoundryInfoEndpointWebExtensionTests { @Test @SuppressWarnings("unchecked") - public void gitFullDetailsAlwaysPresent() { + void gitFullDetailsAlwaysPresent() { this.contextRunner.withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) .run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java index 9ab6d8e4d5d..e10f46a35c2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java @@ -63,14 +63,14 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class CloudFoundryMvcWebEndpointIntegrationTests { +class CloudFoundryMvcWebEndpointIntegrationTests { private static TokenValidator tokenValidator = mock(TokenValidator.class); private static CloudFoundrySecurityService securityService = mock(CloudFoundrySecurityService.class); @Test - public void operationWithSecurityInterceptorForbidden() { + void operationWithSecurityInterceptorForbidden() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) @@ -79,7 +79,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } @Test - public void operationWithSecurityInterceptorSuccess() { + void operationWithSecurityInterceptorSuccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) @@ -88,7 +88,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } @Test - public void responseToOptionsRequestIncludesCorsHeaders() { + void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, (client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") @@ -98,7 +98,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsWithFullAccess() { + void linksToOtherEndpointsWithFullAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) @@ -112,7 +112,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsForbidden() { + void linksToOtherEndpointsForbidden() { CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); @@ -123,7 +123,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } @Test - public void linksToOtherEndpointsWithRestrictedAccess() { + void linksToOtherEndpointsWithRestrictedAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java index 04811785c6b..6c660f86b97 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptorTests.java @@ -41,7 +41,7 @@ import static org.mockito.Mockito.verify; * * @author Madhura Bhave */ -public class CloudFoundrySecurityInterceptorTests { +class CloudFoundrySecurityInterceptorTests { @Mock private TokenValidator tokenValidator; @@ -61,7 +61,7 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenRequestIsPreFlightShouldReturnTrue() { + void preHandleWhenRequestIsPreFlightShouldReturnTrue() { this.request.setMethod("OPTIONS"); this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); @@ -70,20 +70,20 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenTokenIsMissingShouldReturnFalse() { + void preHandleWhenTokenIsMissingShouldReturnFalse() { SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); } @Test - public void preHandleWhenTokenIsNotBearerShouldReturnFalse() { + void preHandleWhenTokenIsNotBearerShouldReturnFalse() { this.request.addHeader("Authorization", mockAccessToken()); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); } @Test - public void preHandleWhenApplicationIdIsNullShouldReturnFalse() { + void preHandleWhenApplicationIdIsNullShouldReturnFalse() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); @@ -91,7 +91,7 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() { + void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); this.request.addHeader("Authorization", "bearer " + mockAccessToken()); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); @@ -99,7 +99,7 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleWhenAccessIsNotAllowedShouldReturnFalse() { + void preHandleWhenAccessIsNotAllowedShouldReturnFalse() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "bearer " + accessToken); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); @@ -108,7 +108,7 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleSuccessfulWithFullAccess() { + void preHandleSuccessfulWithFullAccess() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "Bearer " + accessToken); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL); @@ -122,7 +122,7 @@ public class CloudFoundrySecurityInterceptorTests { } @Test - public void preHandleSuccessfulWithRestrictedAccess() { + void preHandleSuccessfulWithRestrictedAccess() { String accessToken = mockAccessToken(); this.request.addHeader("Authorization", "Bearer " + accessToken); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java index 1b5611d971e..42a2352f94e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java @@ -47,7 +47,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Madhura Bhave */ -public class CloudFoundrySecurityServiceTests { +class CloudFoundrySecurityServiceTests { private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com"; @@ -68,7 +68,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void skipSslValidationWhenTrue() { + void skipSslValidationWhenTrue() { RestTemplateBuilder builder = new RestTemplateBuilder(); this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, true); RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); @@ -76,7 +76,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void doNotskipSslValidationWhenFalse() { + void doNotskipSslValidationWhenFalse() { RestTemplateBuilder builder = new RestTemplateBuilder(); this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); @@ -84,7 +84,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() { + void getAccessLevelWhenSpaceDeveloperShouldReturnFull() { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) @@ -95,7 +95,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() { + void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) @@ -106,7 +106,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenTokenIsNotValidShouldThrowException() { + void getAccessLevelWhenTokenIsNotValidShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) @@ -115,7 +115,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenForbiddenShouldThrowException() { + void getAccessLevelWhenForbiddenShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withStatus(HttpStatus.FORBIDDEN)); @@ -125,7 +125,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { + void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) @@ -134,7 +134,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { + void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" @@ -155,7 +155,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenNoKeysReturnedFromUAA() { + void fetchTokenKeysWhenNoKeysReturnedFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String responseBody = "{\"keys\": []}"; @@ -167,7 +167,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { + void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); @@ -177,7 +177,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { + void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String uaaUrl = this.securityService.getUaaUrl(); @@ -189,7 +189,7 @@ public class CloudFoundrySecurityServiceTests { } @Test - public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { + void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) .isThrownBy(() -> this.securityService.getUaaUrl()) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java index 18d32fadbf4..6ec0637c797 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Test for {@link SkipSslVerificationHttpRequestFactory}. */ -public class SkipSslVerificationHttpRequestFactoryTests { +class SkipSslVerificationHttpRequestFactoryTests { private WebServer webServer; @@ -49,7 +49,7 @@ public class SkipSslVerificationHttpRequestFactoryTests { } @Test - public void restCallToSelfSignedServerShouldNotThrowSslException() { + void restCallToSelfSignedServerShouldNotThrowSslException() { String httpsUrl = getHttpsUrl(); SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java index 503c60f6a5d..16e561c1948 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java @@ -52,7 +52,7 @@ import static org.mockito.Mockito.verify; * * @author Madhura Bhave */ -public class TokenValidatorTests { +class TokenValidatorTests { private static final byte[] DOT = ".".getBytes(); @@ -90,7 +90,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { + void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; @@ -101,7 +101,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { + void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); @@ -112,7 +112,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenShouldFetchTokenKeysIfNull() throws Exception { + void validateTokenShouldFetchTokenKeysIfNull() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; @@ -122,7 +122,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenValidShouldNotFetchTokenKeys() throws Exception { + void validateTokenWhenValidShouldNotFetchTokenKeys() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; @@ -132,7 +132,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { + void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", Collections.singletonMap("valid-key", INVALID_KEY)); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); @@ -144,7 +144,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { + void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; @@ -154,7 +154,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenExpiredShouldThrowException() throws Exception { + void validateTokenWhenExpiredShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; @@ -165,7 +165,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { + void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; @@ -176,7 +176,7 @@ public class TokenValidatorTests { } @Test - public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { + void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java index fa7fd1ef1e2..df2e9fdc62f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java @@ -28,24 +28,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConditionsReportEndpointAutoConfigurationTests { +class ConditionsReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions") .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java index ac1892285b9..a2e40ee1a1c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java @@ -43,10 +43,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class ConditionsReportEndpointTests { +class ConditionsReportEndpointTests { @Test - public void invoke() { + void invoke() { new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { ContextConditionEvaluation report = context.getBean(ConditionsReportEndpoint.class) .applicationConditionEvaluation().getContexts().get(context.getId()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java index af7838dadd7..166455e77e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java @@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ShutdownEndpointAutoConfigurationTests { +class ShutdownEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") .withPropertyValues("management.endpoints.web.exposure.include=shutdown") .run((context) -> assertThat(context).hasSingleBean(ShutdownEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java index 8f9761df4f2..aa74bcff0fd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java @@ -38,26 +38,26 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConfigurationPropertiesReportEndpointAutoConfigurationTests { +class ConfigurationPropertiesReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(Config.class) .withPropertyValues("management.endpoints.web.exposure.include=configprops") .run(validateTestProperties("******", "654321")); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } @Test - public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { + void keysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withUserConfiguration(Config.class) .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") .withPropertyValues("management.endpoints.web.exposure.include=configprops") @@ -65,7 +65,7 @@ public class ConfigurationPropertiesReportEndpointAutoConfigurationTests { } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java index 57f1980ccb0..7228dbb03ea 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfigurationTests.java @@ -34,21 +34,21 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Stephane Nicoll */ -public class CouchbaseHealthIndicatorAutoConfigurationTests { +class CouchbaseHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations .of(CouchbaseHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class) .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java index 218f0fb3952..32613f57139 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthIndicatorAutoConfigurationTests.java @@ -33,20 +33,20 @@ import static org.mockito.Mockito.mock; * * @author Mikalai Lushchytski */ -public class CouchbaseReactiveHealthIndicatorAutoConfigurationTests { +class CouchbaseReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations.of( CouchbaseReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) .doesNotHaveBean(CouchbaseHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java index 15a0cb0e400..2044e1ea6cd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java @@ -37,14 +37,14 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb */ @Deprecated -public class ElasticsearchHealthIndicatorAutoConfigurationTests { +class ElasticsearchHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations .of(ElasticsearchAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class, ElasticSearchJestHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0") .withSystemProperties("es.set.netty.runtime.available.processors=false") .run((context) -> assertThat(context).hasSingleBean(ElasticsearchHealthIndicator.class) @@ -53,7 +53,7 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests { } @Test - public void runWhenUsingJestClientShouldCreateIndicator() { + void runWhenUsingJestClientShouldCreateIndicator() { this.contextRunner.withBean(JestClient.class, () -> mock(JestClient.class)) .withSystemProperties("es.set.netty.runtime.available.processors=false") .run((context) -> assertThat(context).hasSingleBean(ElasticsearchJestHealthIndicator.class) @@ -62,7 +62,7 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests { } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchHealthIndicator.class) .doesNotHaveBean(ElasticsearchJestHealthIndicator.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java index b9fb3a6e328..b5d26c8f026 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointIdTimeToLivePropertyFunctionTests.java @@ -31,27 +31,27 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Phillip Webb */ -public class EndpointIdTimeToLivePropertyFunctionTests { +class EndpointIdTimeToLivePropertyFunctionTests { private final MockEnvironment environment = new MockEnvironment(); private final Function timeToLive = new EndpointIdTimeToLivePropertyFunction(this.environment); @Test - public void defaultConfiguration() { + void defaultConfiguration() { Long result = this.timeToLive.apply(EndpointId.of("test")); assertThat(result).isNull(); } @Test - public void userConfiguration() { + void userConfiguration() { this.environment.setProperty("management.endpoint.test.cache.time-to-live", "500"); Long result = this.timeToLive.apply(EndpointId.of("test")); assertThat(result).isEqualTo(500L); } @Test - public void mixedCaseUserConfiguration() { + void mixedCaseUserConfiguration() { this.environment.setProperty("management.endpoint.another-test.cache.time-to-live", "500"); Long result = this.timeToLive.apply(EndpointId.of("anotherTest")); assertThat(result).isEqualTo(500L); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java index feda448148e..8741a91de7b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ExposeExcludePropertyEndpointFilterTests { +class ExposeExcludePropertyEndpointFilterTests { private ExposeExcludePropertyEndpointFilter filter; @@ -46,77 +46,77 @@ public class ExposeExcludePropertyEndpointFilterTests { } @Test - public void createWhenEndpointTypeIsNullShouldThrowException() { + void createWhenEndpointTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, new MockEnvironment(), "foo")) .withMessageContaining("EndpointType must not be null"); } @Test - public void createWhenEnvironmentIsNullShouldThrowException() { + void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, null, "foo")) .withMessageContaining("Environment must not be null"); } @Test - public void createWhenPrefixIsNullShouldThrowException() { + void createWhenPrefixIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) .withMessageContaining("Prefix must not be empty"); } @Test - public void createWhenPrefixIsEmptyShouldThrowException() { + void createWhenPrefixIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) .withMessageContaining("Prefix must not be empty"); } @Test - public void matchWhenExposeIsEmptyAndExcludeIsEmptyAndInDefaultShouldMatch() { + void matchWhenExposeIsEmptyAndExcludeIsEmptyAndInDefaultShouldMatch() { setupFilter("", ""); assertThat(match(EndpointId.of("def"))).isTrue(); } @Test - public void matchWhenExposeIsEmptyAndExcludeIsEmptyAndNotInDefaultShouldNotMatch() { + void matchWhenExposeIsEmptyAndExcludeIsEmptyAndNotInDefaultShouldNotMatch() { setupFilter("", ""); assertThat(match(EndpointId.of("bar"))).isFalse(); } @Test - public void matchWhenExposeMatchesAndExcludeIsEmptyShouldMatch() { + void matchWhenExposeMatchesAndExcludeIsEmptyShouldMatch() { setupFilter("bar", ""); assertThat(match(EndpointId.of("bar"))).isTrue(); } @Test - public void matchWhenExposeDoesNotMatchAndExcludeIsEmptyShouldNotMatch() { + void matchWhenExposeDoesNotMatchAndExcludeIsEmptyShouldNotMatch() { setupFilter("bar", ""); assertThat(match(EndpointId.of("baz"))).isFalse(); } @Test - public void matchWhenExposeMatchesAndExcludeMatchesShouldNotMatch() { + void matchWhenExposeMatchesAndExcludeMatchesShouldNotMatch() { setupFilter("bar,baz", "baz"); assertThat(match(EndpointId.of("baz"))).isFalse(); } @Test - public void matchWhenExposeMatchesAndExcludeDoesNotMatchShouldMatch() { + void matchWhenExposeMatchesAndExcludeDoesNotMatchShouldMatch() { setupFilter("bar,baz", "buz"); assertThat(match(EndpointId.of("baz"))).isTrue(); } @Test - public void matchWhenExposeMatchesWithDifferentCaseShouldMatch() { + void matchWhenExposeMatchesWithDifferentCaseShouldMatch() { setupFilter("bar", ""); assertThat(match(EndpointId.of("bAr"))).isTrue(); } @Test - public void matchWhenDiscovererDoesNotMatchShouldMatch() { + void matchWhenDiscovererDoesNotMatchShouldMatch() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("foo.include", "bar"); environment.setProperty("foo.exclude", ""); @@ -126,7 +126,7 @@ public class ExposeExcludePropertyEndpointFilterTests { } @Test - public void matchWhenIncludeIsAsteriskShouldMatchAll() { + void matchWhenIncludeIsAsteriskShouldMatchAll() { setupFilter("*", "buz"); assertThat(match(EndpointId.of("bar"))).isTrue(); assertThat(match(EndpointId.of("baz"))).isTrue(); @@ -134,7 +134,7 @@ public class ExposeExcludePropertyEndpointFilterTests { } @Test - public void matchWhenExcludeIsAsteriskShouldMatchNone() { + void matchWhenExcludeIsAsteriskShouldMatchNone() { setupFilter("bar,baz,buz", "*"); assertThat(match(EndpointId.of("bar"))).isFalse(); assertThat(match(EndpointId.of("baz"))).isFalse(); @@ -142,7 +142,7 @@ public class ExposeExcludePropertyEndpointFilterTests { } @Test - public void matchWhenMixedCaseShouldMatch() { + void matchWhenMixedCaseShouldMatch() { setupFilter("foo-bar", ""); assertThat(match(EndpointId.of("fooBar"))).isTrue(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java index d903d635187..cd40883e76e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.actuate.autoconfigure.endpoint.condition; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.endpoint.EndpointFilter; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; @@ -33,33 +33,33 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class ConditionalOnAvailableEndpointTests { +class ConditionalOnAvailableEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(AllEndpointsConfiguration.class); @Test - public void outcomeShouldMatchDefaults() { + void outcomeShouldMatchDefaults() { this.contextRunner.run((context) -> assertThat(context).hasBean("info").hasBean("health") .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { + void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") .run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health") .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { + void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") .hasBean("spring").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { + void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false") @@ -68,7 +68,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() { + void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoint.shutdown.enabled=true") @@ -77,21 +77,21 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { + void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*") .run((context) -> assertThat(context).hasBean("info").hasBean("health").doesNotHaveBean("spring") .doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { + void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true") .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") .hasBean("spring").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { + void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", "management.endpoint.shutdown.enabled=true") @@ -100,7 +100,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() { + void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=spring,info") @@ -109,7 +109,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { + void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", "management.endpoints.web.exposure.exclude=spring,info") @@ -118,21 +118,21 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { + void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring") .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { + void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown") .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() { + void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=shutdown", "management.endpoint.shutdown.enabled=true") @@ -141,14 +141,14 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeMatchesWithCaseShouldMatch() { + void outcomeWhenIncludeMatchesWithCaseShouldMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing") .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); } @Test - public void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { + void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", "management.endpoints.web.exposure.exclude=*") @@ -157,7 +157,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { + void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=spring") .run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent") @@ -166,7 +166,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeWithNoEndpointReferenceShouldFail() { + void outcomeWithNoEndpointReferenceShouldFail() { this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> { assertThat(context).hasFailed(); @@ -177,7 +177,7 @@ public class ConditionalOnAvailableEndpointTests { } @Test - public void outcomeOnCloudFoundryShouldMatchAll() { + void outcomeOnCloudFoundryShouldMatchAll() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run( (context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java index 8dcb3f05e07..3f1f6051189 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java @@ -36,64 +36,64 @@ import static org.assertj.core.api.Assertions.assertThat; */ @Deprecated @SuppressWarnings("deprecation") -public class ConditionalOnEnabledEndpointTests { +class ConditionalOnEnabledEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void outcomeWhenEndpointEnabledPropertyIsTrueShouldMatch() { + void outcomeWhenEndpointEnabledPropertyIsTrueShouldMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true") .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void outcomeWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { + void outcomeWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsTrueShouldMatch() { + void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsTrueShouldMatch() { this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=true") .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsFalseShouldNotMatch() { + void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsFalseShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void outcomeWhenNoPropertiesAndAnnotationIsEnabledByDefaultShouldMatch() { + void outcomeWhenNoPropertiesAndAnnotationIsEnabledByDefaultShouldMatch() { this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void outcomeWhenNoPropertiesAndAnnotationIsNotEnabledByDefaultShouldNotMatch() { + void outcomeWhenNoPropertiesAndAnnotationIsNotEnabledByDefaultShouldNotMatch() { this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void outcomeWhenNoPropertiesAndExtensionAnnotationIsEnabledByDefaultShouldMatch() { + void outcomeWhenNoPropertiesAndExtensionAnnotationIsEnabledByDefaultShouldMatch() { this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultTrueConfiguration.class) .run((context) -> assertThat(context).hasBean("foo").hasBean("fooExt")); } @Test - public void outcomeWhenNoPropertiesAndExtensionAnnotationIsNotEnabledByDefaultShouldNotMatch() { + void outcomeWhenNoPropertiesAndExtensionAnnotationIsNotEnabledByDefaultShouldNotMatch() { this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo").doesNotHaveBean("fooExt")); } @Test - public void outcomeWithReferenceWhenNoPropertiesShouldMatch() { + void outcomeWithReferenceWhenNoPropertiesShouldMatch() { this.contextRunner .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, ComponentEnabledIfEndpointIsEnabledConfiguration.class) @@ -101,7 +101,7 @@ public class ConditionalOnEnabledEndpointTests { } @Test - public void outcomeWithReferenceWhenEndpointEnabledPropertyIsTrueShouldMatch() { + void outcomeWithReferenceWhenEndpointEnabledPropertyIsTrueShouldMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true") .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, ComponentEnabledIfEndpointIsEnabledConfiguration.class) @@ -109,7 +109,7 @@ public class ConditionalOnEnabledEndpointTests { } @Test - public void outcomeWithReferenceWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { + void outcomeWithReferenceWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, ComponentEnabledIfEndpointIsEnabledConfiguration.class) @@ -117,7 +117,7 @@ public class ConditionalOnEnabledEndpointTests { } @Test - public void outcomeWithNoReferenceShouldFail() { + void outcomeWithNoReferenceShouldFail() { this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause().getMessage()) @@ -127,14 +127,14 @@ public class ConditionalOnEnabledEndpointTests { } @Test - public void outcomeWhenEndpointEnabledPropertyIsTrueAndMixedCaseShouldMatch() { + void outcomeWhenEndpointEnabledPropertyIsTrueAndMixedCaseShouldMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo-bar.enabled=true") .withUserConfiguration(FooBarEndpointEnabledByDefaultFalseConfiguration.class) .run((context) -> assertThat(context).hasBean("fooBar")); } @Test - public void outcomeWhenEndpointEnabledPropertyIsFalseOnClassShouldNotMatch() { + void outcomeWhenEndpointEnabledPropertyIsFalseOnClassShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") .withUserConfiguration(FooEndpointEnabledByDefaultTrueOnConfigurationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java index 56623eacec7..e9f06636195 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class DefaultEndpointObjectNameFactoryTests { +class DefaultEndpointObjectNameFactoryTests { private final MockEnvironment environment = new MockEnvironment(); @@ -49,26 +49,26 @@ public class DefaultEndpointObjectNameFactoryTests { private String contextId; @Test - public void generateObjectName() { + void generateObjectName() { ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test"); } @Test - public void generateObjectNameWithCapitalizedId() { + void generateObjectNameWithCapitalizedId() { ObjectName objectName = generateObjectName(endpoint(EndpointId.of("testEndpoint"))); assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint"); } @Test - public void generateObjectNameWithCustomDomain() { + void generateObjectNameWithCustomDomain() { this.properties.setDomain("com.example.acme"); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); assertThat(objectName.toString()).isEqualTo("com.example.acme:type=Endpoint,name=Test"); } @Test - public void generateObjectNameWithUniqueNames() { + void generateObjectNameWithUniqueNames() { this.environment.setProperty("spring.jmx.unique-names", "true"); assertUniqueObjectName(); } @@ -81,7 +81,7 @@ public class DefaultEndpointObjectNameFactoryTests { } @Test - public void generateObjectNameWithStaticNames() { + void generateObjectNameWithStaticNames() { this.properties.getStaticNames().setProperty("counter", "42"); this.properties.getStaticNames().setProperty("foo", "bar"); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); @@ -91,7 +91,7 @@ public class DefaultEndpointObjectNameFactoryTests { } @Test - public void generateObjectNameWithDuplicate() throws MalformedObjectNameException { + void generateObjectNameWithDuplicate() throws MalformedObjectNameException { this.contextId = "testContext"; given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)) .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java index 3aa20853719..32b7541323c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java @@ -30,16 +30,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class MappingWebEndpointPathMapperTests { +class MappingWebEndpointPathMapperTests { @Test - public void defaultConfiguration() { + void defaultConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))).isEqualTo("test"); } @Test - public void userConfiguration() { + void userConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))) @@ -47,14 +47,14 @@ public class MappingWebEndpointPathMapperTests { } @Test - public void mixedCaseDefaultConfiguration() { + void mixedCaseDefaultConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) .isEqualTo("testEndpoint"); } @Test - public void mixedCaseUserConfiguration() { + void mixedCaseUserConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test-endpoint", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java index 2f0c9996b69..5abb1f5bcfe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java @@ -42,13 +42,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class ServletEndpointManagementContextConfigurationTests { +class ServletEndpointManagementContextConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withUserConfiguration(TestConfig.class); @Test - public void contextShouldContainServletEndpointRegistrar() { + void contextShouldContainServletEndpointRegistrar() { FilteredClassLoader classLoader = new FilteredClassLoader(ResourceConfig.class); this.contextRunner.withClassLoader(classLoader).run((context) -> { assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); @@ -58,7 +58,7 @@ public class ServletEndpointManagementContextConfigurationTests { } @Test - public void contextWhenJerseyShouldContainServletEndpointRegistrar() { + void contextWhenJerseyShouldContainServletEndpointRegistrar() { FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); this.contextRunner.withClassLoader(classLoader).run((context) -> { assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); @@ -68,7 +68,7 @@ public class ServletEndpointManagementContextConfigurationTests { } @Test - public void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { + void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { new ApplicationContextRunner().withUserConfiguration(TestConfig.class) .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java index 1d7fc06910c..8765d6aecdf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Yunkun Huang * @author Phillip Webb */ -public class WebEndpointAutoConfigurationTests { +class WebEndpointAutoConfigurationTests { private static final AutoConfigurations CONFIGURATIONS = AutoConfigurations.of(EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class); @@ -58,7 +58,7 @@ public class WebEndpointAutoConfigurationTests { .withConfiguration(CONFIGURATIONS); @Test - public void webApplicationConfiguresEndpointMediaTypes() { + void webApplicationConfiguresEndpointMediaTypes() { this.contextRunner.run((context) -> { EndpointMediaTypes endpointMediaTypes = context.getBean(EndpointMediaTypes.class); assertThat(endpointMediaTypes.getConsumed()).containsExactly(ActuatorMediaType.V2_JSON, "application/json"); @@ -66,7 +66,7 @@ public class WebEndpointAutoConfigurationTests { } @Test - public void webApplicationConfiguresPathMapper() { + void webApplicationConfiguresPathMapper() { this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck") .run((context) -> { assertThat(context).hasSingleBean(PathMapper.class); @@ -76,7 +76,7 @@ public class WebEndpointAutoConfigurationTests { } @Test - public void webApplicationSupportCustomPathMatcher() { + void webApplicationSupportCustomPathMatcher() { this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoints.web.path-mapping.testanotherone=foo") @@ -93,7 +93,7 @@ public class WebEndpointAutoConfigurationTests { } @Test - public void webApplicationConfiguresEndpointDiscoverer() { + void webApplicationConfiguresEndpointDiscoverer() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(ControllerEndpointDiscoverer.class); assertThat(context).hasSingleBean(WebEndpointDiscoverer.class); @@ -101,19 +101,19 @@ public class WebEndpointAutoConfigurationTests { } @Test - public void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { + void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { this.contextRunner .run((context) -> assertThat(context).getBeans(ExposeExcludePropertyEndpointFilter.class).containsKeys( "webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); } @Test - public void contextShouldConfigureServletEndpointDiscoverer() { + void contextShouldConfigureServletEndpointDiscoverer() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletEndpointDiscoverer.class)); } @Test - public void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { + void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { new ApplicationContextRunner().withConfiguration(CONFIGURATIONS) .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java index 146997da65d..d1d55d2901f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java @@ -26,16 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Madhura Bhave */ -public class WebEndpointPropertiesTests { +class WebEndpointPropertiesTests { @Test - public void defaultBasePathShouldBeApplication() { + void defaultBasePathShouldBeApplication() { WebEndpointProperties properties = new WebEndpointProperties(); assertThat(properties.getBasePath()).isEqualTo("/actuator"); } @Test - public void basePathShouldBeCleaned() { + void basePathShouldBeCleaned() { WebEndpointProperties properties = new WebEndpointProperties(); properties.setBasePath("/"); assertThat(properties.getBasePath()).isEqualTo(""); @@ -44,14 +44,14 @@ public class WebEndpointPropertiesTests { } @Test - public void basePathMustStartWithSlash() { + void basePathMustStartWithSlash() { WebEndpointProperties properties = new WebEndpointProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin")) .withMessageContaining("Base path must start with '/' or be empty"); } @Test - public void basePathCanBeEmpty() { + void basePathCanBeEmpty() { WebEndpointProperties properties = new WebEndpointProperties(); properties.setBasePath(""); assertThat(properties.getBasePath()).isEqualTo(""); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java index 8d011d58559..350d2ad7e0c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java @@ -47,13 +47,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @MockBean private AuditEventRepository repository; @Test - public void allAuditEvents() throws Exception { + void allAuditEvents() throws Exception { String queryTimestamp = "2017-11-07T09:37Z"; given(this.repository.find(any(), any(), any())) .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); @@ -66,7 +66,7 @@ public class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocume } @Test - public void filteredAuditEvents() throws Exception { + void filteredAuditEvents() throws Exception { OffsetDateTime now = OffsetDateTime.now(); String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now); given(this.repository.find("alice", now.toInstant(), "logout")) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java index 5c4ac066ec3..a696e008e41 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java @@ -45,10 +45,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void beans() throws Exception { + void beans() throws Exception { List beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."), fieldWithPath("scope").description("Scope of the bean."), fieldWithPath("type").description("Fully qualified type of the bean."), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java index f2307e2ed3b..de5b1d7e91c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java @@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Stephane Nicoll */ -public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final List levelFields = Arrays.asList( fieldWithPath("name").description("Cache name."), @@ -61,7 +61,7 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati .optional()); @Test - public void allCaches() throws Exception { + void allCaches() throws Exception { this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("caches/all", responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), @@ -72,19 +72,19 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati } @Test - public void namedCache() throws Exception { + void namedCache() throws Exception { this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation .document("caches/named", requestParameters(requestParameters), responseFields(levelFields))); } @Test - public void evictAllCaches() throws Exception { + void evictAllCaches() throws Exception { this.mockMvc.perform(delete("/actuator/caches")).andExpect(status().isNoContent()) .andDo(MockMvcRestDocumentation.document("caches/evict-all")); } @Test - public void evictNamedCache() throws Exception { + void evictNamedCache() throws Exception { this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager")) .andExpect(status().isNoContent()) .andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters))); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java index 898d2e58a95..dae0a6582a7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java @@ -49,7 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private MockMvc mockMvc; @@ -64,7 +64,7 @@ public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointD } @Test - public void conditions() throws Exception { + void conditions() throws Exception { List positiveMatchFields = Arrays.asList( fieldWithPath("").description("Classes and methods with conditions that were " + "matched."), fieldWithPath(".*.[].condition").description("Name of the condition."), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java index e43b2d896c7..83de3e6ef73 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java @@ -37,10 +37,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void configProps() throws Exception { + void configProps() throws Exception { this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("configprops", preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java index 553170856b5..94febad1c7a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java @@ -57,7 +57,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @TestPropertySource( properties = "spring.config.location=classpath:/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/") -public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles") .description("Names of the active profiles, if any."); @@ -69,7 +69,7 @@ public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocume .description("Name of the property source."); @Test - public void env() throws Exception { + void env() throws Exception { this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()) .andDo(document("env/all", preprocessResponse(replacePattern( Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), @@ -84,7 +84,7 @@ public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocume } @Test - public void singlePropertyFromEnv() throws Exception { + void singlePropertyFromEnv() throws Exception { this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document( "env/single", preprocessResponse(replacePattern( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java index 97c3d5765fc..2de5109ca45 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java @@ -47,10 +47,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void flyway() throws Exception { + void flyway() throws Exception { this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("flyway", responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java index 498e363c63c..fa39e71916a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java @@ -55,7 +55,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Andy Wilkinson * @author Stephane Nicoll */ -public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final List componentFields = Arrays.asList( fieldWithPath("status").description("Status of a specific part of the application"), @@ -63,7 +63,7 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati .description("Details of the health of a specific part of the" + " application.")); @Test - public void health() throws Exception { + void health() throws Exception { this.mockMvc.perform(get("/actuator/health")).andExpect(status().isOk()).andDo(document("health", responseFields(fieldWithPath("status").description("Overall status of the application."), fieldWithPath("details") @@ -75,13 +75,13 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati } @Test - public void healthComponent() throws Exception { + void healthComponent() throws Exception { this.mockMvc.perform(get("/actuator/health/db")).andExpect(status().isOk()) .andDo(document("health/component", responseFields(componentFields))); } @Test - public void healthComponentInstance() throws Exception { + void healthComponentInstance() throws Exception { this.mockMvc.perform(get("/actuator/health/broker/us1")).andExpect(status().isOk()) .andDo(document("health/instance", responseFields(componentFields))); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java index 79ef92d34a8..710f36efc5c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java @@ -39,10 +39,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void heapDump() throws Exception { + void heapDump() throws Exception { this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk()) .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java index 48aa0a9099a..1e4fad2ccda 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpTraceEndpointDocumentationTests.java @@ -52,13 +52,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @MockBean private HttpTraceRepository repository; @Test - public void traces() throws Exception { + void traces() throws Exception { TraceableRequest request = mock(TraceableRequest.class); given(request.getUri()).willReturn(URI.create("https://api.example.com")); given(request.getMethod()).willReturn("GET"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java index 35e2413e403..0b96b5047c7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java @@ -44,10 +44,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void info() throws Exception { + void info() throws Exception { this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("info", responseFields(beneathPath("git"), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java index ac5baf78e6d..f97c659a21e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java @@ -35,16 +35,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Tim Ysewyn */ -public class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void graph() throws Exception { + void graph() throws Exception { this.mockMvc.perform(get("/actuator/integrationgraph")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); } @Test - public void rebuild() throws Exception { + void rebuild() throws Exception { this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent()) .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java index e27b99c81a1..17d770d4f43 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java @@ -43,10 +43,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void liquibase() throws Exception { + void liquibase() throws Exception { FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets") .description("Change sets made by the Liquibase beans, keyed by " + "bean name."); this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk()) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java index 28d8ea3fe35..ac50beee6c0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java @@ -36,16 +36,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @TestPropertySource( properties = "logging.file.name=src/test/resources/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/sample.log") -public class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void logFile() throws Exception { + void logFile() throws Exception { this.mockMvc.perform(get("/actuator/logfile")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("logfile/entire")); } @Test - public void logFileRange() throws Exception { + void logFileRange() throws Exception { this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023")) .andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java index e21f21cc594..11de037ec93 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java @@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final List levelFields = Arrays.asList( fieldWithPath("configuredLevel").description("Configured level of the logger, if any.").optional(), @@ -58,7 +58,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat private LoggingSystem loggingSystem; @Test - public void allLoggers() throws Exception { + void allLoggers() throws Exception { given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); given(this.loggingSystem.getLoggerConfigurations()) .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), @@ -71,7 +71,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat } @Test - public void logger() throws Exception { + void logger() throws Exception { given(this.loggingSystem.getLoggerConfiguration("com.example")) .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk()) @@ -79,7 +79,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat } @Test - public void setLogLevel() throws Exception { + void setLogLevel() throws Exception { this.mockMvc .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") .contentType(MediaType.APPLICATION_JSON)) @@ -90,7 +90,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat } @Test - public void clearLogLevel() throws Exception { + void clearLogLevel() throws Exception { this.mockMvc .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java index 0997629c9ac..49654c99f82 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java @@ -62,7 +62,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r */ @ExtendWith(RestDocumentationExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") -public class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumentationTests { +class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumentationTests { @LocalServerPort private int port; @@ -77,7 +77,7 @@ public class MappingsEndpointReactiveDocumentationTests extends AbstractEndpoint } @Test - public void mappings() throws Exception { + void mappings() throws Exception { List requestMappingConditions = Arrays.asList( requestMappingConditionField("").description("Details of the request mapping conditions.").optional(), requestMappingConditionField(".consumes").description("Details of the consumes condition"), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java index 420575bac23..9cc3dc2b1ff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java @@ -62,7 +62,7 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume */ @ExtendWith(RestDocumentationExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests { +class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests { @LocalServerPort private int port; @@ -76,7 +76,7 @@ public class MappingsEndpointServletDocumentationTests extends AbstractEndpointD } @Test - public void mappings() throws Exception { + void mappings() throws Exception { ResponseFieldsSnippet commonResponseFields = responseFields( fieldWithPath("contexts").description("Application contexts keyed by id."), fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."), diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java index 99f6b5eb8ef..895d8742527 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java @@ -39,16 +39,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void metricNames() throws Exception { + void metricNames() throws Exception { this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names", responseFields(fieldWithPath("names").description("Names of the known metrics.")))); } @Test - public void metric() throws Exception { + void metric() throws Exception { this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk()) .andDo(document("metrics/metric", responseFields(fieldWithPath("name").description("Name of the metric"), @@ -64,7 +64,7 @@ public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentat } @Test - public void metricWithTags() throws Exception { + void metricWithTags() throws Exception { this.mockMvc .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag", "id:Compressed Class Space")) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java index 72becce0bed..ec8747b4e3e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java @@ -36,10 +36,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void prometheus() throws Exception { + void prometheus() throws Exception { this.mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()).andDo(document("prometheus")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java index 2097f852723..bccc1c159b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java @@ -48,10 +48,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void scheduledTasks() throws Exception { + void scheduledTasks() throws Exception { this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()).andDo(document( "scheduled-tasks", preprocessResponse(replacePattern( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java index a28495c62b1..ca79caf3941 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java @@ -54,7 +54,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Andy Wilkinson */ @TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false") -public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final Session sessionOne = createSession(Instant.now().minusSeconds(60 * 60 * 12), Instant.now().minusSeconds(45)); @@ -78,7 +78,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta private FindByIndexNameSessionRepository sessionRepository; @Test - public void sessionsForUsername() throws Exception { + void sessionsForUsername() throws Exception { Map sessions = new HashMap<>(); sessions.put(sessionOne.getId(), sessionOne); sessions.put(sessionTwo.getId(), sessionTwo); @@ -92,7 +92,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta } @Test - public void sessionWithId() throws Exception { + void sessionWithId() throws Exception { Map sessions = new HashMap<>(); sessions.put(sessionOne.getId(), sessionOne); sessions.put(sessionTwo.getId(), sessionTwo); @@ -103,7 +103,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta } @Test - public void deleteASession() throws Exception { + void deleteASession() throws Exception { this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) .andDo(document("sessions/delete")); verify(this.sessionRepository).deleteById(sessionTwo.getId()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java index f8a386ccd34..794ab29a515 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java @@ -36,10 +36,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void shutdown() throws Exception { + void shutdown() throws Exception { this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk()) .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( fieldWithPath("message").description("Message describing the result of the request.")))); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java index 2994b259ab6..3cffdbb07e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java @@ -40,10 +40,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { +class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test - public void threadDump() throws Exception { + void threadDump() throws Exception { ReentrantLock lock = new ReentrantLock(); CountDownLatch latch = new CountDownLatch(1); new Thread(() -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java index 9cd777d37eb..014a9cc6ccc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Michael Simons * @author Madhura Bhave */ -public class JerseyWebEndpointManagementContextConfigurationTests { +class JerseyWebEndpointManagementContextConfigurationTests { private final WebApplicationContextRunner runner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, @@ -46,12 +46,12 @@ public class JerseyWebEndpointManagementContextConfigurationTests { .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); @Test - public void resourceConfigCustomizerForEndpointsIsAutoConfigured() { + void resourceConfigCustomizerForEndpointsIsAutoConfigured() { this.runner.run((context) -> assertThat(context).hasSingleBean(ResourceConfigCustomizer.class)); } @Test - public void autoConfigurationIsConditionalOnServletWebApplication() { + void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner @@ -59,7 +59,7 @@ public class JerseyWebEndpointManagementContextConfigurationTests { } @Test - public void autoConfigurationIsConditionalOnClassResourceConfig() { + void autoConfigurationIsConditionalOnClassResourceConfig() { this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java index 9e2e0e2d6b4..6965b59bb88 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java @@ -36,31 +36,31 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class EnvironmentEndpointAutoConfigurationTests { +class EnvironmentEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") .withSystemProperties("dbPassword=123456", "apiKey=123456") .run(validateSystemProperties("******", "******")); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test - public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { + void keysToSanitizeCanBeConfiguredViaTheEnvironment() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") .withSystemProperties("dbPassword=123456", "apiKey=123456") .withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java index 82e7122a4f1..6f99929e497 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java @@ -31,26 +31,26 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class FlywayEndpointAutoConfigurationTests { +class FlywayEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) .withBean(Flyway.class, () -> mock(Flyway.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway") .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java index 39a47af214a..2c46621f973 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java @@ -40,13 +40,13 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Phillip Webb */ -public class HealthEndpointAutoConfigurationTests { +class HealthEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); @Test - public void healthEndpointShowDetailsDefault() { + void healthEndpointShowDetailsDefault() { this.contextRunner.withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", ReactiveHealthIndicator.class); @@ -59,7 +59,7 @@ public class HealthEndpointAutoConfigurationTests { } @Test - public void healthEndpointAdaptReactiveHealthIndicator() { + void healthEndpointAdaptReactiveHealthIndicator() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") .withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", @@ -73,7 +73,7 @@ public class HealthEndpointAutoConfigurationTests { } @Test - public void healthEndpointMergeRegularAndReactive() { + void healthEndpointMergeRegularAndReactive() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") .withBean("simpleHealthIndicator", HealthIndicator.class, this::simpleHealthIndicator) .withBean("reactiveHealthIndicator", ReactiveHealthIndicator.class, this::reactiveHealthIndicator) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java index 4d61cdc5df7..0acac3ac61b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionTests.java @@ -49,25 +49,25 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class HealthEndpointWebExtensionTests { +class HealthEndpointWebExtensionTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations .of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); @Test - public void runShouldCreateExtensionBeans() { + void runShouldCreateExtensionBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); } @Test - public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { + void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(HealthEndpointWebExtension.class)); } @Test - public void runWithCustomHealthMappingShouldMapStatusCode() { + void runWithCustomHealthMappingShouldMapStatusCode() { this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { Object extension = context.getBean(HealthEndpointWebExtension.class); HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils @@ -82,7 +82,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersAreNotShownDetailsByDefault() { + void unauthenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); @@ -90,7 +90,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersAreNotShownDetailsByDefault() { + void authenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); @@ -100,7 +100,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { + void authenticatedUsersWhenAuthorizedCanBeShownDetails() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -111,7 +111,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersCanBeShownDetails() { + void unauthenticatedUsersCanBeShownDetails() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertThat(extension.health(null).getBody().getDetails()).isNotEmpty(); @@ -119,7 +119,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void detailsCanBeHiddenFromAuthenticatedUsers() { + void detailsCanBeHiddenFromAuthenticatedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); @@ -127,7 +127,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void detailsCanBeHiddenFromUnauthorizedUsers() { + void detailsCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -139,7 +139,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void detailsCanBeShownToAuthorizedUsers() { + void detailsCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -151,7 +151,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersAreNotShownComponentByDefault() { + void unauthenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); @@ -159,7 +159,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersAreNotShownComponentByDefault() { + void authenticatedUsersAreNotShownComponentByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); @@ -169,7 +169,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersWhenAuthorizedCanBeShownComponent() { + void authenticatedUsersWhenAuthorizedCanBeShownComponent() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -180,7 +180,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersCanBeShownComponent() { + void unauthenticatedUsersCanBeShownComponent() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertSimpleComponent(extension.healthForComponent(null, "simple")); @@ -188,7 +188,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentCanBeHiddenFromAuthenticatedUsers() { + void componentCanBeHiddenFromAuthenticatedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); @@ -196,7 +196,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentCanBeHiddenFromUnauthorizedUsers() { + void componentCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -208,7 +208,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentCanBeShownToAuthorizedUsers() { + void componentCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -220,7 +220,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentThatDoesNotExistMapTo404() { + void componentThatDoesNotExistMapTo404() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponent(null, "does-not-exist")); @@ -228,7 +228,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersAreNotShownComponentInstanceByDefault() { + void unauthenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound( @@ -237,7 +237,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersAreNotShownComponentInstanceByDefault() { + void authenticatedUsersAreNotShownComponentInstanceByDefault() { this.contextRunner.run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); @@ -247,7 +247,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() { + void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -258,7 +258,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersCanBeShownComponentInstance() { + void unauthenticatedUsersCanBeShownComponentInstance() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertSimpleComponent(extension.healthForComponentInstance(null, "composite", "one")); @@ -266,7 +266,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentInstanceCanBeHiddenFromAuthenticatedUsers() { + void componentInstanceCanBeHiddenFromAuthenticatedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound( @@ -275,7 +275,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentInstanceCanBeHiddenFromUnauthorizedUsers() { + void componentInstanceCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -287,7 +287,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentInstanceCanBeShownToAuthorizedUsers() { + void componentInstanceCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); @@ -299,7 +299,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void componentInstanceThatDoesNotExistMapTo404() { + void componentInstanceThatDoesNotExistMapTo404() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); assertDetailsNotFound(extension.healthForComponentInstance(null, "composite", "does-not-exist")); @@ -317,7 +317,7 @@ public class HealthEndpointWebExtensionTests { } @Test - public void roleCanBeCustomized() { + void roleCanBeCustomized() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ADMIN").run((context) -> { HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java index 6f74e1de767..329019094a4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfigurationTests.java @@ -40,26 +40,26 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class HealthIndicatorAutoConfigurationTests { +class HealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HealthIndicatorAutoConfiguration.class)); @Test - public void runWhenNoOtherIndicatorsShouldCreateDefaultApplicationHealthIndicator() { + void runWhenNoOtherIndicatorsShouldCreateDefaultApplicationHealthIndicator() { this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class) .isInstanceOf(ApplicationHealthIndicator.class)); } @Test - public void runWhenHasDefinedIndicatorShouldNotCreateDefaultApplicationHealthIndicator() { + void runWhenHasDefinedIndicatorShouldNotCreateDefaultApplicationHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) .run((context) -> assertThat(context).getBean(HealthIndicator.class) .isInstanceOf(CustomHealthIndicator.class)); } @Test - public void runWhenHasDefaultsDisabledAndNoSingleIndicatorEnabledShouldCreateDefaultApplicationHealthIndicator() { + void runWhenHasDefaultsDisabledAndNoSingleIndicatorEnabledShouldCreateDefaultApplicationHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) .withPropertyValues("management.health.defaults.enabled:false").run((context) -> assertThat(context) .getBean(HealthIndicator.class).isInstanceOf(ApplicationHealthIndicator.class)); @@ -67,7 +67,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Test - public void runWhenHasDefaultsDisabledAndSingleIndicatorEnabledShouldCreateEnabledIndicator() { + void runWhenHasDefaultsDisabledAndSingleIndicatorEnabledShouldCreateEnabledIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) .withPropertyValues("management.health.defaults.enabled:false", "management.health.custom.enabled:true") .run((context) -> assertThat(context).getBean(HealthIndicator.class) @@ -76,13 +76,13 @@ public class HealthIndicatorAutoConfigurationTests { } @Test - public void runShouldCreateOrderedHealthAggregator() { + void runShouldCreateOrderedHealthAggregator() { this.contextRunner.run((context) -> assertThat(context).getBean(HealthAggregator.class) .isInstanceOf(OrderedHealthAggregator.class)); } @Test - public void runWhenHasCustomOrderPropertyShouldCreateOrderedHealthAggregator() { + void runWhenHasCustomOrderPropertyShouldCreateOrderedHealthAggregator() { this.contextRunner.withPropertyValues("management.health.status.order:UP,DOWN").run((context) -> { OrderedHealthAggregator aggregator = context.getBean(OrderedHealthAggregator.class); Map healths = new LinkedHashMap<>(); @@ -94,7 +94,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Test - public void runWhenHasCustomHealthAggregatorShouldNotCreateOrderedHealthAggregator() { + void runWhenHasCustomHealthAggregatorShouldNotCreateOrderedHealthAggregator() { this.contextRunner.withUserConfiguration(CustomHealthAggregatorConfiguration.class) .run((context) -> assertThat(context).getBean(HealthAggregator.class) .isNotInstanceOf(OrderedHealthAggregator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java index eb8aa08d83a..fec94cbc003 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/ReactiveHealthEndpointWebExtensionTests.java @@ -46,25 +46,25 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class ReactiveHealthEndpointWebExtensionTests { +class ReactiveHealthEndpointWebExtensionTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withUserConfiguration(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class); @Test - public void runShouldCreateExtensionBeans() { + void runShouldCreateExtensionBeans() { this.contextRunner .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } @Test - public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { + void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveHealthEndpointWebExtension.class)); } @Test - public void runWithCustomHealthMappingShouldMapStatusCode() { + void runWithCustomHealthMappingShouldMapStatusCode() { this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { Object extension = context.getBean(ReactiveHealthEndpointWebExtension.class); HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils @@ -79,7 +79,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void regularAndReactiveHealthIndicatorsMatch() { + void regularAndReactiveHealthIndicatorsMatch() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") .withUserConfiguration(HealthIndicatorsConfiguration.class).run((context) -> { HealthEndpoint endpoint = context.getBean(HealthEndpoint.class); @@ -95,7 +95,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersAreNotShownDetailsByDefault() { + void unauthenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); assertThat( @@ -105,7 +105,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersAreNotShownDetailsByDefault() { + void authenticatedUsersAreNotShownDetailsByDefault() { this.contextRunner.run((context) -> { ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); @@ -116,7 +116,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { + void authenticatedUsersWhenAuthorizedCanBeShownDetails() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") .run((context) -> { ReactiveHealthEndpointWebExtension extension = context @@ -129,7 +129,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void unauthenticatedUsersCanBeShownDetails() { + void unauthenticatedUsersCanBeShownDetails() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()).isNotEmpty(); @@ -137,7 +137,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void detailsCanBeHiddenFromAuthenticatedUsers() { + void detailsCanBeHiddenFromAuthenticatedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); SecurityContext securityContext = mock(SecurityContext.class); @@ -147,7 +147,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void detailsCanBeHiddenFromUnauthorizedUsers() { + void detailsCanBeHiddenFromUnauthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { ReactiveHealthEndpointWebExtension extension = context @@ -161,7 +161,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void detailsCanBeShownToAuthorizedUsers() { + void detailsCanBeShownToAuthorizedUsers() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ACTUATOR").run((context) -> { ReactiveHealthEndpointWebExtension extension = context @@ -175,7 +175,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void roleCanBeCustomized() { + void roleCanBeCustomized() { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", "management.endpoint.health.roles=ADMIN").run((context) -> { ReactiveHealthEndpointWebExtension extension = context @@ -189,7 +189,7 @@ public class ReactiveHealthEndpointWebExtensionTests { } @Test - public void registryCanBeAltered() { + void registryCanBeAltered() { this.contextRunner.withUserConfiguration(HealthIndicatorsConfiguration.class) .withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java index 3572c7d6625..297fb9d77e3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfigurationTests.java @@ -33,20 +33,20 @@ import static org.mockito.Mockito.mock; * * @author Eddú Meléndez */ -public class InfluxDbHealthIndicatorAutoConfigurationTests { +class InfluxDbHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations .of(InfluxDbHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InfluxDbHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java index 15291409d74..f97cab9e7fc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class InfoContributorAutoConfigurationTests { +class InfoContributorAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -52,21 +52,21 @@ public class InfoContributorAutoConfigurationTests { } @Test - public void disableEnvContributor() { + void disableEnvContributor() { load("management.info.env.enabled:false"); Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test - public void defaultInfoContributorsDisabled() { + void defaultInfoContributorsDisabled() { load("management.info.defaults.enabled:false"); Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(0); } @Test - public void defaultInfoContributorsDisabledWithCustomOne() { + void defaultInfoContributorsDisabledWithCustomOne() { load(CustomInfoContributorConfiguration.class, "management.info.defaults.enabled:false"); Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).hasSize(1); @@ -75,7 +75,7 @@ public class InfoContributorAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void gitPropertiesDefaultMode() { + void gitPropertiesDefaultMode() { load(GitPropertiesConfiguration.class); Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("gitInfoContributor"); @@ -89,7 +89,7 @@ public class InfoContributorAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void gitPropertiesFullMode() { + void gitPropertiesFullMode() { load(GitPropertiesConfiguration.class, "management.info.git.mode=full"); Map content = invokeContributor( this.context.getBean("gitInfoContributor", InfoContributor.class)); @@ -101,7 +101,7 @@ public class InfoContributorAutoConfigurationTests { } @Test - public void customGitInfoContributor() { + void customGitInfoContributor() { load(CustomGitInfoContributorConfiguration.class); assertThat(this.context.getBean(GitInfoContributor.class)) .isSameAs(this.context.getBean("customGitInfoContributor")); @@ -109,7 +109,7 @@ public class InfoContributorAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void buildProperties() { + void buildProperties() { load(BuildPropertiesConfiguration.class); Map beans = this.context.getBeansOfType(InfoContributor.class); assertThat(beans).containsKeys("buildInfoContributor"); @@ -123,7 +123,7 @@ public class InfoContributorAutoConfigurationTests { } @Test - public void customBuildInfoContributor() { + void customBuildInfoContributor() { load(CustomBuildInfoContributorConfiguration.class); assertThat(this.context.getBean(BuildInfoContributor.class)) .isSameAs(this.context.getBean("customBuildInfoContributor")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java index fb13bf85adb..e670aef99c1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java @@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class InfoEndpointAutoConfigurationTests { +class InfoEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test - public void runShouldHaveEndpointBeanEvenIfDefaultIsDisabled() { + void runShouldHaveEndpointBeanEvenIfDefaultIsDisabled() { // FIXME this.contextRunner.withPropertyValues("management.endpoint.default.enabled:false") .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java index 6ac89b5bb68..4e2fb0ab38a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java @@ -33,20 +33,20 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Tim Ysewyn * @author Stephane Nicoll */ -public class IntegrationGraphEndpointAutoConfigurationTests { +class IntegrationGraphEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, IntegrationGraphEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph") .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.integrationgraph.enabled:false").run((context) -> { assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); @@ -54,7 +54,7 @@ public class IntegrationGraphEndpointAutoConfigurationTests { } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); @@ -62,7 +62,7 @@ public class IntegrationGraphEndpointAutoConfigurationTests { } @Test - public void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { + void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); noSpringIntegrationRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java index 4c497e45a33..001356cc1f7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java @@ -45,7 +45,7 @@ import org.springframework.web.bind.annotation.GetMapping; * * @author Phillip Webb */ -public class ControllerEndpointWebFluxIntegrationTests { +class ControllerEndpointWebFluxIntegrationTests { private AnnotationConfigReactiveWebApplicationContext context; @@ -56,7 +56,7 @@ public class ControllerEndpointWebFluxIntegrationTests { } @Test - public void endpointsCanBeAccessed() throws Exception { + void endpointsCanBeAccessed() throws Exception { TestSecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigReactiveWebApplicationContext(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java index ff624db3a8f..04c1ed5ac0e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java @@ -58,7 +58,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Phillip Webb * @author Andy Wilkinson */ -public class ControllerEndpointWebMvcIntegrationTests { +class ControllerEndpointWebMvcIntegrationTests { private AnnotationConfigServletWebApplicationContext context; @@ -69,7 +69,7 @@ public class ControllerEndpointWebMvcIntegrationTests { } @Test - public void endpointsAreSecureByDefault() throws Exception { + void endpointsAreSecureByDefault() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class, ExampleController.class); MockMvc mockMvc = createSecureMockMvc(); @@ -78,7 +78,7 @@ public class ControllerEndpointWebMvcIntegrationTests { } @Test - public void endpointsCanBeAccessed() throws Exception { + void endpointsCanBeAccessed() throws Exception { TestSecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java index 9af2040928b..d04bb5a2834 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java @@ -43,15 +43,15 @@ import org.springframework.web.servlet.DispatcherServlet; * @author Andy Wilkinson * @author Madhura Bhave */ -public class JerseyEndpointIntegrationTests { +class JerseyEndpointIntegrationTests { @Test - public void linksAreProvidedToAllEndpointTypes() { + void linksAreProvidedToAllEndpointTypes() { testJerseyEndpoints(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class }); } @Test - public void actuatorEndpointsWhenUserProvidedResourceConfigBeanNotAvailable() { + void actuatorEndpointsWhenUserProvidedResourceConfigBeanNotAvailable() { testJerseyEndpoints(new Class[] { EndpointsConfiguration.class }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java index 6a43e1f5e16..6bc4a40d321 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class JmxEndpointIntegrationTests { +class JmxEndpointIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, @@ -58,7 +58,7 @@ public class JmxEndpointIntegrationTests { .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); @Test - public void jmxEndpointsAreExposed() { + void jmxEndpointsAreExposed() { this.contextRunner.run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health", @@ -67,7 +67,7 @@ public class JmxEndpointIntegrationTests { } @Test - public void jmxEndpointsCanBeExcluded() { + void jmxEndpointsCanBeExcluded() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.exclude:*").run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); checkEndpointMBeans(mBeanServer, new String[0], new String[] { "beans", "conditions", "configprops", "env", @@ -77,7 +77,7 @@ public class JmxEndpointIntegrationTests { } @Test - public void singleJmxEndpointCanBeExposed() { + void singleJmxEndpointCanBeExposed() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=beans").run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); checkEndpointMBeans(mBeanServer, new String[] { "beans" }, new String[] { "conditions", "configprops", diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java index fea99f5fdd3..b613e902def 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JolokiaEndpointAutoConfigurationIntegrationTests.java @@ -58,13 +58,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "management.endpoints.web.exposure.include=jolokia") @DirtiesContext -public class JolokiaEndpointAutoConfigurationIntegrationTests { +class JolokiaEndpointAutoConfigurationIntegrationTests { @Autowired private TestRestTemplate restTemplate; @Test - public void jolokiaIsExposed() { + void jolokiaIsExposed() { ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).contains("\"agent\""); @@ -72,7 +72,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { } @Test - public void search() { + void search() { ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia/search/java.lang:*", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); @@ -80,7 +80,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { } @Test - public void read() { + void read() { ResponseEntity response = this.restTemplate.getForEntity("/actuator/jolokia/read/java.lang:type=Memory", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); @@ -88,7 +88,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests { } @Test - public void list() { + void list() { ResponseEntity response = this.restTemplate .getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java index 2d6d1ad33dc..4d42270ffa0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java @@ -51,16 +51,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class WebEndpointsAutoConfigurationIntegrationTests { +class WebEndpointsAutoConfigurationIntegrationTests { @Test - public void healthEndpointWebExtensionIsAutoConfigured() { + void healthEndpointWebExtensionIsAutoConfigured() { servletWebRunner().run((context) -> context.getBean(WebEndpointTestApplication.class)); servletWebRunner().run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); } @Test - public void healthEndpointReactiveWebExtensionIsAutoConfigured() { + void healthEndpointReactiveWebExtensionIsAutoConfigured() { reactiveWebRunner() .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java index 649136af35b..4072d8674c2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java @@ -44,7 +44,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; * @author Stephane Nicoll * @see WebFluxEndpointManagementContextConfiguration */ -public class WebFluxEndpointCorsIntegrationTests { +class WebFluxEndpointCorsIntegrationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, @@ -54,14 +54,14 @@ public class WebFluxEndpointCorsIntegrationTests { .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test - public void corsIsDisabledByDefault() { + void corsIsDisabledByDefault() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); } @Test - public void settingAllowedOriginsEnablesCors() { + void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") .run(withWebTestClient((webTestClient) -> { webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org") @@ -72,14 +72,14 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void maxAgeDefaultsTo30Minutes() { + void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); } @Test - public void maxAgeCanBeConfigured() { + void maxAgeCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", "management.endpoints.web.cors.max-age: 2400") @@ -88,7 +88,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void requestsWithDisallowedHeadersAreRejected() { + void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") @@ -97,7 +97,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void allowedHeadersCanBeConfigured() { + void allowedHeadersCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") @@ -108,7 +108,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void requestsWithDisallowedMethodsAreRejected() { + void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") .header("Origin", "spring.example.org") @@ -117,7 +117,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void allowedMethodsCanBeConfigured() { + void allowedMethodsCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", "management.endpoints.web.cors.allowed-methods:GET,HEAD") @@ -128,7 +128,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void credentialsCanBeAllowed() { + void credentialsCanBeAllowed() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", "management.endpoints.web.cors.allow-credentials:true") @@ -137,7 +137,7 @@ public class WebFluxEndpointCorsIntegrationTests { } @Test - public void credentialsCanBeDisabled() { + void credentialsCanBeDisabled() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", "management.endpoints.web.cors.allow-credentials:false") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java index ddd8052ad28..321e9dd8dec 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java @@ -41,10 +41,10 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Andy Wilkinson */ -public class WebFluxEndpointIntegrationTests { +class WebFluxEndpointIntegrationTests { @Test - public void linksAreProvidedToAllEndpointTypes() throws Exception { + void linksAreProvidedToAllEndpointTypes() throws Exception { new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java index 48f51281847..0e3598a1aa3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java @@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Stephane Nicoll * @see WebMvcEndpointManagementContextConfiguration */ -public class WebMvcEndpointCorsIntegrationTests { +class WebMvcEndpointCorsIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, @@ -59,7 +59,7 @@ public class WebMvcEndpointCorsIntegrationTests { .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test - public void corsIsDisabledByDefault() { + void corsIsDisabledByDefault() { this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc .perform(options("/actuator/beans").header("Origin", "foo.example.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) @@ -67,7 +67,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void settingAllowedOriginsEnablesCors() { + void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> { mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com") @@ -78,14 +78,14 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void maxAgeDefaultsTo30Minutes() { + void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); } @Test - public void maxAgeCanBeConfigured() { + void maxAgeCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.max-age: 2400") @@ -94,7 +94,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void requestsWithDisallowedHeadersAreRejected() { + void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> @@ -105,7 +105,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void allowedHeadersCanBeConfigured() { + void allowedHeadersCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") @@ -118,7 +118,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void requestsWithDisallowedMethodsAreRejected() { + void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") .run(withMockMvc((mockMvc) -> mockMvc .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") @@ -127,7 +127,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void allowedMethodsCanBeConfigured() { + void allowedMethodsCanBeConfigured() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allowed-methods:GET,HEAD") @@ -139,7 +139,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void credentialsCanBeAllowed() { + void credentialsCanBeAllowed() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allow-credentials:true") @@ -148,7 +148,7 @@ public class WebMvcEndpointCorsIntegrationTests { } @Test - public void credentialsCanBeDisabled() { + void credentialsCanBeDisabled() { this.contextRunner .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", "management.endpoints.web.cors.allow-credentials:false") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java index 6b77355e775..aa896726f74 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java @@ -63,7 +63,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Phillip Webb */ -public class WebMvcEndpointExposureIntegrationTests { +class WebMvcEndpointExposureIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) @@ -80,7 +80,7 @@ public class WebMvcEndpointExposureIntegrationTests { .withPropertyValues("server.port:0"); @Test - public void webEndpointsAreDisabledByDefault() { + void webEndpointsAreDisabledByDefault() { this.contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isFalse(); @@ -99,7 +99,7 @@ public class WebMvcEndpointExposureIntegrationTests { } @Test - public void webEndpointsCanBeExposed() { + void webEndpointsCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=*"); contextRunner.run((context) -> { @@ -120,7 +120,7 @@ public class WebMvcEndpointExposureIntegrationTests { } @Test - public void singleWebEndpointCanBeExposed() { + void singleWebEndpointCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner .withPropertyValues("management.endpoints.web.exposure.include=beans"); contextRunner.run((context) -> { @@ -141,7 +141,7 @@ public class WebMvcEndpointExposureIntegrationTests { } @Test - public void singleWebEndpointCanBeExcluded() { + void singleWebEndpointCanBeExcluded() { WebApplicationContextRunner contextRunner = this.contextRunner.withPropertyValues( "management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=shutdown"); contextRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java index c8f3c1057e5..8de76b934d9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java @@ -68,7 +68,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class WebMvcEndpointIntegrationTests { +class WebMvcEndpointIntegrationTests { private AnnotationConfigServletWebApplicationContext context; @@ -79,7 +79,7 @@ public class WebMvcEndpointIntegrationTests { } @Test - public void endpointsAreSecureByDefault() throws Exception { + void endpointsAreSecureByDefault() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); MockMvc mockMvc = createSecureMockMvc(); @@ -87,7 +87,7 @@ public class WebMvcEndpointIntegrationTests { } @Test - public void endpointsAreSecureByDefaultWithCustomBasePath() throws Exception { + void endpointsAreSecureByDefaultWithCustomBasePath() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context); @@ -97,7 +97,7 @@ public class WebMvcEndpointIntegrationTests { } @Test - public void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { + void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { TestSecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); @@ -110,7 +110,7 @@ public class WebMvcEndpointIntegrationTests { } @Test - public void linksAreProvidedToAllEndpointTypes() throws Exception { + void linksAreProvidedToAllEndpointTypes() throws Exception { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java index 7534e5a26c0..4b03831747e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfigurationTests.java @@ -45,7 +45,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class DataSourceHealthIndicatorAutoConfigurationTests { +class DataSourceHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -53,7 +53,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { .withPropertyValues("spring.datasource.initialization-mode=never"); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> { context.getBean(DataSourceHealthIndicator.class); assertThat(context).hasSingleBean(DataSourceHealthIndicator.class) @@ -62,7 +62,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { } @Test - public void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { + void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) .run((context) -> { assertThat(context).hasSingleBean(HealthIndicator.class); @@ -72,14 +72,14 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { } @Test - public void runShouldFilterRoutingDataSource() { + void runShouldFilterRoutingDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class) .run((context) -> assertThat(context).hasSingleBean(DataSourceHealthIndicator.class) .doesNotHaveBean(CompositeHealthIndicator.class)); } @Test - public void runWithValidationQueryPropertyShouldUseCustomQuery() { + void runWithValidationQueryPropertyShouldUseCustomQuery() { this.contextRunner .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> { @@ -90,7 +90,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests { } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("management.health.db.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java index 269e66c71ff..2bb7c081c62 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfigurationTests.java @@ -33,20 +33,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class JmsHealthIndicatorAutoConfigurationTests { +class JmsHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JmsHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.jms.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java index 0a4b0e788cc..da7ec96b310 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfigurationTests.java @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class JolokiaEndpointAutoConfigurationTests { +class JolokiaEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, @@ -55,7 +55,7 @@ public class JolokiaEndpointAutoConfigurationTests { TestConfiguration.class)); @Test - public void jolokiaServletShouldBeEnabledByDefault() { + void jolokiaServletShouldBeEnabledByDefault() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); @@ -65,7 +65,7 @@ public class JolokiaEndpointAutoConfigurationTests { } @Test - public void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() { + void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() { this.contextRunner.run((context) -> { Collection endpoints = context.getBean(ServletEndpointsSupplier.class) .getEndpoints(); @@ -74,7 +74,7 @@ public class JolokiaEndpointAutoConfigurationTests { } @Test - public void jolokiaServletWhenDisabledShouldNotBeDiscovered() { + void jolokiaServletWhenDisabledShouldNotBeDiscovered() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false") .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { Collection endpoints = context.getBean(ServletEndpointsSupplier.class) @@ -84,7 +84,7 @@ public class JolokiaEndpointAutoConfigurationTests { } @Test - public void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { + void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true") .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java index 174252a90c8..f3a297d0e08 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfigurationTests.java @@ -34,20 +34,20 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class LdapHealthIndicatorAutoConfigurationTests { +class LdapHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations .of(LdapHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LdapHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.ldap.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java index 994b81729de..368d02885b0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java @@ -34,32 +34,32 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class LiquibaseEndpointAutoConfigurationTests { +class LiquibaseEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase") .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) .withPropertyValues("management.endpoint.liquibase.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test - public void disablesCloseOfDataSourceWhenEndpointIsEnabled() { + void disablesCloseOfDataSourceWhenEndpointIsEnabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> { assertThat(context).hasSingleBean(LiquibaseEndpoint.class); @@ -69,7 +69,7 @@ public class LiquibaseEndpointAutoConfigurationTests { } @Test - public void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { + void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) .withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> { assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java index e9cefd8639e..83d3f73e3d7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java @@ -41,25 +41,25 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Christian Carriere-Tisseur */ -public class LogFileWebEndpointAutoConfigurationTests { +class LogFileWebEndpointAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); @Test - public void runWithOnlyExposedShouldNotHaveEndpointBean() { + void runWithOnlyExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile") .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test - public void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { + void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.name:test.log") .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test - public void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { + void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); @@ -67,20 +67,20 @@ public class LogFileWebEndpointAutoConfigurationTests { @Test @Deprecated - public void runWhenLoggingFileIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { + void runWhenLoggingFileIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { this.contextRunner .withPropertyValues("logging.file:test.log", "management.endpoints.web.exposure.include=logfile") .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test - public void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { + void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.path:test/logs") .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test - public void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { + void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); @@ -88,14 +88,14 @@ public class LogFileWebEndpointAutoConfigurationTests { @Test @Deprecated - public void runWhenLoggingPathIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { + void runWhenLoggingPathIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { this.contextRunner .withPropertyValues("logging.path:test/logs", "management.endpoints.web.exposure.include=logfile") .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test - public void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { + void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { this.contextRunner .withPropertyValues("management.endpoint.logfile.external-file:external.log", "management.endpoints.web.exposure.include=logfile") @@ -103,13 +103,13 @@ public class LogFileWebEndpointAutoConfigurationTests { } @Test - public void logFileWebEndpointCanBeDisabled() { + void logFileWebEndpointCanBeDisabled() { this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test - public void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { + void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { File file = new File(temp.toFile(), "logfile"); FileCopyUtils.copy("--TEST--".getBytes(), file); this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile", diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java index 79efa5414e7..de30f06f06a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java @@ -33,31 +33,31 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class LoggersEndpointAutoConfigurationTests { +class LoggersEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) .withUserConfiguration(LoggingConfiguration.class); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers") .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test - public void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { + void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none") .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java index 55cc9b8841b..6696c1aebe3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfigurationTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MailHealthIndicatorAutoConfigurationTests { +class MailHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, @@ -40,13 +40,13 @@ public class MailHealthIndicatorAutoConfigurationTests { .withPropertyValues("spring.mail.host:smtp.example.com"); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mail.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java index 3ff77c07b3c..48403bc5b20 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java @@ -28,19 +28,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class HeapDumpWebEndpointAutoConfigurationTests { +class HeapDumpWebEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withPropertyValues("management.endpoints.web.exposure.include:*") .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HeapDumpWebEndpoint.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java index 0759a6849aa..ac7fb7be205 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java @@ -29,24 +29,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ThreadDumpEndpointAutoConfigurationTests { +class ThreadDumpEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump") .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") .withPropertyValues("management.endpoint.threaddump.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java index 29ca30f469d..c35dbfa1d4c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class CompositeMeterRegistryAutoConfigurationTests { +class CompositeMeterRegistryAutoConfigurationTests { private static final String COMPOSITE_NAME = "compositeMeterRegistry"; @@ -46,7 +46,7 @@ public class CompositeMeterRegistryAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); @Test - public void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { + void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { this.contextRunner.withUserConfiguration(NoMeterRegistryConfig.class).run((context) -> { assertThat(context).hasSingleBean(MeterRegistry.class); CompositeMeterRegistry registry = context.getBean("noOpMeterRegistry", CompositeMeterRegistry.class); @@ -55,7 +55,7 @@ public class CompositeMeterRegistryAutoConfigurationTests { } @Test - public void registerWhenHasSingleMeterRegistryShouldDoNothing() { + void registerWhenHasSingleMeterRegistryShouldDoNothing() { this.contextRunner.withUserConfiguration(SingleMeterRegistryConfig.class).run((context) -> { assertThat(context).hasSingleBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -64,7 +64,7 @@ public class CompositeMeterRegistryAutoConfigurationTests { } @Test - public void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { + void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> { assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne", "meterRegistryTwo", COMPOSITE_NAME); @@ -76,7 +76,7 @@ public class CompositeMeterRegistryAutoConfigurationTests { } @Test - public void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { + void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> { assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne", "meterRegistryTwo"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java index c5100f87b42..81b089d3ac5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java @@ -36,20 +36,20 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class JvmMetricsAutoConfigurationTests { +class JvmMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test - public void autoConfiguresJvmMetrics() { + void autoConfiguresJvmMetrics() { this.contextRunner.run( (context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasSingleBean(JvmMemoryMetrics.class) .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class)); } @Test - public void allowsCustomJvmGcMetricsToBeUsed() { + void allowsCustomJvmGcMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasBean("customJvmGcMetrics") .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) @@ -57,7 +57,7 @@ public class JvmMetricsAutoConfigurationTests { } @Test - public void allowsCustomJvmMemoryMetricsToBeUsed() { + void allowsCustomJvmMemoryMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasBean("customJvmMemoryMetrics") @@ -65,7 +65,7 @@ public class JvmMetricsAutoConfigurationTests { } @Test - public void allowsCustomJvmThreadMetricsToBeUsed() { + void allowsCustomJvmThreadMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) @@ -73,7 +73,7 @@ public class JvmMetricsAutoConfigurationTests { } @Test - public void allowsCustomClassLoaderMetricsToBeUsed() { + void allowsCustomClassLoaderMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java index c0b0661b272..d557aee0a52 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java @@ -33,25 +33,25 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class KafkaMetricsAutoConfigurationTests { +class KafkaMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withPropertyValues("spring.jmx.enabled=true") .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); @Test - public void whenThereIsNoMBeanServerAutoConfigurationBacksOff() { + void whenThereIsNoMBeanServerAutoConfigurationBacksOff() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(KafkaConsumerMetrics.class)); } @Test - public void whenThereIsAnMBeanServerKafkaConsumerMetricsIsConfigured() { + void whenThereIsAnMBeanServerKafkaConsumerMetricsIsConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(KafkaConsumerMetrics.class)); } @Test - public void allowsCustomKafkaConsumerMetricsToBeUsed() { + void allowsCustomKafkaConsumerMetricsToBeUsed() { this.contextRunner.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)) .withUserConfiguration(CustomKafkaConsumerMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(KafkaConsumerMetrics.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java index 75b6c316f4e..2d5242dd804 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.actuate.autoconfigure.metrics; import io.micrometer.core.instrument.binder.logging.Log4j2Metrics; import org.apache.logging.log4j.LogManager; import org.apache.logging.slf4j.SLF4JLoggerContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -32,13 +32,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests { +class Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test - public void backsOffWhenLoggerContextIsBackedBySlf4j() { + void backsOffWhenLoggerContextIsBackedBySlf4j() { assertThat(LogManager.getContext()).isInstanceOf(SLF4JLoggerContext.class); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Log4j2Metrics.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java index e2efba0797e..8c1d2dca40c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java @@ -33,18 +33,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class LogbackMetricsAutoConfigurationTests { +class LogbackMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); @Test - public void autoConfiguresLogbackMetrics() { + void autoConfiguresLogbackMetrics() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LogbackMetrics.class)); } @Test - public void allowsCustomLogbackMetricsToBeUsed() { + void allowsCustomLogbackMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class).run( (context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java index 28fe97551af..5f54204fd12 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Jon Schneider */ -public class MeterRegistryConfigurerIntegrationTests { +class MeterRegistryConfigurerIntegrationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, @@ -54,7 +54,7 @@ public class MeterRegistryConfigurerIntegrationTests { .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test - public void binderMetricsAreSearchableFromTheComposite() { + void binderMetricsAreSearchableFromTheComposite() { this.contextRunner.run((context) -> { CompositeMeterRegistry composite = context.getBean(CompositeMeterRegistry.class); composite.get("jvm.memory.used").gauge(); @@ -64,7 +64,7 @@ public class MeterRegistryConfigurerIntegrationTests { } @Test - public void customizersAreAppliedBeforeBindersAreCreated() { + void customizersAreAppliedBeforeBindersAreCreated() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class)) @@ -74,7 +74,7 @@ public class MeterRegistryConfigurerIntegrationTests { } @Test - public void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() { + void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() { new ApplicationContextRunner().with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()) @@ -88,7 +88,7 @@ public class MeterRegistryConfigurerIntegrationTests { } @Test - public void counterIsIncrementedOncePerEventWithCompositeMeterRegistry() { + void counterIsIncrementedOncePerEventWithCompositeMeterRegistry() { new ApplicationContextRunner() .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, PrometheusMetricsExportAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java index 6440af65d5d..4b909d198ba 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerTests.java @@ -46,7 +46,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Phillip Webb * @author Andy Wilkinson */ -public class MeterRegistryConfigurerTests { +class MeterRegistryConfigurerTests { private List binders = new ArrayList<>(); @@ -76,7 +76,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureWhenCompositeShouldApplyCustomizer() { + void configureWhenCompositeShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -86,7 +86,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldApplyCustomizer() { + void configureShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -95,7 +95,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldApplyFilter() { + void configureShouldApplyFilter() { this.filters.add(this.mockFilter); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -104,7 +104,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldApplyBinder() { + void configureShouldApplyBinder() { this.binders.add(this.mockBinder); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -113,7 +113,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldApplyBinderToComposite() { + void configureShouldApplyBinderToComposite() { this.binders.add(this.mockBinder); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); @@ -123,7 +123,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldNotApplyBinderWhenCompositeExists() { + void configureShouldNotApplyBinderWhenCompositeExists() { this.binders.add(this.mockBinder); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); @@ -132,7 +132,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureShouldBeCalledInOrderCustomizerFilterBinder() { + void configureShouldBeCalledInOrderCustomizerFilterBinder() { this.customizers.add(this.mockCustomizer); this.filters.add(this.mockFilter); this.binders.add(this.mockBinder); @@ -146,7 +146,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureWhenAddToGlobalRegistryShouldAddToGlobalRegistry() { + void configureWhenAddToGlobalRegistryShouldAddToGlobalRegistry() { MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), true, false); try { @@ -159,7 +159,7 @@ public class MeterRegistryConfigurerTests { } @Test - public void configureWhenNotAddToGlobalRegistryShouldAddToGlobalRegistry() { + void configureWhenNotAddToGlobalRegistryShouldAddToGlobalRegistry() { MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); configurer.configure(this.mockRegistry); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java index 67c5b0acbc5..94ea37f4170 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Jon Schneider * @author Andy Wilkinson */ -public class MeterRegistryCustomizerTests { +class MeterRegistryCustomizerTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, @@ -45,7 +45,7 @@ public class MeterRegistryCustomizerTests { .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test - public void commonTagsAreAppliedToAutoConfiguredBinders() { + void commonTagsAreAppliedToAutoConfiguredBinders() { this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); registry.get("jvm.memory.used").tags("region", "us-east-1").gauge(); @@ -53,7 +53,7 @@ public class MeterRegistryCustomizerTests { } @Test - public void commonTagsAreAppliedBeforeRegistryIsInjectableElsewhere() { + void commonTagsAreAppliedBeforeRegistryIsInjectableElsewhere() { this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); registry.get("my.thing").tags("region", "us-east-1").gauge(); @@ -61,7 +61,7 @@ public class MeterRegistryCustomizerTests { } @Test - public void customizersCanBeAppliedToSpecificRegistryTypes() { + void customizersCanBeAppliedToSpecificRegistryTypes() { this.contextRunner.withUserConfiguration(MeterRegistryCustomizerConfiguration.class).run((context) -> { MeterRegistry prometheus = context.getBean(PrometheusMeterRegistry.class); prometheus.get("jvm.memory.used").tags("job", "myjob").gauge(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java index faed39bf97c..f63da5faaef 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java @@ -31,46 +31,46 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MeterValueTests { +class MeterValueTests { @Test - public void getValueForDistributionSummaryWhenFromLongShouldReturnLongValue() { + void getValueForDistributionSummaryWhenFromLongShouldReturnLongValue() { MeterValue meterValue = MeterValue.valueOf(123L); assertThat(meterValue.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123); } @Test - public void getValueForDistributionSummaryWhenFromNumberStringShouldReturnLongValue() { + void getValueForDistributionSummaryWhenFromNumberStringShouldReturnLongValue() { MeterValue meterValue = MeterValue.valueOf("123"); assertThat(meterValue.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123); } @Test - public void getValueForDistributionSummaryWhenFromDurationStringShouldReturnNull() { + void getValueForDistributionSummaryWhenFromDurationStringShouldReturnNull() { MeterValue meterValue = MeterValue.valueOf("123ms"); assertThat(meterValue.getValue(Type.DISTRIBUTION_SUMMARY)).isNull(); } @Test - public void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() { + void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() { MeterValue meterValue = MeterValue.valueOf(123L); assertThat(meterValue.getValue(Type.TIMER)).isEqualTo(123000000); } @Test - public void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() { + void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() { MeterValue meterValue = MeterValue.valueOf("123"); assertThat(meterValue.getValue(Type.TIMER)).isEqualTo(123000000); } @Test - public void getValueForTimerWhenFromDurationStringShouldReturnDurationNanos() { + void getValueForTimerWhenFromDurationStringShouldReturnDurationNanos() { MeterValue meterValue = MeterValue.valueOf("123ms"); assertThat(meterValue.getValue(Type.TIMER)).isEqualTo(123000000); } @Test - public void getValueForOthersShouldReturnNull() { + void getValueForOthersShouldReturnNull() { MeterValue meterValue = MeterValue.valueOf("123"); assertThat(meterValue.getValue(Type.COUNTER)).isNull(); assertThat(meterValue.getValue(Type.GAUGE)).isNull(); @@ -79,7 +79,7 @@ public class MeterValueTests { } @Test - public void valueOfShouldWorkInBinder() { + void valueOfShouldWorkInBinder() { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of("duration=10ms", "long=20").applyTo(environment); assertThat(Binder.get(environment).bind("duration", Bindable.of(MeterValue.class)).get().getValue(Type.TIMER)) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java index ad8d28d992f..181378b07f4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java @@ -40,12 +40,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class MetricsAutoConfigurationIntegrationTests { +class MetricsAutoConfigurationIntegrationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()); @Test - public void propertyBasedMeterFilteringIsAutoConfigured() { + void propertyBasedMeterFilteringIsAutoConfigured() { this.contextRunner.withPropertyValues("management.metrics.enable.my.org=false").run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); registry.timer("my.org.timer"); @@ -54,7 +54,7 @@ public class MetricsAutoConfigurationIntegrationTests { } @Test - public void propertyBasedCommonTagsIsAutoConfigured() { + void propertyBasedCommonTagsIsAutoConfigured() { this.contextRunner .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") .run((context) -> { @@ -66,13 +66,13 @@ public class MetricsAutoConfigurationIntegrationTests { } @Test - public void simpleMeterRegistryIsUsedAsAFallback() { + void simpleMeterRegistryIsUsedAsAFallback() { this.contextRunner.run( (context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test - public void emptyCompositeIsCreatedWhenNoMeterRegistriesAreAutoConfigured() { + void emptyCompositeIsCreatedWhenNoMeterRegistriesAreAutoConfigured() { new ApplicationContextRunner().with(MetricsRun.limitedTo()).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); @@ -81,14 +81,14 @@ public class MetricsAutoConfigurationIntegrationTests { } @Test - public void noCompositeIsCreatedWhenASingleMeterRegistryIsAutoConfigured() { + void noCompositeIsCreatedWhenASingleMeterRegistryIsAutoConfigured() { new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class)) .run((context) -> assertThat(context.getBean(MeterRegistry.class)) .isInstanceOf(GraphiteMeterRegistry.class)); } @Test - public void noCompositeIsCreatedWithMultipleRegistriesAndOneThatIsPrimary() { + void noCompositeIsCreatedWithMultipleRegistriesAndOneThatIsPrimary() { new ApplicationContextRunner() .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, JmxMetricsExportAutoConfiguration.class)) @@ -98,7 +98,7 @@ public class MetricsAutoConfigurationIntegrationTests { } @Test - public void compositeCreatedWithMultipleRegistries() { + void compositeCreatedWithMultipleRegistries() { new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, JmxMetricsExportAutoConfiguration.class)).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java index 63cbf2059b0..6737aba194a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java @@ -41,25 +41,25 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class MetricsAutoConfigurationTests { +class MetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); @Test - public void autoConfiguresAClock() { + void autoConfiguresAClock() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Clock.class)); } @Test - public void allowsACustomClockToBeUsed() { + void allowsACustomClockToBeUsed() { this.contextRunner.withUserConfiguration(CustomClockConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); } @SuppressWarnings("unchecked") @Test - public void configuresMeterRegistries() { + void configuresMeterRegistries() { this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class).run((context) -> { MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils.getField(meterRegistry, "filters"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java index 3bc7a4179e2..81541b0d47e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MissingRequiredConfigurationFailureAnalyzerTests.java @@ -27,17 +27,17 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link MissingRequiredConfigurationFailureAnalyzer}. * * @author Andy Wilkinson */ -public class MissingRequiredConfigurationFailureAnalyzerTests { +class MissingRequiredConfigurationFailureAnalyzerTests { @Test - public void analyzesMissingRequiredConfiguration() { + void analyzesMissingRequiredConfiguration() { FailureAnalysis analysis = new MissingRequiredConfigurationFailureAnalyzer() .analyze(createFailure(MissingAccountIdConfiguration.class)); assertThat(analysis).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java index eae3a694d9a..992d4040eb3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java @@ -42,79 +42,79 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Jon Schneider * @author Artsiom Yudovin */ -public class PropertiesMeterFilterTests { +class PropertiesMeterFilterTests { @Test - public void createWhenPropertiesIsNullShouldThrowException() { + void createWhenPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null)) .withMessageContaining("Properties must not be null"); } @Test - public void acceptWhenHasNoEnabledPropertiesShouldReturnNeutral() { + void acceptWhenHasNoEnabledPropertiesShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties()); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void acceptWhenHasNoMatchingEnabledPropertyShouldReturnNeutral() { + void acceptWhenHasNoMatchingEnabledPropertyShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.something.else=false")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void acceptWhenHasEnableFalseShouldReturnDeny() { + void acceptWhenHasEnableFalseShouldReturnDeny() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring.boot=false")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test - public void acceptWhenHasEnableTrueShouldReturnNeutral() { + void acceptWhenHasEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring.boot=true")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void acceptWhenHasHigherEnableFalseShouldReturnDeny() { + void acceptWhenHasHigherEnableFalseShouldReturnDeny() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring=false")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test - public void acceptWhenHasHigherEnableTrueShouldReturnNeutral() { + void acceptWhenHasHigherEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.spring=true")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void acceptWhenHasHigherEnableFalseExactEnableTrueShouldReturnNeutral() { + void acceptWhenHasHigherEnableFalseExactEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.spring=false", "enable.spring.boot=true")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void acceptWhenHasHigherEnableTrueExactEnableFalseShouldReturnDeny() { + void acceptWhenHasHigherEnableTrueExactEnableFalseShouldReturnDeny() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.spring=true", "enable.spring.boot=false")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test - public void acceptWhenHasAllEnableFalseShouldReturnDeny() { + void acceptWhenHasAllEnableFalseShouldReturnDeny() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("enable.all=false")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.DENY); } @Test - public void acceptWhenHasAllEnableFalseButHigherEnableTrueShouldReturnNeutral() { + void acceptWhenHasAllEnableFalseButHigherEnableTrueShouldReturnNeutral() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("enable.all=false", "enable.spring=true")); assertThat(filter.accept(createMeterId("spring.boot"))).isEqualTo(MeterFilterReply.NEUTRAL); } @Test - public void configureWhenHasHistogramTrueShouldSetPercentilesHistogramToTrue() { + void configureWhenHasHistogramTrueShouldSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -122,7 +122,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHistogramFalseShouldSetPercentilesHistogramToFalse() { + void configureWhenHasHistogramFalseShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -130,7 +130,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherHistogramTrueShouldSetPercentilesHistogramToTrue() { + void configureWhenHasHigherHistogramTrueShouldSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -138,7 +138,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherHistogramFalseShouldSetPercentilesHistogramToFalse() { + void configureWhenHasHigherHistogramFalseShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -146,7 +146,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherHistogramTrueAndLowerFalseShouldSetPercentilesHistogramToFalse() { + void configureWhenHasHigherHistogramTrueAndLowerFalseShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true", "distribution.percentiles-histogram.spring.boot=false")); @@ -155,7 +155,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherHistogramFalseAndLowerTrueShouldSetPercentilesHistogramToFalse() { + void configureWhenHasHigherHistogramFalseAndLowerTrueShouldSetPercentilesHistogramToFalse() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false", "distribution.percentiles-histogram.spring.boot=true")); @@ -164,7 +164,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenAllHistogramTrueSetPercentilesHistogramToTrue() { + void configureWhenAllHistogramTrueSetPercentilesHistogramToTrue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.all=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -172,7 +172,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasPercentilesShouldSetPercentilesToValue() { + void configureWhenHasPercentilesShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring.boot=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) @@ -180,7 +180,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherPercentilesShouldSetPercentilesToValue() { + void configureWhenHasHigherPercentilesShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) @@ -188,7 +188,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherPercentilesAndLowerShouldSetPercentilesToHigher() { + void configureWhenHasHigherPercentilesAndLowerShouldSetPercentilesToHigher() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.percentiles.spring=1,1.5,2", "distribution.percentiles.spring.boot=3,3.5,4")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) @@ -196,7 +196,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenAllPercentilesSetShouldSetPercentilesToValue() { + void configureWhenAllPercentilesSetShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.all=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) @@ -204,7 +204,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasSlaShouldSetSlaToValue() { + void configureWhenHasSlaShouldSetSlaToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.sla.spring.boot=1,2,3")); assertThat( @@ -213,7 +213,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherSlaShouldSetPercentilesToValue() { + void configureWhenHasHigherSlaShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.sla.spring=1,2,3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) @@ -221,7 +221,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherSlaAndLowerShouldSetSlaToHigher() { + void configureWhenHasHigherSlaAndLowerShouldSetSlaToHigher() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.sla.spring=1,2,3", "distribution.sla.spring.boot=4,5,6")); assertThat( @@ -230,7 +230,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasMinimumExpectedValueShouldSetMinimumExpectedToValue() { + void configureWhenHasMinimumExpectedValueShouldSetMinimumExpectedToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring.boot=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -238,7 +238,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherMinimumExpectedValueShouldSetMinimumExpectedValueToValue() { + void configureWhenHasHigherMinimumExpectedValueShouldSetMinimumExpectedValueToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -246,7 +246,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherMinimumExpectedValueAndLowerShouldSetMinimumExpectedValueToHigher() { + void configureWhenHasHigherMinimumExpectedValueAndLowerShouldSetMinimumExpectedValueToHigher() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.minimum-expected-value.spring=10", "distribution.minimum-expected-value.spring.boot=50")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -254,7 +254,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasMaximumExpectedValueShouldSetMaximumExpectedToValue() { + void configureWhenHasMaximumExpectedValueShouldSetMaximumExpectedToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring.boot=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -262,7 +262,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherMaximumExpectedValueShouldSetMaximumExpectedValueToValue() { + void configureWhenHasHigherMaximumExpectedValueShouldSetMaximumExpectedValueToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) @@ -270,7 +270,7 @@ public class PropertiesMeterFilterTests { } @Test - public void configureWhenHasHigherMaximumExpectedValueAndLowerShouldSetMaximumExpectedValueToHigher() { + void configureWhenHasHigherMaximumExpectedValueAndLowerShouldSetMaximumExpectedValueToHigher() { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000", "distribution.maximum-expected-value.spring.boot=10000")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java index 1e240d93e7b..d9cb37e7f1d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ServiceLevelAgreementBoundaryTests.java @@ -26,22 +26,22 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ServiceLevelAgreementBoundaryTests { +class ServiceLevelAgreementBoundaryTests { @Test - public void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() { + void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() { ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary.valueOf(123L); assertThat(sla.getValue(Type.TIMER)).isEqualTo(123000000); } @Test - public void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() { + void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() { ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary.valueOf("123"); assertThat(sla.getValue(Type.TIMER)).isEqualTo(123000000); } @Test - public void getValueForTimerWhenFromDurationStringShouldReturnDurationNanos() { + void getValueForTimerWhenFromDurationStringShouldReturnDurationNanos() { ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary.valueOf("123ms"); assertThat(sla.getValue(Type.TIMER)).isEqualTo(123000000); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java index a3e5737dc9f..7a5d3fd2d9f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java @@ -35,41 +35,41 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class SystemMetricsAutoConfigurationTests { +class SystemMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); @Test - public void autoConfiguresUptimeMetrics() { + void autoConfiguresUptimeMetrics() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class)); } @Test - public void allowsCustomUptimeMetricsToBeUsed() { + void allowsCustomUptimeMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class).run( (context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); } @Test - public void autoConfiguresProcessorMetrics() { + void autoConfiguresProcessorMetrics() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class)); } @Test - public void allowsCustomProcessorMetricsToBeUsed() { + void allowsCustomProcessorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomProcessorMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) .hasBean("customProcessorMetrics")); } @Test - public void autoConfiguresFileDescriptorMetrics() { + void autoConfiguresFileDescriptorMetrics() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class)); } @Test - public void allowsCustomFileDescriptorMetricsToBeUsed() { + void allowsCustomFileDescriptorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomFileDescriptorMetricsConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) .hasBean("customFileDescriptorMetrics")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java index 08b789db073..48fc19121aa 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java @@ -31,14 +31,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class RabbitMetricsAutoConfigurationTests { +class RabbitMetricsAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration( AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); @Test - public void autoConfiguredConnectionFactoryIsInstrumented() { + void autoConfiguredConnectionFactoryIsInstrumented() { this.contextRunner.run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); registry.get("rabbitmq.connections").meter(); @@ -46,7 +46,7 @@ public class RabbitMetricsAutoConfigurationTests { } @Test - public void rabbitmqNativeConnectionFactoryInstrumentationCanBeDisabled() { + void rabbitmqNativeConnectionFactoryInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.rabbitmq=false").run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("rabbitmq.connections").meter()).isNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java index 334925de6d8..fb40f572065 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java @@ -33,14 +33,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CacheMetricsAutoConfigurationTests { +class CacheMetricsAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withUserConfiguration(CachingConfiguration.class).withConfiguration( AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); @Test - public void autoConfiguredCacheManagerIsInstrumented() { + void autoConfiguredCacheManagerIsInstrumented() { this.contextRunner.withPropertyValues("spring.cache.type=caffeine", "spring.cache.cache-names=cache1,cache2") .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -50,7 +50,7 @@ public class CacheMetricsAutoConfigurationTests { } @Test - public void autoConfiguredNonSupportedCacheManagerIsIgnored() { + void autoConfiguredNonSupportedCacheManagerIsIgnored() { this.contextRunner.withPropertyValues("spring.cache.type=simple", "spring.cache.cache-names=cache1,cache2") .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -62,7 +62,7 @@ public class CacheMetricsAutoConfigurationTests { } @Test - public void cacheInstrumentationCanBeDisabled() { + void cacheInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", "spring.cache.cache-names=cache1").run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java index c3845dddee8..75f92fe48cc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java @@ -34,25 +34,25 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AppOpticsMetricsExportAutoConfigurationTests { +class AppOpticsMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(AppOpticsMeterRegistry.class).hasSingleBean(AppOpticsConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.appoptics.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) @@ -60,14 +60,14 @@ public class AppOpticsMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) .hasSingleBean(AppOpticsConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") .withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) @@ -75,7 +75,7 @@ public class AppOpticsMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.metrics.export.appoptics.api-token=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> { AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java index 68641989592..819cdeabef1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesConfigAdapterTests.java @@ -27,7 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AppOpticsPropertiesConfigAdapterTests +class AppOpticsPropertiesConfigAdapterTests extends StepRegistryPropertiesConfigAdapterTests { @Override @@ -41,21 +41,21 @@ public class AppOpticsPropertiesConfigAdapterTests } @Test - public void whenPropertiesUrisIsSetAdapterUriReturnsIt() { + void whenPropertiesUrisIsSetAdapterUriReturnsIt() { AppOpticsProperties properties = createProperties(); properties.setUri("https://appoptics.example.com/v1/measurements"); assertThat(createConfigAdapter(properties).uri()).isEqualTo("https://appoptics.example.com/v1/measurements"); } @Test - public void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { + void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { AppOpticsProperties properties = createProperties(); properties.setApiToken("ABC123"); assertThat(createConfigAdapter(properties).apiToken()).isEqualTo("ABC123"); } @Test - public void whenPropertiesHostTagIsSetAdapterHostTagReturnsIt() { + void whenPropertiesHostTagIsSetAdapterHostTagReturnsIt() { AppOpticsProperties properties = createProperties(); properties.setHostTag("node"); assertThat(createConfigAdapter(properties).hostTag()).isEqualTo("node"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesTests.java index 28a600dc6cb..2ca99cf87ab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AppOpticsPropertiesTests extends StepRegistryPropertiesTests { +class AppOpticsPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { AppOpticsProperties properties = new AppOpticsProperties(); AppOpticsConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java index 1465c893f9a..6eea5438e16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class AtlasMetricsExportAutoConfigurationTests { +class AtlasMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.atlas.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) @@ -59,19 +59,19 @@ public class AtlasMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(AtlasMeterRegistry.class).hasBean("customRegistry").hasSingleBean(AtlasConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { AtlasMeterRegistry registry = context.getBean(AtlasMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java index 7d424a58d57..7d345ad9c16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AtlasPropertiesTests { +class AtlasPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { AtlasProperties properties = new AtlasProperties(); AtlasConfig config = (key) -> null; assertThat(properties.getStep()).isEqualTo(config.step()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java index 581e24d9a41..24dd90c5ff8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class DatadogMetricsExportAutoConfigurationTests { +class DatadogMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class)); } @Test - public void failsWithoutAnApiKey() { + void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasFailed()); } @Test - public void autoConfiguresConfigAndMeterRegistry() { + void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.datadog.api-key=abcde") .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) @@ -59,7 +59,7 @@ public class DatadogMetricsExportAutoConfigurationTests { } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.datadog.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) @@ -67,13 +67,13 @@ public class DatadogMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(DatadogMeterRegistry.class).hasSingleBean(DatadogConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.datadog.api-key=abcde") .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) @@ -81,7 +81,7 @@ public class DatadogMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.datadog.api-key=abcde").run((context) -> { DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesConfigAdapterTests.java index b5a9907268b..622e3cc4a3d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesConfigAdapterTests.java @@ -25,10 +25,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class DatadogPropertiesConfigAdapterTests { +class DatadogPropertiesConfigAdapterTests { @Test - public void uriCanBeSet() { + void uriCanBeSet() { DatadogProperties properties = new DatadogProperties(); properties.setUri("https://app.example.com/api/v1/series"); properties.setApiKey("my-key"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesTests.java index a736e04e98a..d8fdb2c90ba 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class DatadogPropertiesTests extends StepRegistryPropertiesTests { +class DatadogPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { DatadogProperties properties = new DatadogProperties(); DatadogConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java index ad549f82b7d..67304eb9890 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java @@ -37,31 +37,31 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class DynatraceMetricsExportAutoConfigurationTests { +class DynatraceMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class)); } @Test - public void failsWithoutAUri() { + void failsWithoutAUri() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasFailed()); } @Test - public void autoConfiguresConfigAndMeterRegistry() { + void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(mandatoryProperties()) .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasSingleBean(DynatraceConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.dynatrace.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) @@ -69,21 +69,21 @@ public class DynatraceMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasSingleBean(DynatraceConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).with(mandatoryProperties()) .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(DynatraceConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(mandatoryProperties()).run((context) -> { DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java index 3e3802c1165..688873bf632 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java @@ -25,31 +25,31 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class DynatracePropertiesConfigAdapterTests { +class DynatracePropertiesConfigAdapterTests { @Test - public void whenPropertiesUriIsSetAdapterUriReturnsIt() { + void whenPropertiesUriIsSetAdapterUriReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setUri("https://dynatrace.example.com"); assertThat(new DynatracePropertiesConfigAdapter(properties).uri()).isEqualTo("https://dynatrace.example.com"); } @Test - public void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { + void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setApiToken("123ABC"); assertThat(new DynatracePropertiesConfigAdapter(properties).apiToken()).isEqualTo("123ABC"); } @Test - public void whenPropertiesDeviceIdIsSetAdapterDeviceIdReturnsIt() { + void whenPropertiesDeviceIdIsSetAdapterDeviceIdReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setDeviceId("dev-1"); assertThat(new DynatracePropertiesConfigAdapter(properties).deviceId()).isEqualTo("dev-1"); } @Test - public void whenPropertiesTechnologyTypeIsSetAdapterTechnologyTypeReturnsIt() { + void whenPropertiesTechnologyTypeIsSetAdapterTechnologyTypeReturnsIt() { DynatraceProperties properties = new DynatraceProperties(); properties.setTechnologyType("tech-1"); assertThat(new DynatracePropertiesConfigAdapter(properties).technologyType()).isEqualTo("tech-1"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java index ac0ff8d8bcc..51a3708bb0b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class DynatracePropertiesTests extends StepRegistryPropertiesTests { +class DynatracePropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { DynatraceProperties properties = new DynatraceProperties(); DynatraceConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java index db5fd8c4c65..79d3f875a6f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ElasticMetricsExportAutoConfigurationTests { +class ElasticMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class)); } @Test - public void autoConfiguresConfigAndMeterRegistry() { + void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.elastic.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) @@ -59,13 +59,13 @@ public class ElasticMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) @@ -73,7 +73,7 @@ public class ElasticMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { ElasticMeterRegistry registry = context.getBean(ElasticMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java index a05d66d2bb2..f3a27b724a3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesConfigAdapterTests.java @@ -25,52 +25,52 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ElasticPropertiesConfigAdapterTests { +class ElasticPropertiesConfigAdapterTests { @Test - public void whenPropertiesHostsIsSetAdapterHostsReturnsIt() { + void whenPropertiesHostsIsSetAdapterHostsReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setHost("https://elastic.example.com"); assertThat(new ElasticPropertiesConfigAdapter(properties).host()).isEqualTo("https://elastic.example.com"); } @Test - public void whenPropertiesIndexIsSetAdapterIndexReturnsIt() { + void whenPropertiesIndexIsSetAdapterIndexReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setIndex("test-metrics"); assertThat(new ElasticPropertiesConfigAdapter(properties).index()).isEqualTo("test-metrics"); } @Test - public void whenPropertiesIndexDateFormatIsSetAdapterIndexDateFormatReturnsIt() { + void whenPropertiesIndexDateFormatIsSetAdapterIndexDateFormatReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setIndexDateFormat("yyyy"); assertThat(new ElasticPropertiesConfigAdapter(properties).indexDateFormat()).isEqualTo("yyyy"); } @Test - public void whenPropertiesTimestampFieldNameIsSetAdapterTimestampFieldNameReturnsIt() { + void whenPropertiesTimestampFieldNameIsSetAdapterTimestampFieldNameReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setTimestampFieldName("@test"); assertThat(new ElasticPropertiesConfigAdapter(properties).timestampFieldName()).isEqualTo("@test"); } @Test - public void whenPropertiesAutoCreateIndexIsSetAdapterAutoCreateIndexReturnsIt() { + void whenPropertiesAutoCreateIndexIsSetAdapterAutoCreateIndexReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setAutoCreateIndex(false); assertThat(new ElasticPropertiesConfigAdapter(properties).autoCreateIndex()).isFalse(); } @Test - public void whenPropertiesUserNameIsSetAdapterUserNameReturnsIt() { + void whenPropertiesUserNameIsSetAdapterUserNameReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setUserName("alice"); assertThat(new ElasticPropertiesConfigAdapter(properties).userName()).isEqualTo("alice"); } @Test - public void whenPropertiesPasswordIsSetAdapterPasswordReturnsIt() { + void whenPropertiesPasswordIsSetAdapterPasswordReturnsIt() { ElasticProperties properties = new ElasticProperties(); properties.setPassword("secret"); assertThat(new ElasticPropertiesConfigAdapter(properties).password()).isEqualTo("secret"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java index af097088bc4..407c968c14f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ElasticPropertiesTests extends StepRegistryPropertiesTests { +class ElasticPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { ElasticProperties properties = new ElasticProperties(); ElasticConfig config = ElasticConfig.DEFAULT; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java index 1f90b35f5a4..f9d440d3b2c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class GangliaMetricsExportAutoConfigurationTests { +class GangliaMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.ganglia.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) @@ -59,20 +59,20 @@ public class GangliaMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(GangliaConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { GangliaMeterRegistry registry = context.getBean(GangliaMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesTests.java index bd8e6536981..a840f380788 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class GangliaPropertiesTests { +class GangliaPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { GangliaProperties properties = new GangliaProperties(); GangliaConfig config = GangliaConfig.DEFAULT; assertThat(properties.isEnabled()).isEqualTo(config.enabled()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java index 024ad86867c..65b501a8366 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java @@ -36,18 +36,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class GraphiteMetricsExportAutoConfigurationTests { +class GraphiteMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class)); } @Test - public void autoConfiguresUseTagsAsPrefix() { + void autoConfiguresUseTagsAsPrefix() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app").run((context) -> { assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); @@ -58,13 +58,13 @@ public class GraphiteMetricsExportAutoConfigurationTests { } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(GraphiteMeterRegistry.class).hasSingleBean(GraphiteConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.graphite.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) @@ -72,21 +72,21 @@ public class GraphiteMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) .hasSingleBean(GraphiteConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(GraphiteConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphitePropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphitePropertiesTests.java index 19efb0ddc4b..54aef944a34 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphitePropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphitePropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class GraphitePropertiesTests { +class GraphitePropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { GraphiteProperties properties = new GraphiteProperties(); GraphiteConfig config = GraphiteConfig.DEFAULT; assertThat(properties.isEnabled()).isEqualTo(config.enabled()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java index f08f1243afe..5a8e75ea7e8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java @@ -35,24 +35,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class HumioMetricsExportAutoConfigurationTests { +class HumioMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class)); } @Test - public void autoConfiguresConfigAndMeterRegistry() { + void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.humio.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) @@ -60,19 +60,19 @@ public class HumioMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(HumioMeterRegistry.class).hasBean("customRegistry").hasSingleBean(HumioConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { HumioMeterRegistry registry = context.getBean(HumioMeterRegistry.class); new JvmMemoryMetrics().bindTo(registry); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java index 0182af7bf04..12de2a72911 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java @@ -27,24 +27,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class HumioPropertiesConfigAdapterTests { +class HumioPropertiesConfigAdapterTests { @Test - public void whenApiTokenIsSetAdapterApiTokenReturnsIt() { + void whenApiTokenIsSetAdapterApiTokenReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setApiToken("ABC123"); assertThat(new HumioPropertiesConfigAdapter(properties).apiToken()).isEqualTo("ABC123"); } @Test - public void whenPropertiesRepositoryIsSetAdapterRepositoryReturnsIt() { + void whenPropertiesRepositoryIsSetAdapterRepositoryReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setRepository("test"); assertThat(new HumioPropertiesConfigAdapter(properties).repository()).isEqualTo("test"); } @Test - public void whenPropertiesTagsIsSetAdapterTagsReturnsIt() { + void whenPropertiesTagsIsSetAdapterTagsReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setTags(Collections.singletonMap("name", "test")); assertThat(new HumioPropertiesConfigAdapter(properties).tags()) @@ -52,7 +52,7 @@ public class HumioPropertiesConfigAdapterTests { } @Test - public void whenPropertiesUriIsSetAdapterUriReturnsIt() { + void whenPropertiesUriIsSetAdapterUriReturnsIt() { HumioProperties properties = new HumioProperties(); properties.setUri("https://humio.example.com"); assertThat(new HumioPropertiesConfigAdapter(properties).uri()).isEqualTo("https://humio.example.com"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesTests.java index 3aed805b4f6..336bcb66720 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class HumioPropertiesTests extends StepRegistryPropertiesTests { +class HumioPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { HumioProperties properties = new HumioProperties(); HumioConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java index 3bc0f1d9ea1..783c1f3c1ef 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class InfluxMetricsExportAutoConfigurationTests { +class InfluxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.influx.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) @@ -59,19 +59,19 @@ public class InfluxMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(InfluxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(InfluxConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { InfluxMeterRegistry registry = context.getBean(InfluxMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java index 44f9cf0d0f9..c45eb100277 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class InfluxPropertiesTests extends StepRegistryPropertiesTests { +class InfluxPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { InfluxProperties properties = new InfluxProperties(); InfluxConfig config = InfluxConfig.DEFAULT; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java index db221dc3851..7838c2a80d5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java @@ -34,43 +34,43 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class JmxMetricsExportAutoConfigurationTests { +class JmxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( (context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.jmx.enabled=false").run((context) -> assertThat(context) .doesNotHaveBean(JmxMeterRegistry.class).doesNotHaveBean(JmxConfig.class)); } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(JmxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(JmxConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { JmxMeterRegistry registry = context.getBean(JmxMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesTests.java index 3a08adc4336..67b1ed81603 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxPropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class JmxPropertiesTests { +class JmxPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { JmxProperties properties = new JmxProperties(); JmxConfig config = JmxConfig.DEFAULT; assertThat(properties.getDomain()).isEqualTo(config.domain()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java index 769b2a8590d..b87a4a14620 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class KairosMetricsExportAutoConfigurationTests { +class KairosMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigAndMeterRegistry() { + void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.kairos.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) @@ -59,19 +59,19 @@ public class KairosMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(KairosMeterRegistry.class).hasBean("customRegistry").hasSingleBean(KairosConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { KairosMeterRegistry registry = context.getBean(KairosMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java index 28795b1c5fa..777e28fd181 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java @@ -27,7 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class KairosPropertiesConfigAdapterTests +class KairosPropertiesConfigAdapterTests extends StepRegistryPropertiesConfigAdapterTests { @Override @@ -41,7 +41,7 @@ public class KairosPropertiesConfigAdapterTests } @Test - public void whenPropertiesUrisIsSetAdapterUriReturnsIt() { + void whenPropertiesUrisIsSetAdapterUriReturnsIt() { KairosProperties properties = createProperties(); properties.setUri("https://kairos.example.com:8080/api/v1/datapoints"); assertThat(createConfigAdapter(properties).uri()) @@ -49,14 +49,14 @@ public class KairosPropertiesConfigAdapterTests } @Test - public void whenPropertiesUserNameIsSetAdapterUserNameReturnsIt() { + void whenPropertiesUserNameIsSetAdapterUserNameReturnsIt() { KairosProperties properties = createProperties(); properties.setUserName("alice"); assertThat(createConfigAdapter(properties).userName()).isEqualTo("alice"); } @Test - public void whenPropertiesPasswordIsSetAdapterPasswordReturnsIt() { + void whenPropertiesPasswordIsSetAdapterPasswordReturnsIt() { KairosProperties properties = createProperties(); properties.setPassword("secret"); assertThat(createConfigAdapter(properties).password()).isEqualTo("secret"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java index 18d641267ec..7d63395859e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class KairosPropertiesTests extends StepRegistryPropertiesTests { +class KairosPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { KairosProperties properties = new KairosProperties(); KairosConfig config = KairosConfig.DEFAULT; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java index a1cfe81d780..5f309c5c561 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java @@ -35,32 +35,32 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class NewRelicMetricsExportAutoConfigurationTests { +class NewRelicMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class)); } @Test - public void failsWithoutAnApiKey() { + void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.account-id=12345") .run((context) -> assertThat(context).hasFailed()); } @Test - public void failsWithoutAnAccountId() { + void failsWithoutAnAccountId() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde") .run((context) -> assertThat(context).hasFailed()); } @Test - public void autoConfiguresWithAccountIdAndApiKey() { + void autoConfiguresWithAccountIdAndApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") @@ -69,7 +69,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) @@ -77,7 +77,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { } @Test - public void allowsConfigToBeCustomized() { + void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") @@ -85,7 +85,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { } @Test - public void allowsRegistryToBeCustomized() { + void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=12345") @@ -94,7 +94,7 @@ public class NewRelicMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner .withPropertyValues("management.metrics.export.newrelic.api-key=abcde", "management.metrics.export.newrelic.account-id=abcde") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesTests.java index d63452634cd..af63e34ee02 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class NewRelicPropertiesTests extends StepRegistryPropertiesTests { +class NewRelicPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { NewRelicProperties properties = new NewRelicProperties(); NewRelicConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java index f95e8edfd99..e306bbab50e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java @@ -44,32 +44,32 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @ExtendWith(OutputCaptureExtension.class) -public class PrometheusMetricsExportAutoConfigurationTests { +class PrometheusMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigCollectorRegistryAndMeterRegistry() { + void autoConfiguresItsConfigCollectorRegistryAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.export.prometheus.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class) @@ -77,7 +77,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) .hasBean("customRegistry").hasSingleBean(CollectorRegistry.class) @@ -85,7 +85,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomCollectorRegistryToBeUsed() { + void allowsCustomCollectorRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomCollectorRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) .hasBean("customCollectorRegistry").hasSingleBean(CollectorRegistry.class) @@ -93,7 +93,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void addsScrapeEndpointToManagementContext() { + void addsScrapeEndpointToManagementContext() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=prometheus") @@ -101,14 +101,14 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void scrapeEndpointNotAddedToManagementContextWhenNotExposed() { + void scrapeEndpointNotAddedToManagementContextWhenNotExposed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test - public void scrapeEndpointCanBeDisabled() { + void scrapeEndpointCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withPropertyValues("management.endpoints.web.exposure.include=prometheus") .withPropertyValues("management.endpoint.prometheus.enabled=false") @@ -117,14 +117,14 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void allowsCustomScrapeEndpointToBeUsed() { + void allowsCustomScrapeEndpointToBeUsed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withUserConfiguration(CustomEndpointConfiguration.class).run((context) -> assertThat(context) .hasBean("customEndpoint").hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test - public void withPushGatewayEnabled(CapturedOutput capturedOutput) { + void withPushGatewayEnabled(CapturedOutput capturedOutput) { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") .withUserConfiguration(BaseConfiguration.class).run((context) -> { @@ -135,7 +135,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { @Test @Deprecated - public void withCustomLegacyPushGatewayURL(CapturedOutput capturedOutput) { + void withCustomLegacyPushGatewayURL(CapturedOutput capturedOutput) { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", "management.metrics.export.prometheus.pushgateway.base-url=localhost:9090") @@ -146,7 +146,7 @@ public class PrometheusMetricsExportAutoConfigurationTests { } @Test - public void withCustomPushGatewayURL() { + void withCustomPushGatewayURL() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", "management.metrics.export.prometheus.pushgateway.base-url=https://example.com:8080") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesTests.java index d1f69d51089..993986a80b5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class PrometheusPropertiesTests { +class PrometheusPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { PrometheusProperties properties = new PrometheusProperties(); PrometheusConfig config = PrometheusConfig.DEFAULT; assertThat(properties.isDescriptions()).isEqualTo(config.descriptions()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java index 43f9744c554..fbad715910f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/properties/StepRegistryPropertiesConfigAdapterTests.java @@ -37,28 +37,28 @@ public abstract class StepRegistryPropertiesConfigAdapterTests

assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class)); } @Test - public void failsWithoutAnAccessToken() { + void failsWithoutAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasFailed()); } @Test - public void autoConfiguresWithAnAccessToken() { + void autoConfiguresWithAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) @@ -59,7 +59,7 @@ public class SignalFxMetricsExportAutoConfigurationTests { } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.signalfx.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) @@ -67,7 +67,7 @@ public class SignalFxMetricsExportAutoConfigurationTests { } @Test - public void allowsConfigToBeCustomized() { + void allowsConfigToBeCustomized() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class) @@ -76,7 +76,7 @@ public class SignalFxMetricsExportAutoConfigurationTests { } @Test - public void allowsRegistryToBeCustomized() { + void allowsRegistryToBeCustomized() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(CustomRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class) @@ -84,7 +84,7 @@ public class SignalFxMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.metrics.export.signalfx.access-token=abcde") .withUserConfiguration(BaseConfiguration.class).run((context) -> { SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesTests.java index 1987a491998..19ea7cdc9d8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class SignalFxPropertiesTests extends StepRegistryPropertiesTests { +class SignalFxPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { SignalFxProperties properties = new SignalFxProperties(); SignalFxConfig config = (key) -> null; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java index a086d08b15e..75d42881507 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java @@ -37,19 +37,19 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class SimpleMetricsExportAutoConfigurationTests { +class SimpleMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); @Test - public void autoConfiguresConfigAndMeterRegistry() { + void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(SimpleMeterRegistry.class).hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class)); } @Test - public void backsOffWhenSpecificallyDisabled() { + void backsOffWhenSpecificallyDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.simple.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) @@ -57,13 +57,13 @@ public class SimpleMetricsExportAutoConfigurationTests { } @Test - public void allowsConfigToBeCustomized() { + void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); } @Test - public void backsOffEntirelyWithCustomMeterRegistry() { + void backsOffEntirelyWithCustomMeterRegistry() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(MeterRegistry.class).hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesTests.java index 9f2b8486c36..dc58979f14c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesTests.java @@ -24,10 +24,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll */ -public class SimplePropertiesTests { +class SimplePropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { SimpleProperties properties = new SimpleProperties(); SimpleConfig config = SimpleConfig.DEFAULT; assertThat(properties.getStep()).isEqualTo(config.step()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java index abbc5c44ab2..a9cca4372af 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java @@ -35,44 +35,44 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class StatsdMetricsExportAutoConfigurationTests { +class StatsdMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class)); } @Test - public void autoConfiguresItsConfigMeterRegistryAndMetrics() { + void autoConfiguresItsConfigMeterRegistryAndMetrics() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) .hasSingleBean(StatsdConfig.class).hasSingleBean(StatsdMetrics.class)); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.export.statsd.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) .doesNotHaveBean(StatsdConfig.class)); } @Test - public void allowsCustomConfigToBeUsed() { + void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class).hasBean("customConfig")); } @Test - public void allowsCustomRegistryToBeUsed() { + void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(StatsdMeterRegistry.class).hasBean("customRegistry").hasSingleBean(StatsdConfig.class)); } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { StatsdMeterRegistry registry = context.getBean(StatsdMeterRegistry.class); assertThat(registry.isClosed()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java index 932f86db600..006e4e5e2dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class StatsdPropertiesTests { +class StatsdPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { StatsdProperties properties = new StatsdProperties(); StatsdConfig config = StatsdConfig.DEFAULT; assertThat(properties.isEnabled()).isEqualTo(config.enabled()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java index e17fca046e2..b930e4e0c87 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java @@ -34,24 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Jon Schneider */ -public class WavefrontMetricsExportAutoConfigurationTests { +class WavefrontMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WavefrontMetricsExportAutoConfiguration.class)); @Test - public void backsOffWithoutAClock() { + void backsOffWithoutAClock() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class)); } @Test - public void failsWithoutAnApiTokenWhenPublishingDirectly() { + void failsWithoutAnApiTokenWhenPublishingDirectly() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context).hasFailed()); } @Test - public void autoConfigurationCanBeDisabled() { + void autoConfigurationCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.wavefront.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) @@ -59,7 +59,7 @@ public class WavefrontMetricsExportAutoConfigurationTests { } @Test - public void allowsConfigToBeCustomized() { + void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(Clock.class) .hasSingleBean(WavefrontMeterRegistry.class).hasSingleBean(WavefrontConfig.class) @@ -67,7 +67,7 @@ public class WavefrontMetricsExportAutoConfigurationTests { } @Test - public void allowsRegistryToBeCustomized() { + void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) .withPropertyValues("management.metrics.export.wavefront.api-token=abcde") .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(WavefrontConfig.class) @@ -75,7 +75,7 @@ public class WavefrontMetricsExportAutoConfigurationTests { } @Test - public void stopsMeterRegistryWhenContextIsClosed() { + void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("management.metrics.export.wavefront.api-token=abcde").run((context) -> { WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java index 5b6675e12cf..7771204902c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesConfigAdapterTests.java @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class WavefrontPropertiesConfigAdapterTests +class WavefrontPropertiesConfigAdapterTests extends StepRegistryPropertiesConfigAdapterTests { @Override @@ -43,28 +43,28 @@ public class WavefrontPropertiesConfigAdapterTests } @Test - public void whenPropertiesUriIsSetAdapterUriReturnsIt() { + void whenPropertiesUriIsSetAdapterUriReturnsIt() { WavefrontProperties properties = createProperties(); properties.setUri(URI.create("https://wavefront.example.com")); assertThat(createConfigAdapter(properties).uri()).isEqualTo("https://wavefront.example.com"); } @Test - public void whenPropertiesSourceIsSetAdapterSourceReturnsIt() { + void whenPropertiesSourceIsSetAdapterSourceReturnsIt() { WavefrontProperties properties = createProperties(); properties.setSource("test"); assertThat(createConfigAdapter(properties).source()).isEqualTo("test"); } @Test - public void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { + void whenPropertiesApiTokenIsSetAdapterApiTokenReturnsIt() { WavefrontProperties properties = createProperties(); properties.setApiToken("ABC123"); assertThat(createConfigAdapter(properties).apiToken()).isEqualTo("ABC123"); } @Test - public void whenPropertiesGlobalPrefixIsSetAdapterGlobalPrefixReturnsIt() { + void whenPropertiesGlobalPrefixIsSetAdapterGlobalPrefixReturnsIt() { WavefrontProperties properties = createProperties(); properties.setGlobalPrefix("test"); assertThat(createConfigAdapter(properties).globalPrefix()).isEqualTo("test"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesTests.java index 82340a4856f..d17dd6c990c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontPropertiesTests.java @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class WavefrontPropertiesTests extends StepRegistryPropertiesTests { +class WavefrontPropertiesTests extends StepRegistryPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { WavefrontProperties properties = new WavefrontProperties(); WavefrontConfig config = WavefrontConfig.DEFAULT_DIRECT; assertStepRegistryDefaultValues(properties, config); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java index da2fd1dc8a5..50f1361fa14 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java @@ -51,7 +51,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Tommy Ludwig */ -public class DataSourcePoolMetricsAutoConfigurationTests { +class DataSourcePoolMetricsAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true").with(MetricsRun.simple()) @@ -59,7 +59,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { .withUserConfiguration(BaseConfiguration.class); @Test - public void autoConfiguredDataSourceIsInstrumented() { + void autoConfiguredDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .run((context) -> { context.getBean(DataSource.class).getConnection().getMetaData(); @@ -69,7 +69,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void dataSourceInstrumentationCanBeDisabled() { + void dataSourceInstrumentationCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withPropertyValues("management.metrics.enable.jdbc=false").run((context) -> { context.getBean(DataSource.class).getConnection().getMetaData(); @@ -79,7 +79,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void allDataSourcesCanBeInstrumented() { + void allDataSourcesCanBeInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); @@ -91,7 +91,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void autoConfiguredHikariDataSourceIsInstrumented() { + void autoConfiguredHikariDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .run((context) -> { context.getBean(DataSource.class).getConnection(); @@ -101,7 +101,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDataSourceInitialization() { + void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDataSourceInitialization() { this.contextRunner.withPropertyValues("spring.datasource.schema:db/create-custom-schema.sql") .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean(DataSource.class).getConnection(); @@ -111,7 +111,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void hikariCanBeInstrumentedAfterThePoolHasBeenSealed() { + void hikariCanBeInstrumentedAfterThePoolHasBeenSealed() { this.contextRunner.withUserConfiguration(HikariSealingConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { assertThat(context).hasNotFailed(); @@ -122,7 +122,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void hikariDataSourceInstrumentationCanBeDisabled() { + void hikariDataSourceInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.hikaricp=false") .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean(DataSource.class).getConnection(); @@ -132,7 +132,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void allHikariDataSourcesCanBeInstrumented() { + void allHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean("firstDataSource", DataSource.class).getConnection(); @@ -144,7 +144,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void someHikariDataSourcesCanBeInstrumented() { + void someHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(MixedDataSourcesConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean("firstDataSource", DataSource.class).getConnection(); @@ -156,7 +156,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void hikariProxiedDataSourceCanBeInstrumented() { + void hikariProxiedDataSourceCanBeInstrumented() { this.contextRunner.withUserConfiguration(ProxiedHikariDataSourcesConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { context.getBean("proxiedDataSource", DataSource.class).getConnection(); @@ -168,7 +168,7 @@ public class DataSourcePoolMetricsAutoConfigurationTests { } @Test - public void hikariDataSourceIsInstrumentedWithoutMetadataProvider() { + void hikariDataSourceIsInstrumentedWithoutMetadataProvider() { this.contextRunner.withUserConfiguration(OneHikariDataSourceConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(DataSourcePoolMetadataProvider.class); context.getBean("hikariDataSource", DataSource.class).getConnection(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java index ca0fad58fee..d144d68764a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java @@ -56,7 +56,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Michael Weirauch * @author Michael Simons */ -public class JerseyServerMetricsAutoConfigurationTests { +class JerseyServerMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); @@ -69,24 +69,24 @@ public class JerseyServerMetricsAutoConfigurationTests { .withUserConfiguration(ResourceConfiguration.class).withPropertyValues("server.port:0"); @Test - public void shouldOnlyBeActiveInWebApplicationContext() { + void shouldOnlyBeActiveInWebApplicationContext() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ResourceConfigCustomizer.class)); } @Test - public void shouldProvideAllNecessaryBeans() { + void shouldProvideAllNecessaryBeans() { this.webContextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyTagsProvider.class) .hasSingleBean(ResourceConfigCustomizer.class)); } @Test - public void shouldHonorExistingTagProvider() { + void shouldHonorExistingTagProvider() { this.webContextRunner.withUserConfiguration(CustomJerseyTagsProviderConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); } @Test - public void httpRequestsAreTimed() { + void httpRequestsAreTimed() { this.webContextRunner.run((context) -> { doRequest(context); MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -96,7 +96,7 @@ public class JerseyServerMetricsAutoConfigurationTests { } @Test - public void noHttpRequestsTimedWhenJerseyInstrumentationMissingFromClasspath() { + void noHttpRequestsTimedWhenJerseyInstrumentationMissingFromClasspath() { this.webContextRunner.withClassLoader(new FilteredClassLoader(MetricsApplicationEventListener.class)) .run((context) -> { doRequest(context); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java index 1dda84788a7..f04a805d8ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java @@ -56,7 +56,7 @@ import static org.mockito.Mockito.mock; * @author Rui Figueira * @author Stephane Nicoll */ -public class HibernateMetricsAutoConfigurationTests { +class HibernateMetricsAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -64,7 +64,7 @@ public class HibernateMetricsAutoConfigurationTests { .withUserConfiguration(BaseConfiguration.class); @Test - public void autoConfiguredEntityManagerFactoryWithStatsIsInstrumented() { + void autoConfiguredEntityManagerFactoryWithStatsIsInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") .run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); @@ -73,7 +73,7 @@ public class HibernateMetricsAutoConfigurationTests { } @Test - public void autoConfiguredEntityManagerFactoryWithoutStatsIsNotInstrumented() { + void autoConfiguredEntityManagerFactoryWithoutStatsIsNotInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:false") .run((context) -> { context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); @@ -83,7 +83,7 @@ public class HibernateMetricsAutoConfigurationTests { } @Test - public void entityManagerFactoryInstrumentationCanBeDisabled() { + void entityManagerFactoryInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.hibernate=false", "spring.jpa.properties.hibernate.generate_statistics:true").run((context) -> { context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); @@ -93,7 +93,7 @@ public class HibernateMetricsAutoConfigurationTests { } @Test - public void allEntityManagerFactoriesCanBeInstrumented() { + void allEntityManagerFactoriesCanBeInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class).run((context) -> { context.getBean("firstEntityManagerFactory", EntityManagerFactory.class) @@ -106,7 +106,7 @@ public class HibernateMetricsAutoConfigurationTests { } @Test - public void entityManagerFactoryInstrumentationIsDisabledIfNotHibernateSessionFactory() { + void entityManagerFactoryInstrumentationIsDisabledIfNotHibernateSessionFactory() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { // ensure EntityManagerFactory is not a Hibernate SessionFactory @@ -118,7 +118,7 @@ public class HibernateMetricsAutoConfigurationTests { } @Test - public void entityManagerFactoryInstrumentationIsDisabledIfHibernateIsNotAvailable() { + void entityManagerFactoryInstrumentationIsDisabledIfHibernateIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(SessionFactory.class)) .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java index 5685be8ce79..c8a6ecaf17a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java @@ -83,7 +83,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MetricsIntegrationTests.MetricsApp.class, properties = "management.metrics.use-global-registry=false") -public class MetricsIntegrationTests { +class MetricsIntegrationTests { @Autowired private ApplicationContext context; @@ -99,7 +99,7 @@ public class MetricsIntegrationTests { @SuppressWarnings("unchecked") @Test - public void restTemplateIsInstrumented() { + void restTemplateIsInstrumented() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.external).build(); server.expect(once(), requestTo("/api/external")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); @@ -108,20 +108,20 @@ public class MetricsIntegrationTests { } @Test - public void requestMappingIsInstrumented() { + void requestMappingIsInstrumented() { this.loopback.getForObject("/api/people", Set.class); assertThat(this.registry.get("http.server.requests").timer().count()).isEqualTo(1); } @Test - public void automaticallyRegisteredBinders() { + void automaticallyRegisteredBinders() { assertThat(this.context.getBeansOfType(MeterBinder.class).values()) .hasAtLeastOneElementOfType(LogbackMetrics.class).hasAtLeastOneElementOfType(JvmMemoryMetrics.class); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void metricsFilterRegisteredForAsyncDispatches() { + void metricsFilterRegisteredForAsyncDispatches() { Map filterRegistrations = this.context .getBeansOfType(FilterRegistrationBean.class); assertThat(filterRegistrations).containsKey("webMvcMetricsFilter"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java index 18699e119cd..ce733aa2e03 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsConfigurationTests.java @@ -48,14 +48,14 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * @author Raheela Aslam */ @ExtendWith(OutputCaptureExtension.class) -public class RestTemplateMetricsConfigurationTests { +class RestTemplateMetricsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @Test - public void restTemplateCreatedWithBuilderIsInstrumented() { + void restTemplateCreatedWithBuilderIsInstrumented() { this.contextRunner.run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); RestTemplateBuilder builder = context.getBean(RestTemplateBuilder.class); @@ -64,7 +64,7 @@ public class RestTemplateMetricsConfigurationTests { } @Test - public void restTemplateCanBeCustomizedManually() { + void restTemplateCanBeCustomizedManually() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(MetricsRestTemplateCustomizer.class); RestTemplateBuilder customBuilder = new RestTemplateBuilder() @@ -75,7 +75,7 @@ public class RestTemplateMetricsConfigurationTests { } @Test - public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { + void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(2); @@ -85,7 +85,7 @@ public class RestTemplateMetricsConfigurationTests { } @Test - public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { + void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(3); @@ -96,7 +96,7 @@ public class RestTemplateMetricsConfigurationTests { } @Test - public void autoTimeRequestsCanBeConfigured() { + void autoTimeRequestsCanBeConfigured() { this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { @@ -110,7 +110,7 @@ public class RestTemplateMetricsConfigurationTests { } @Test - public void backsOffWhenRestTemplateBuilderIsMissing() { + void backsOffWhenRestTemplateBuilderIsMissing() { new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(HttpClientMetricsAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java index c0ce0b7c067..d024660b9d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/WebClientMetricsConfigurationTests.java @@ -52,14 +52,14 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll */ @ExtendWith(OutputCaptureExtension.class) -public class WebClientMetricsConfigurationTests { +class WebClientMetricsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration( AutoConfigurations.of(WebClientAutoConfiguration.class, HttpClientMetricsAutoConfiguration.class)); @Test - public void webClientCreatedWithBuilderIsInstrumented() { + void webClientCreatedWithBuilderIsInstrumented() { this.contextRunner.run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); WebClient.Builder builder = context.getBean(WebClient.Builder.class); @@ -68,13 +68,13 @@ public class WebClientMetricsConfigurationTests { } @Test - public void shouldNotOverrideCustomTagsProvider() { + void shouldNotOverrideCustomTagsProvider() { this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class).run((context) -> assertThat(context) .getBeans(WebClientExchangeTagsProvider.class).hasSize(1).containsKey("customTagsProvider")); } @Test - public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { + void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(2); @@ -84,7 +84,7 @@ public class WebClientMetricsConfigurationTests { } @Test - public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { + void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { MeterRegistry registry = getInitializedMeterRegistry(context); assertThat(registry.get("http.client.requests").meters()).hasSize(3); @@ -95,7 +95,7 @@ public class WebClientMetricsConfigurationTests { } @Test - public void autoTimeRequestsCanBeConfigured() { + void autoTimeRequestsCanBeConfigured() { this.contextRunner.withPropertyValues("management.metrics.web.client.request.autotime.enabled=true", "management.metrics.web.client.request.autotime.percentiles=0.5,0.7", "management.metrics.web.client.request.autotime.percentiles-histogram=true").run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java index 04db0852313..9ee1fe34110 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java @@ -44,10 +44,10 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class JettyMetricsAutoConfigurationTests { +class JettyMetricsAutoConfigurationTests { @Test - public void autoConfiguresThreadPoolMetricsWithEmbeddedServletJetty() { + void autoConfiguresThreadPoolMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class)) @@ -62,7 +62,7 @@ public class JettyMetricsAutoConfigurationTests { } @Test - public void autoConfiguresThreadPoolMetricsWithEmbeddedReactiveJetty() { + void autoConfiguresThreadPoolMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class)) @@ -76,7 +76,7 @@ public class JettyMetricsAutoConfigurationTests { } @Test - public void allowsCustomJettyServerThreadPoolMetricsBinderToBeUsed() { + void allowsCustomJettyServerThreadPoolMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java index d3d90bcb5f7..1c38188347b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfigurationTests.java @@ -45,13 +45,13 @@ import static org.mockito.Mockito.mock; * @author Dmytro Nosan */ @ExtendWith(OutputCaptureExtension.class) -public class WebFluxMetricsAutoConfigurationTests { +class WebFluxMetricsAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class)); @Test - public void shouldProvideWebFluxMetricsBeans() { + void shouldProvideWebFluxMetricsBeans() { this.contextRunner.run((context) -> { assertThat(context).getBeans(MetricsWebFilter.class).hasSize(1); assertThat(context).getBeans(DefaultWebFluxTagsProvider.class).hasSize(1); @@ -59,14 +59,14 @@ public class WebFluxMetricsAutoConfigurationTests { } @Test - public void shouldNotOverrideCustomTagsProvider() { + void shouldNotOverrideCustomTagsProvider() { this.contextRunner.withUserConfiguration(CustomWebFluxTagsProviderConfig.class) .run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class).hasSize(1) .containsKey("customWebFluxTagsProvider")); } @Test - public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { + void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { @@ -78,7 +78,7 @@ public class WebFluxMetricsAutoConfigurationTests { } @Test - public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { + void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { @@ -90,7 +90,7 @@ public class WebFluxMetricsAutoConfigurationTests { } @Test - public void metricsAreNotRecordedIfAutoTimeRequestsIsDisabled() { + void metricsAreNotRecordedIfAutoTimeRequestsIsDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) .withPropertyValues("management.metrics.web.server.request.autotime.enabled=false").run((context) -> { @@ -101,7 +101,7 @@ public class WebFluxMetricsAutoConfigurationTests { @Test @Deprecated - public void metricsAreNotRecordedIfAutoTimeRequestsIsDisabledWithDeprecatedProperty() { + void metricsAreNotRecordedIfAutoTimeRequestsIsDisabledWithDeprecatedProperty() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .withUserConfiguration(TestController.class) .withPropertyValues("management.metrics.web.server.auto-time-requests=false").run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java index f115035f308..f4dbc4834c1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfigurationTests.java @@ -64,19 +64,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Tadaya Tsuyukubo */ @ExtendWith(OutputCaptureExtension.class) -public class WebMvcMetricsAutoConfigurationTests { +class WebMvcMetricsAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); @Test - public void backsOffWhenMeterRegistryIsMissing() { + void backsOffWhenMeterRegistryIsMissing() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(WebMvcTagsProvider.class)); } @Test - public void definesTagsProviderAndFilterWhenMeterRegistryIsPresent() { + void definesTagsProviderAndFilterWhenMeterRegistryIsPresent() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); assertThat(context).hasSingleBean(FilterRegistrationBean.class); @@ -86,7 +86,7 @@ public class WebMvcMetricsAutoConfigurationTests { } @Test - public void tagsProviderBacksOff() { + void tagsProviderBacksOff() { this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class); assertThat(context).hasSingleBean(TestWebMvcTagsProvider.class); @@ -94,7 +94,7 @@ public class WebMvcMetricsAutoConfigurationTests { } @Test - public void filterRegistrationHasExpectedDispatcherTypesAndOrder() { + void filterRegistrationHasExpectedDispatcherTypesAndOrder() { this.contextRunner.run((context) -> { FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", @@ -104,7 +104,7 @@ public class WebMvcMetricsAutoConfigurationTests { } @Test - public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { + void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestController.class) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { @@ -116,7 +116,7 @@ public class WebMvcMetricsAutoConfigurationTests { } @Test - public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { + void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestController.class) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { @@ -128,7 +128,7 @@ public class WebMvcMetricsAutoConfigurationTests { } @Test - public void autoTimeRequestsCanBeConfigured() { + void autoTimeRequestsCanBeConfigured() { this.contextRunner.withUserConfiguration(TestController.class) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withPropertyValues("management.metrics.web.server.request.autotime.enabled=true", @@ -146,7 +146,7 @@ public class WebMvcMetricsAutoConfigurationTests { @Test @SuppressWarnings("rawtypes") - public void longTaskTimingInterceptorIsRegistered() { + void longTaskTimingInterceptorIsRegistered() { this.contextRunner.withUserConfiguration(TestController.class) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .run((context) -> assertThat(context.getBean(RequestMappingHandlerMapping.class)) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java index ef568e8dde9..90909ea787b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java @@ -51,10 +51,10 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class TomcatMetricsAutoConfigurationTests { +class TomcatMetricsAutoConfigurationTests { @Test - public void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { + void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { resetTomcatState(); new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, @@ -71,7 +71,7 @@ public class TomcatMetricsAutoConfigurationTests { } @Test - public void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { + void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { resetTomcatState(); new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, @@ -87,14 +87,14 @@ public class TomcatMetricsAutoConfigurationTests { } @Test - public void autoConfiguresTomcatMetricsWithStandaloneTomcat() { + void autoConfiguresTomcatMetricsWithStandaloneTomcat() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) .withUserConfiguration(MeterRegistryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); } @Test - public void allowsCustomTomcatMetricsBinderToBeUsed() { + void allowsCustomTomcatMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) @@ -102,7 +102,7 @@ public class TomcatMetricsAutoConfigurationTests { } @Test - public void allowsCustomTomcatMetricsToBeUsed() { + void allowsCustomTomcatMetricsToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java index d007c67a0c6..25fa7c3a896 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfigurationTests.java @@ -33,20 +33,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MongoHealthIndicatorAutoConfigurationTests { +class MongoHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java index bc8c4a74e91..3ebb15b2425 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfigurationTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Yulin Qin */ -public class MongoReactiveHealthIndicatorAutoConfigurationTests { +class MongoReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -44,13 +44,13 @@ public class MongoReactiveHealthIndicatorAutoConfigurationTests { MongoReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) .doesNotHaveBean(MongoHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) .doesNotHaveBean(MongoHealthIndicator.class).hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java index 85a6b09f041..13fa40e080c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfigurationTests.java @@ -39,27 +39,27 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Stephane Nicoll */ -public class Neo4jHealthIndicatorAutoConfigurationTests { +class Neo4jHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(Neo4jConfiguration.class).withConfiguration(AutoConfigurations .of(Neo4jHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Neo4jHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.neo4j.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); } @Test - public void defaultIndicatorCanBeReplaced() { + void defaultIndicatorCanBeReplaced() { this.contextRunner.withUserConfiguration(CustomIndicatorConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Neo4jHealthIndicator.class); assertThat(context).doesNotHaveBean(ApplicationHealthIndicator.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java index eec9a8872b0..542bf23c975 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorAutoConfigurationTests.java @@ -33,21 +33,21 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class RedisReactiveHealthIndicatorAutoConfigurationTests { +class RedisReactiveHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicatorAutoConfiguration.class) .doesNotHaveBean(RedisHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) .doesNotHaveBean(RedisHealthIndicator.class).hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java index 9e4eb761ed1..ab89b695993 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java @@ -33,30 +33,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ScheduledTasksEndpointAutoConfigurationTests { +class ScheduledTasksEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); @Test - public void endpointIsAutoConfigured() { + void endpointIsAutoConfigured() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=scheduledtasks") .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); } @Test - public void endpointNotAutoConfiguredWhenNotExposed() { + void endpointNotAutoConfiguredWhenNotExposed() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test - public void endpointCanBeDisabled() { + void endpointCanBeDisabled() { this.contextRunner.withPropertyValues("management.endpoint.scheduledtasks.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test - public void endpointBacksOffWhenUserProvidedEndpointIsPresent() { + void endpointBacksOffWhenUserProvidedEndpointIsPresent() { this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class).run( (context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class).hasBean("customEndpoint")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java index 449718e1340..2b0b18088cc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java @@ -51,10 +51,10 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Phillip Webb */ -public class EndpointRequestTests { +class EndpointRequestTests { @Test - public void toAnyEndpointShouldMatchEndpointPath() { + void toAnyEndpointShouldMatchEndpointPath() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher).matches("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); @@ -62,7 +62,7 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointShouldMatchEndpointPathWithTrailingSlash() { + void toAnyEndpointShouldMatchEndpointPathWithTrailingSlash() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher).matches("/actuator/foo/"); assertMatcher(matcher).matches("/actuator/bar/"); @@ -70,7 +70,7 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointWhenBasePathIsEmptyShouldNotMatchLinks() { + void toAnyEndpointWhenBasePathIsEmptyShouldNotMatchLinks() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); @@ -79,37 +79,37 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointShouldNotMatchOtherPath() { + void toAnyEndpointShouldNotMatchOtherPath() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher).doesNotMatch("/actuator/baz"); } @Test - public void toEndpointClassShouldMatchEndpointPath() { + void toEndpointClassShouldMatchEndpointPath() { ServerWebExchangeMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).matches("/actuator/foo"); } @Test - public void toEndpointClassShouldNotMatchOtherPath() { + void toEndpointClassShouldNotMatchOtherPath() { ServerWebExchangeMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/bar"); } @Test - public void toEndpointIdShouldMatchEndpointPath() { + void toEndpointIdShouldMatchEndpointPath() { ServerWebExchangeMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).matches("/actuator/foo"); } @Test - public void toEndpointIdShouldNotMatchOtherPath() { + void toEndpointIdShouldNotMatchOtherPath() { ServerWebExchangeMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); } @Test - public void toLinksShouldOnlyMatchLinks() { + void toLinksShouldOnlyMatchLinks() { ServerWebExchangeMatcher matcher = EndpointRequest.toLinks(); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); @@ -118,7 +118,7 @@ public class EndpointRequestTests { } @Test - public void toLinksWhenBasePathEmptyShouldNotMatch() { + void toLinksWhenBasePathEmptyShouldNotMatch() { ServerWebExchangeMatcher matcher = EndpointRequest.toLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/actuator/foo"); @@ -127,7 +127,7 @@ public class EndpointRequestTests { } @Test - public void excludeByClassShouldNotMatchExcluded() { + void excludeByClassShouldNotMatchExcluded() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, BazServletEndpoint.class); List> endpoints = new ArrayList<>(); @@ -142,7 +142,7 @@ public class EndpointRequestTests { } @Test - public void excludeByClassShouldNotMatchLinksIfExcluded() { + void excludeByClassShouldNotMatchLinksIfExcluded() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() .excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); @@ -150,7 +150,7 @@ public class EndpointRequestTests { } @Test - public void excludeByIdShouldNotMatchExcluded() { + void excludeByIdShouldNotMatchExcluded() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); @@ -158,14 +158,14 @@ public class EndpointRequestTests { } @Test - public void excludeByIdShouldNotMatchLinksIfExcluded() { + void excludeByIdShouldNotMatchLinksIfExcluded() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test - public void excludeLinksShouldNotMatchBasePath() { + void excludeLinksShouldNotMatchBasePath() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); assertMatcher(matcher).doesNotMatch("/actuator"); assertMatcher(matcher).matches("/actuator/foo"); @@ -173,7 +173,7 @@ public class EndpointRequestTests { } @Test - public void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { + void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); @@ -182,7 +182,7 @@ public class EndpointRequestTests { } @Test - public void noEndpointPathsBeansShouldNeverMatch() { + void noEndpointPathsBeansShouldNeverMatch() { ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/foo"); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/bar"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java index b640a097112..54f4e879f89 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java @@ -62,7 +62,7 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ReactiveManagementWebSecurityAutoConfigurationTests { +class ReactiveManagementWebSecurityAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration( @@ -73,17 +73,17 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { ReactiveManagementWebSecurityAutoConfiguration.class)); @Test - public void permitAllForHealth() { + void permitAllForHealth() { this.contextRunner.run((context) -> assertThat(getAuthenticateHeader(context, "/actuator/health")).isNull()); } @Test - public void permitAllForInfo() { + void permitAllForInfo() { this.contextRunner.run((context) -> assertThat(getAuthenticateHeader(context, "/actuator/info")).isNull()); } @Test - public void securesEverythingElse() { + void securesEverythingElse() { this.contextRunner.run((context) -> { assertThat(getAuthenticateHeader(context, "/actuator").get(0)).contains("Basic realm="); assertThat(getAuthenticateHeader(context, "/foo").toString()).contains("Basic realm="); @@ -91,7 +91,7 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Test - public void usesMatchersBasedOffConfiguredActuatorBasePath() { + void usesMatchersBasedOffConfiguredActuatorBasePath() { this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/").run((context) -> { assertThat(getAuthenticateHeader(context, "/health")).isNull(); assertThat(getAuthenticateHeader(context, "/foo").get(0)).contains("Basic realm="); @@ -99,7 +99,7 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Test - public void backsOffIfCustomSecurityIsAdded() { + void backsOffIfCustomSecurityIsAdded() { this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class).run((context) -> { assertThat(getLocationHeader(context, "/actuator/health").toString()).contains("/login"); assertThat(getLocationHeader(context, "/foo")).isNull(); @@ -107,7 +107,7 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Test - public void backOffIfReactiveOAuth2ResourceServerAutoConfigurationPresent() { + void backOffIfReactiveOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") .run((context) -> assertThat(context) @@ -115,7 +115,7 @@ public class ReactiveManagementWebSecurityAutoConfigurationTests { } @Test - public void backsOffWhenWebFilterChainProxyBeanPresent() { + void backsOffWhenWebFilterChainProxyBeanPresent() { this.contextRunner.withUserConfiguration(WebFilterChainProxyConfiguration.class).run((context) -> { assertThat(getLocationHeader(context, "/actuator/health").toString()).contains("/login"); assertThat(getLocationHeader(context, "/foo").toString()).contains("/login"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java index 5ae2c88a1fe..d3fe2413a7d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java @@ -47,12 +47,12 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public abstract class AbstractEndpointRequestIntegrationTests { +abstract class AbstractEndpointRequestIntegrationTests { protected abstract WebApplicationContextRunner getContextRunner(); @Test - public void toEndpointShouldMatch() { + void toEndpointShouldMatch() { getContextRunner().run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/actuator/e1").exchange().expectStatus().isOk(); @@ -60,7 +60,7 @@ public abstract class AbstractEndpointRequestIntegrationTests { } @Test - public void toAllEndpointsShouldMatch() { + void toAllEndpointsShouldMatch() { getContextRunner().withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) .withPropertyValues("spring.security.user.password=password").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); @@ -71,7 +71,7 @@ public abstract class AbstractEndpointRequestIntegrationTests { } @Test - public void toLinksShouldMatch() { + void toLinksShouldMatch() { getContextRunner().run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/actuator").exchange().expectStatus().isOk(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java index 59585f61602..bb31be525d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequestTests.java @@ -49,10 +49,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class EndpointRequestTests { +class EndpointRequestTests { @Test - public void toAnyEndpointShouldMatchEndpointPath() { + void toAnyEndpointShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo"); assertMatcher(matcher, "/actuator").matches("/actuator/foo/zoo/"); @@ -62,7 +62,7 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointShouldMatchEndpointPathWithTrailingSlash() { + void toAnyEndpointShouldMatchEndpointPathWithTrailingSlash() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo/"); assertMatcher(matcher, "/actuator").matches("/actuator/bar/"); @@ -70,7 +70,7 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointWhenBasePathIsEmptyShouldNotMatchLinks() { + void toAnyEndpointWhenBasePathIsEmptyShouldNotMatchLinks() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); @@ -79,13 +79,13 @@ public class EndpointRequestTests { } @Test - public void toAnyEndpointShouldNotMatchOtherPath() { + void toAnyEndpointShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher).doesNotMatch("/actuator/baz"); } @Test - public void toAnyEndpointWhenDispatcherServletPathProviderNotAvailableUsesEmptyPath() { + void toAnyEndpointWhenDispatcherServletPathProviderNotAvailableUsesEmptyPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo"); assertMatcher(matcher, "/actuator").matches("/actuator/bar"); @@ -94,33 +94,33 @@ public class EndpointRequestTests { } @Test - public void toEndpointClassShouldMatchEndpointPath() { + void toEndpointClassShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).matches("/actuator/foo"); } @Test - public void toEndpointClassShouldNotMatchOtherPath() { + void toEndpointClassShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/bar"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test - public void toEndpointIdShouldMatchEndpointPath() { + void toEndpointIdShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).matches("/actuator/foo"); } @Test - public void toEndpointIdShouldNotMatchOtherPath() { + void toEndpointIdShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test - public void toLinksShouldOnlyMatchLinks() { + void toLinksShouldOnlyMatchLinks() { RequestMatcher matcher = EndpointRequest.toLinks(); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); @@ -129,7 +129,7 @@ public class EndpointRequestTests { } @Test - public void toLinksWhenBasePathEmptyShouldNotMatch() { + void toLinksWhenBasePathEmptyShouldNotMatch() { RequestMatcher matcher = EndpointRequest.toLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/actuator/foo"); @@ -138,7 +138,7 @@ public class EndpointRequestTests { } @Test - public void excludeByClassShouldNotMatchExcluded() { + void excludeByClassShouldNotMatchExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, BazServletEndpoint.class); List> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); @@ -152,14 +152,14 @@ public class EndpointRequestTests { } @Test - public void excludeByClassShouldNotMatchLinksIfExcluded() { + void excludeByClassShouldNotMatchLinksIfExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test - public void excludeByIdShouldNotMatchExcluded() { + void excludeByIdShouldNotMatchExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); @@ -167,14 +167,14 @@ public class EndpointRequestTests { } @Test - public void excludeByIdShouldNotMatchLinksIfExcluded() { + void excludeByIdShouldNotMatchLinksIfExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test - public void excludeLinksShouldNotMatchBasePath() { + void excludeLinksShouldNotMatchBasePath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); assertMatcher(matcher).doesNotMatch("/actuator"); assertMatcher(matcher).matches("/actuator/foo"); @@ -182,7 +182,7 @@ public class EndpointRequestTests { } @Test - public void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { + void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); @@ -191,7 +191,7 @@ public class EndpointRequestTests { } @Test - public void endpointRequestMatcherShouldUseCustomRequestMatcherProvider() { + void endpointRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcher mockRequestMatcher = (request) -> false; RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints(""), @@ -201,7 +201,7 @@ public class EndpointRequestTests { } @Test - public void linksRequestMatcherShouldUseCustomRequestMatcherProvider() { + void linksRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toLinks(); RequestMatcher mockRequestMatcher = (request) -> false; RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints("/actuator"), @@ -210,7 +210,7 @@ public class EndpointRequestTests { } @Test - public void noEndpointPathsBeansShouldNeverMatch() { + void noEndpointPathsBeansShouldNeverMatch() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/foo"); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/bar"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java index 1bc716e4cfc..c423e7bca81 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java @@ -56,7 +56,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Madhura Bhave */ -public class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { +class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { @Override protected WebApplicationContextRunner getContextRunner() { @@ -71,7 +71,7 @@ public class JerseyEndpointRequestIntegrationTests extends AbstractEndpointReque } @Test - public void toLinksWhenApplicationPathSetShouldMatch() { + void toLinksWhenApplicationPathSetShouldMatch() { getContextRunner().withPropertyValues("spring.jersey.application-path=/admin").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/admin/actuator/").exchange().expectStatus().isOk(); @@ -80,7 +80,7 @@ public class JerseyEndpointRequestIntegrationTests extends AbstractEndpointReque } @Test - public void toEndpointWhenApplicationPathSetShouldMatch() { + void toEndpointWhenApplicationPathSetShouldMatch() { getContextRunner().withPropertyValues("spring.jersey.application-path=/admin").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/admin/actuator/e1").exchange().expectStatus().isOk(); @@ -88,7 +88,7 @@ public class JerseyEndpointRequestIntegrationTests extends AbstractEndpointReque } @Test - public void toAnyEndpointWhenApplicationPathSetShouldMatch() { + void toAnyEndpointWhenApplicationPathSetShouldMatch() { getContextRunner() .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") .run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java index 0b1b4ec9281..274cb8ff9c2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class ManagementWebSecurityAutoConfigurationTests { +class ManagementWebSecurityAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, @@ -58,7 +58,7 @@ public class ManagementWebSecurityAutoConfigurationTests { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class)); @Test - public void permitAllForHealth() { + void permitAllForHealth() { this.contextRunner.run((context) -> { HttpStatus status = getResponseStatus(context, "/actuator/health"); assertThat(status).isEqualTo(HttpStatus.OK); @@ -66,7 +66,7 @@ public class ManagementWebSecurityAutoConfigurationTests { } @Test - public void permitAllForInfo() { + void permitAllForInfo() { this.contextRunner.run((context) -> { HttpStatus status = getResponseStatus(context, "/actuator/info"); assertThat(status).isEqualTo(HttpStatus.OK); @@ -74,7 +74,7 @@ public class ManagementWebSecurityAutoConfigurationTests { } @Test - public void securesEverythingElse() { + void securesEverythingElse() { this.contextRunner.run((context) -> { HttpStatus status = getResponseStatus(context, "/actuator"); assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED); @@ -84,7 +84,7 @@ public class ManagementWebSecurityAutoConfigurationTests { } @Test - public void usesMatchersBasedOffConfiguredActuatorBasePath() { + void usesMatchersBasedOffConfiguredActuatorBasePath() { this.contextRunner.withPropertyValues("management.endpoints.web.base-path=/").run((context) -> { HttpStatus status = getResponseStatus(context, "/health"); assertThat(status).isEqualTo(HttpStatus.OK); @@ -92,7 +92,7 @@ public class ManagementWebSecurityAutoConfigurationTests { } @Test - public void backOffIfCustomSecurityIsAdded() { + void backOffIfCustomSecurityIsAdded() { this.contextRunner.withUserConfiguration(CustomSecurityConfiguration.class).run((context) -> { HttpStatus status = getResponseStatus(context, "/actuator/health"); assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED); @@ -102,7 +102,7 @@ public class ManagementWebSecurityAutoConfigurationTests { } @Test - public void backOffIfOAuth2ResourceServerAutoConfigurationPresent() { + void backOffIfOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityConfigurerAdapter.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java index f2949ef0386..8d1f6a3a7d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java @@ -54,10 +54,10 @@ import org.springframework.web.cors.CorsConfiguration; * * @author Madhura Bhave */ -public class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { +class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrationTests { @Test - public void toLinksWhenServletPathSetShouldMatch() { + void toLinksWhenServletPathSetShouldMatch() { getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/admin/actuator/").exchange().expectStatus().isOk(); @@ -66,7 +66,7 @@ public class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestI } @Test - public void toEndpointWhenServletPathSetShouldMatch() { + void toEndpointWhenServletPathSetShouldMatch() { getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/admin/actuator/e1").exchange().expectStatus().isOk(); @@ -74,7 +74,7 @@ public class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestI } @Test - public void toAnyEndpointWhenServletPathSetShouldMatch() { + void toAnyEndpointWhenServletPathSetShouldMatch() { getContextRunner() .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") .run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java index fb1f94705fc..fcd5d98dc24 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java @@ -33,25 +33,25 @@ import static org.mockito.Mockito.mock; * * @author Vedran Pavic */ -public class SessionsEndpointAutoConfigurationTests { +class SessionsEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) .withUserConfiguration(SessionConfiguration.class); @Test - public void runShouldHaveEndpointBean() { + void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sessions") .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.sessions.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java index 4ac714b15ba..2f9e1fe2a72 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfigurationTests.java @@ -32,20 +32,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class SolrHealthIndicatorAutoConfigurationTests { +class SolrHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class, SolrHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(SolrHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.solr.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(SolrHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java index b0aa833af8a..1dcac730cbb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfigurationTests.java @@ -33,26 +33,26 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class DiskSpaceHealthIndicatorAutoConfigurationTests { +class DiskSpaceHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations .of(DiskSpaceHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class) .doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void thresholdMustBePositive() { + void thresholdMustBePositive() { this.contextRunner.withPropertyValues("management.health.diskspace.threshold=-10MB") .run((context) -> assertThat(context).hasFailed().getFailure() .hasMessageContaining("Failed to bind properties under 'management.health.diskspace'")); } @Test - public void thresholdCanBeCustomized() { + void thresholdCanBeCustomized() { this.contextRunner.withPropertyValues("management.health.diskspace.threshold=20MB").run((context) -> { assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class); assertThat(context.getBean(DiskSpaceHealthIndicator.class)).hasFieldOrPropertyWithValue("threshold", @@ -61,7 +61,7 @@ public class DiskSpaceHealthIndicatorAutoConfigurationTests { } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class) .hasSingleBean(ApplicationHealthIndicator.class)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java index d4e7b5e0de4..bae035ca257 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.actuate.autoconfigure.web; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotatedElementUtils; @@ -29,17 +29,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ManagementContextConfigurationTests { +class ManagementContextConfigurationTests { @Test - public void proxyBeanMethodsIsEnabledByDefault() { + void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test - public void proxyBeanMethodsCanBeDisabled() { + void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes( NoBeanMethodProxyingManagementContextConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java index fd1d26ce4e9..dec98aa4707 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextFactoryTests.java @@ -34,14 +34,14 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ReactiveManagementContextFactoryTests { +class ReactiveManagementContextFactoryTests { private ReactiveManagementContextFactory factory = new ReactiveManagementContextFactory(); private AnnotationConfigReactiveWebServerApplicationContext parent = new AnnotationConfigReactiveWebServerApplicationContext(); @Test - public void createManagementContextShouldCreateChildContextWithConfigClasses() { + void createManagementContextShouldCreateChildContextWithConfigClasses() { this.parent.register(ParentConfiguration.class); this.parent.refresh(); AnnotationConfigReactiveWebServerApplicationContext childContext = (AnnotationConfigReactiveWebServerApplicationContext) this.factory diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java index c22b8375eae..b8d91f0a790 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java @@ -40,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @ExtendWith(OutputCaptureExtension.class) -public class ManagementContextAutoConfigurationTests { +class ManagementContextAutoConfigurationTests { @Test - public void childManagementContextShouldStartForEmbeddedServer(CapturedOutput capturedOutput) { + void childManagementContextShouldStartForEmbeddedServer(CapturedOutput capturedOutput) { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java index 3b73b81663a..6c53d4a06df 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java @@ -35,24 +35,24 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class ManagementContextConfigurationImportSelectorTests { +class ManagementContextConfigurationImportSelectorTests { @Test - public void selectImportsShouldOrderResult() { + void selectImportsShouldOrderResult() { String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, A.class, D.class, B.class) .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), C.class.getName(), D.class.getName()); } @Test - public void selectImportsFiltersChildOnlyConfigurationWhenUsingSameContext() { + void selectImportsFiltersChildOnlyConfigurationWhenUsingSameContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, A.class).selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), A.class.getName()); } @Test - public void selectImportsFiltersSameOnlyConfigurationWhenUsingChildContext() { + void selectImportsFiltersSameOnlyConfigurationWhenUsingChildContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, A.class).selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), A.class.getName()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerPropertiesTests.java index b2e7338c8d6..bea755292c2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerPropertiesTests.java @@ -26,17 +26,17 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class ManagementServerPropertiesTests { +class ManagementServerPropertiesTests { @Test - public void defaultManagementServerProperties() { + void defaultManagementServerProperties() { ManagementServerProperties properties = new ManagementServerProperties(); assertThat(properties.getPort()).isNull(); assertThat(properties.getServlet().getContextPath()).isEqualTo(""); } @Test - public void definedManagementServerProperties() { + void definedManagementServerProperties() { ManagementServerProperties properties = new ManagementServerProperties(); properties.setPort(123); properties.getServlet().setContextPath("/foo"); @@ -45,14 +45,14 @@ public class ManagementServerPropertiesTests { } @Test - public void trailingSlashOfContextPathIsRemoved() { + void trailingSlashOfContextPathIsRemoved() { ManagementServerProperties properties = new ManagementServerProperties(); properties.getServlet().setContextPath("/foo/"); assertThat(properties.getServlet().getContextPath()).isEqualTo("/foo"); } @Test - public void slashOfContextPathIsDefaultValue() { + void slashOfContextPathIsDefaultValue() { ManagementServerProperties properties = new ManagementServerProperties(); properties.getServlet().setContextPath("/"); assertThat(properties.getServlet().getContextPath()).isEqualTo(""); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java index d60081205ea..c7370404229 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class CompositeHandlerExceptionResolverTests { +class CompositeHandlerExceptionResolverTests { private AnnotationConfigApplicationContext context; @@ -48,7 +48,7 @@ public class CompositeHandlerExceptionResolverTests { private MockHttpServletResponse response = new MockHttpServletResponse(); @Test - public void resolverShouldDelegateToOtherResolversInContext() { + void resolverShouldDelegateToOtherResolversInContext() { load(TestConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); @@ -58,7 +58,7 @@ public class CompositeHandlerExceptionResolverTests { } @Test - public void resolverShouldAddDefaultResolverIfNonePresent() { + void resolverShouldAddDefaultResolverIfNonePresent() { load(BaseConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java index 7ad8dfdd609..bbb509d24f4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java @@ -33,18 +33,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class WebMvcEndpointChildContextConfigurationTests { +class WebMvcEndpointChildContextConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(); @Test - public void contextShouldConfigureRequestContextFilter() { + void contextShouldConfigureRequestContextFilter() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); } @Test - public void contextShouldNotConfigureRequestContextFilterWhenPresent() { + void contextShouldNotConfigureRequestContextFilterWhenPresent() { this.contextRunner.withUserConfiguration(ExistingConfig.class, WebMvcEndpointChildContextConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(RequestContextFilter.class); @@ -53,7 +53,7 @@ public class WebMvcEndpointChildContextConfigurationTests { } @Test - public void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() { + void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() { this.contextRunner.withUserConfiguration(RequestContextListenerConfig.class, WebMvcEndpointChildContextConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(RequestContextListener.class); @@ -62,7 +62,7 @@ public class WebMvcEndpointChildContextConfigurationTests { } @Test - public void contextShouldConfigureDispatcherServletPathWithRootPath() { + void contextShouldConfigureDispatcherServletPathWithRootPath() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java index 661794f84e6..eae78fd422f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceAutoConfigurationTests.java @@ -44,18 +44,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Madhura Bhave */ -public class HttpTraceAutoConfigurationTests { +class HttpTraceAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)); @Test - public void autoConfigurationIsDisabledByDefault() { + void autoConfigurationIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(HttpTraceAutoConfiguration.class)); } @Test - public void autoConfigurationIsEnabledWhenHttpTraceRepositoryBeanPresent() { + void autoConfigurationIsEnabledWhenHttpTraceRepositoryBeanPresent() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpExchangeTracer.class); assertThat(context).hasSingleBean(HttpTraceFilter.class); @@ -65,7 +65,7 @@ public class HttpTraceAutoConfigurationTests { } @Test - public void usesUserProvidedTracer() { + void usesUserProvidedTracer() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withUserConfiguration(CustomTracerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpExchangeTracer.class); @@ -74,7 +74,7 @@ public class HttpTraceAutoConfigurationTests { } @Test - public void usesUserProvidedWebFilterWhenReactiveContext() { + void usesUserProvidedWebFilterWhenReactiveContext() { new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) .withUserConfiguration(HttpTraceRepositoryConfiguration.class) @@ -85,13 +85,13 @@ public class HttpTraceAutoConfigurationTests { } @Test - public void configuresServletFilter() { + void configuresServletFilter() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(HttpTraceFilter.class)); } @Test - public void usesUserProvidedServletFilter() { + void usesUserProvidedServletFilter() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withUserConfiguration(CustomFilterConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpTraceFilter.class); @@ -100,7 +100,7 @@ public class HttpTraceAutoConfigurationTests { } @Test - public void backsOffWhenDisabled() { + void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.trace.http.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpTraceRepository.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java index cc98226e56a..f2120ea6d00 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/trace/HttpTraceEndpointAutoConfigurationTests.java @@ -35,26 +35,26 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class HttpTraceEndpointAutoConfigurationTests { +class HttpTraceEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( AutoConfigurations.of(HttpTraceAutoConfiguration.class, HttpTraceEndpointAutoConfiguration.class)); @Test - public void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { + void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=httptrace") .run((context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); } @Test - public void runWhenNotExposedShouldNotHaveEndpointBean() { + void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test - public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { + void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpTraceRepositoryConfiguration.class) .withPropertyValues("management.endpoints.web.exposure.include=httptrace") .withPropertyValues("management.endpoint.httptrace.enabled:false") @@ -62,7 +62,7 @@ public class HttpTraceEndpointAutoConfigurationTests { } @Test - public void endpointBacksOffWhenRepositoryIsNotAvailable() { + void endpointBacksOffWhenRepositoryIsNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=httptrace") .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/AdhocTestSuite.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/AdhocTestSuite.java deleted file mode 100644 index bd025960a1f..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/AdhocTestSuite.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A test suite for probing weird ordering problems in the tests. - * - * @author Dave Syer - */ -@RunWith(Suite.class) -@SuiteClasses({}) -@Ignore -public class AdhocTestSuite { - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java index eaaee0441ab..969dd8475de 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java @@ -41,7 +41,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class RabbitHealthIndicatorTests { +class RabbitHealthIndicatorTests { @Mock private RabbitTemplate rabbitTemplate; @@ -59,13 +59,13 @@ public class RabbitHealthIndicatorTests { } @Test - public void createWhenRabbitTemplateIsNullShouldThrowException() { + void createWhenRabbitTemplateIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RabbitHealthIndicator(null)) .withMessageContaining("RabbitTemplate must not be null"); } @Test - public void healthWhenConnectionSucceedsShouldReturnUpWithVersion() { + void healthWhenConnectionSucceedsShouldReturnUpWithVersion() { Connection connection = mock(Connection.class); given(this.channel.getConnection()).willReturn(connection); given(connection.getServerProperties()).willReturn(Collections.singletonMap("version", "123")); @@ -75,7 +75,7 @@ public class RabbitHealthIndicatorTests { } @Test - public void healthWhenConnectionFailsShouldReturnDown() { + void healthWhenConnectionFailsShouldReturnDown() { given(this.channel.getConnection()).willThrow(new RuntimeException()); Health health = new RabbitHealthIndicator(this.rabbitTemplate).health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index c906e78bcc7..93333bdc3ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Dave Syer * @author Vedran Pavic */ -public class AuditEventTests { +class AuditEventTests { @Test - public void nowEvent() { + void nowEvent() { AuditEvent event = new AuditEvent("phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(event.getData().get("a")).isEqualTo("b"); assertThat(event.getType()).isEqualTo("UNKNOWN"); @@ -44,34 +44,34 @@ public class AuditEventTests { } @Test - public void convertStringsToData() { + void convertStringsToData() { AuditEvent event = new AuditEvent("phil", "UNKNOWN", "a=b", "c=d"); assertThat(event.getData().get("a")).isEqualTo("b"); assertThat(event.getData().get("c")).isEqualTo("d"); } @Test - public void nullPrincipalIsMappedToEmptyString() { + void nullPrincipalIsMappedToEmptyString() { AuditEvent auditEvent = new AuditEvent(null, "UNKNOWN", Collections.singletonMap("a", (Object) "b")); assertThat(auditEvent.getPrincipal()).isEmpty(); } @Test - public void nullTimestamp() { + void nullTimestamp() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b"))) .withMessageContaining("Timestamp must not be null"); } @Test - public void nullType() { + void nullType() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", (Object) "b"))) .withMessageContaining("Type must not be null"); } @Test - public void jsonFormat() throws Exception { + void jsonFormat() throws Exception { AuditEvent event = new AuditEvent("johannes", "UNKNOWN", Collections.singletonMap("type", (Object) "BadCredentials")); String json = Jackson2ObjectMapperBuilder.json().build().writeValueAsString(event); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java index 742398aeb8c..508a42fcdfe 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointTests.java @@ -31,7 +31,7 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class AuditEventsEndpointTests { +class AuditEventsEndpointTests { private final AuditEventRepository repository = mock(AuditEventRepository.class); @@ -40,14 +40,14 @@ public class AuditEventsEndpointTests { private final AuditEvent event = new AuditEvent("principal", "type", Collections.singletonMap("a", "alpha")); @Test - public void eventsWithType() { + void eventsWithType() { given(this.repository.find(null, null, "type")).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events(null, null, "type").getEvents(); assertThat(result).isEqualTo(Collections.singletonList(this.event)); } @Test - public void eventsCreatedAfter() { + void eventsCreatedAfter() { OffsetDateTime now = OffsetDateTime.now(); given(this.repository.find(null, now.toInstant(), null)).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events(null, now, null).getEvents(); @@ -55,7 +55,7 @@ public class AuditEventsEndpointTests { } @Test - public void eventsWithPrincipal() { + void eventsWithPrincipal() { given(this.repository.find("Joan", null, null)).willReturn(Collections.singletonList(this.event)); List result = this.endpoint.events("Joan", null, null).getEvents(); assertThat(result).isEqualTo(Collections.singletonList(this.event)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java index 845d9a35238..204a5f47077 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java @@ -20,10 +20,8 @@ import java.time.Instant; import java.util.Collections; import net.minidev.json.JSONArray; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.web.reactive.server.WebTestClient; @@ -35,35 +33,32 @@ import org.springframework.test.web.reactive.server.WebTestClient; * @author Vedran Pavic * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class AuditEventsEndpointWebIntegrationTests { +class AuditEventsEndpointWebIntegrationTests { - private static WebTestClient client; - - @Test - public void allEvents() { + @WebEndpointTest + void allEvents(WebTestClient client) { client.get().uri((builder) -> builder.path("/actuator/auditevents").build()).exchange().expectStatus().isOk() .expectBody().jsonPath("events.[*].principal") .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); } - @Test - public void eventsAfter() { + @WebEndpointTest + void eventsAfter(WebTestClient client) { client.get() .uri((builder) -> builder.path("/actuator/auditevents") .queryParam("after", "2016-11-01T13:00:00%2B00:00").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("events").isEmpty(); } - @Test - public void eventsWithPrincipal() { + @WebEndpointTest + void eventsWithPrincipal(WebTestClient client) { client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") .isEqualTo(new JSONArray().appendElement("user")); } - @Test - public void eventsWithType() { + @WebEndpointTest + void eventsWithType(WebTestClient client) { client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") .isEqualTo(new JSONArray().appendElement("admin")).jsonPath("events.[*].type") diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index 8632b8faa1d..1c332729d41 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -34,10 +34,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Vedran Pavic */ -public class InMemoryAuditEventRepositoryTests { +class InMemoryAuditEventRepositoryTests { @Test - public void lessThanCapacity() { + void lessThanCapacity() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); repository.add(new AuditEvent("dave", "a")); repository.add(new AuditEvent("dave", "b")); @@ -48,7 +48,7 @@ public class InMemoryAuditEventRepositoryTests { } @Test - public void capacity() { + void capacity() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(2); repository.add(new AuditEvent("dave", "a")); repository.add(new AuditEvent("dave", "b")); @@ -60,14 +60,14 @@ public class InMemoryAuditEventRepositoryTests { } @Test - public void addNullAuditEvent() { + void addNullAuditEvent() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); assertThatIllegalArgumentException().isThrownBy(() -> repository.add(null)) .withMessageContaining("AuditEvent must not be null"); } @Test - public void findByPrincipal() { + void findByPrincipal() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); repository.add(new AuditEvent("dave", "a")); repository.add(new AuditEvent("phil", "b")); @@ -80,7 +80,7 @@ public class InMemoryAuditEventRepositoryTests { } @Test - public void findByPrincipalAndType() { + void findByPrincipalAndType() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); repository.add(new AuditEvent("dave", "a")); repository.add(new AuditEvent("phil", "b")); @@ -93,7 +93,7 @@ public class InMemoryAuditEventRepositoryTests { } @Test - public void findByDate() { + void findByDate() { Instant instant = Instant.now(); Map data = new HashMap<>(); InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java index c7708ac1504..f241a4f0315 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/listener/AuditListenerTests.java @@ -31,10 +31,10 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class AuditListenerTests { +class AuditListenerTests { @Test - public void testStoredEvents() { + void testStoredEvents() { AuditEventRepository repository = mock(AuditEventRepository.class); AuditEvent event = new AuditEvent("principal", "type", Collections.emptyMap()); AuditListener listener = new AuditListener(repository); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java index e58706b0ff2..9707b28a35c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java @@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class BeansEndpointTests { +class BeansEndpointTests { @Test - public void beansAreFound() { + void beansAreFound() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { @@ -59,7 +59,7 @@ public class BeansEndpointTests { } @Test - public void infrastructureBeansAreOmitted() { + void infrastructureBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { @@ -78,7 +78,7 @@ public class BeansEndpointTests { } @Test - public void lazyBeansAreOmitted() { + void lazyBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); contextRunner.run((context) -> { @@ -90,7 +90,7 @@ public class BeansEndpointTests { } @Test - public void beansInParentContextAreFound() { + void beansInParentContextAreFound() { ApplicationContextRunner parentRunner = new ApplicationContextRunner() .withUserConfiguration(BeanConfiguration.class); parentRunner.run((parent) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java index beda28b7e4a..e05af5ad1e7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java @@ -43,10 +43,10 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class CachesEndpointTests { +class CachesEndpointTests { @Test - public void allCachesWithSingleCacheManager() { + void allCachesWithSingleCacheManager() { CachesEndpoint endpoint = new CachesEndpoint( Collections.singletonMap("test", new ConcurrentMapCacheManager("a", "b"))); Map allDescriptors = endpoint.caches().getCacheManagers(); @@ -58,7 +58,7 @@ public class CachesEndpointTests { } @Test - public void allCachesWithSeveralCacheManagers() { + void allCachesWithSeveralCacheManagers() { Map cacheManagers = new LinkedHashMap<>(); cacheManagers.put("test", new ConcurrentMapCacheManager("a", "b")); cacheManagers.put("another", new ConcurrentMapCacheManager("a", "c")); @@ -70,7 +70,7 @@ public class CachesEndpointTests { } @Test - public void namedCacheWithSingleCacheManager() { + void namedCacheWithSingleCacheManager() { CachesEndpoint endpoint = new CachesEndpoint( Collections.singletonMap("test", new ConcurrentMapCacheManager("b", "a"))); CacheEntry entry = endpoint.cache("a", null); @@ -81,7 +81,7 @@ public class CachesEndpointTests { } @Test - public void namedCacheWithSeveralCacheManagers() { + void namedCacheWithSeveralCacheManagers() { Map cacheManagers = new LinkedHashMap<>(); cacheManagers.put("test", new ConcurrentMapCacheManager("b", "dupe-cache")); cacheManagers.put("another", new ConcurrentMapCacheManager("c", "dupe-cache")); @@ -91,7 +91,7 @@ public class CachesEndpointTests { } @Test - public void namedCacheWithUnknownCache() { + void namedCacheWithUnknownCache() { CachesEndpoint endpoint = new CachesEndpoint( Collections.singletonMap("test", new ConcurrentMapCacheManager("b", "a"))); CacheEntry entry = endpoint.cache("unknown", null); @@ -99,7 +99,7 @@ public class CachesEndpointTests { } @Test - public void namedCacheWithWrongCacheManager() { + void namedCacheWithWrongCacheManager() { Map cacheManagers = new LinkedHashMap<>(); cacheManagers.put("test", new ConcurrentMapCacheManager("b", "a")); cacheManagers.put("another", new ConcurrentMapCacheManager("c", "a")); @@ -109,7 +109,7 @@ public class CachesEndpointTests { } @Test - public void namedCacheWithSeveralCacheManagersWithCacheManagerFilter() { + void namedCacheWithSeveralCacheManagersWithCacheManagerFilter() { Map cacheManagers = new LinkedHashMap<>(); cacheManagers.put("test", new ConcurrentMapCacheManager("b", "a")); cacheManagers.put("another", new ConcurrentMapCacheManager("c", "a")); @@ -121,7 +121,7 @@ public class CachesEndpointTests { } @Test - public void clearAllCaches() { + void clearAllCaches() { Cache a = mockCache("a"); Cache b = mockCache("b"); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); @@ -131,7 +131,7 @@ public class CachesEndpointTests { } @Test - public void clearCache() { + void clearCache() { Cache a = mockCache("a"); Cache b = mockCache("b"); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); @@ -141,7 +141,7 @@ public class CachesEndpointTests { } @Test - public void clearCacheWithSeveralCacheManagers() { + void clearCacheWithSeveralCacheManagers() { Map cacheManagers = new LinkedHashMap<>(); cacheManagers.put("test", cacheManager(mockCache("dupe-cache"), mockCache("b"))); cacheManagers.put("another", cacheManager(mockCache("dupe-cache"))); @@ -152,7 +152,7 @@ public class CachesEndpointTests { } @Test - public void clearCacheWithSeveralCacheManagersWithCacheManagerFilter() { + void clearCacheWithSeveralCacheManagersWithCacheManagerFilter() { Map cacheManagers = new LinkedHashMap<>(); Cache a = mockCache("a"); Cache b = mockCache("b"); @@ -167,7 +167,7 @@ public class CachesEndpointTests { } @Test - public void clearCacheWithUnknownCache() { + void clearCacheWithUnknownCache() { Cache a = mockCache("a"); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); assertThat(endpoint.clearCache("unknown", null)).isFalse(); @@ -175,7 +175,7 @@ public class CachesEndpointTests { } @Test - public void clearCacheWithUnknownCacheManager() { + void clearCacheWithUnknownCacheManager() { Cache a = mockCache("a"); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); assertThat(endpoint.clearCache("a", "unknown")).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java index c3671ed8fa7..0ba73962f63 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java @@ -19,14 +19,11 @@ package org.springframework.boot.actuate.cache; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.web.reactive.server.WebTestClient; @@ -39,15 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(WebEndpointRunners.class) -public class CachesEndpointWebIntegrationTests { +class CachesEndpointWebIntegrationTests { - private static WebTestClient client; - - private static ConfigurableApplicationContext context; - - @Test - public void allCaches() { + @WebEndpointTest + void allCaches(WebTestClient client) { client.get().uri("/actuator/caches").exchange().expectStatus().isOk().expectBody() .jsonPath("cacheManagers.one.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) .jsonPath("cacheManagers.one.caches.b.target").isEqualTo(ConcurrentHashMap.class.getName()) @@ -55,38 +47,38 @@ public class CachesEndpointWebIntegrationTests { .jsonPath("cacheManagers.two.caches.c.target").isEqualTo(ConcurrentHashMap.class.getName()); } - @Test - public void namedCache() { + @WebEndpointTest + void namedCache(WebTestClient client) { client.get().uri("/actuator/caches/b").exchange().expectStatus().isOk().expectBody().jsonPath("name") .isEqualTo("b").jsonPath("cacheManager").isEqualTo("one").jsonPath("target") .isEqualTo(ConcurrentHashMap.class.getName()); } - @Test - public void namedCacheWithUnknownName() { + @WebEndpointTest + void namedCacheWithUnknownName(WebTestClient client) { client.get().uri("/actuator/caches/does-not-exist").exchange().expectStatus().isNotFound(); } - @Test - public void namedCacheWithNonUniqueName() { + @WebEndpointTest + void namedCacheWithNonUniqueName(WebTestClient client) { client.get().uri("/actuator/caches/a").exchange().expectStatus().isBadRequest(); } - @Test - public void clearNamedCache() { + @WebEndpointTest + void clearNamedCache(WebTestClient client, ApplicationContext context) { Cache b = context.getBean("one", CacheManager.class).getCache("b"); b.put("test", "value"); client.delete().uri("/actuator/caches/b").exchange().expectStatus().isNoContent(); assertThat(b.get("test")).isNull(); } - @Test - public void cleanNamedCacheWithUnknownName() { + @WebEndpointTest + void cleanNamedCacheWithUnknownName(WebTestClient client) { client.delete().uri("/actuator/caches/does-not-exist").exchange().expectStatus().isNotFound(); } - @Test - public void clearNamedCacheWithNonUniqueName() { + @WebEndpointTest + void clearNamedCacheWithNonUniqueName(WebTestClient client) { client.get().uri("/actuator/caches/a").exchange().expectStatus().isBadRequest(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java index f3077a52932..61889d385a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicatorTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.actuate.cassandra; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.querybuilder.Select; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; @@ -37,15 +37,15 @@ import static org.mockito.Mockito.mock; * * @author Oleksii Bondar */ -public class CassandraHealthIndicatorTests { +class CassandraHealthIndicatorTests { @Test - public void createWhenCassandraOperationsIsNullShouldThrowException() { + void createWhenCassandraOperationsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new CassandraHealthIndicator(null)); } @Test - public void verifyHealthStatusWhenExhausted() { + void verifyHealthStatusWhenExhausted() { CassandraOperations cassandraOperations = mock(CassandraOperations.class); CqlOperations cqlOperations = mock(CqlOperations.class); ResultSet resultSet = mock(ResultSet.class); @@ -58,7 +58,7 @@ public class CassandraHealthIndicatorTests { } @Test - public void verifyHealthStatusWithVersion() { + void verifyHealthStatusWithVersion() { CassandraOperations cassandraOperations = mock(CassandraOperations.class); CqlOperations cqlOperations = mock(CqlOperations.class); ResultSet resultSet = mock(ResultSet.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java index 7daba57d9ba..a480f644310 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraReactiveHealthIndicatorTests.java @@ -37,10 +37,10 @@ import static org.mockito.Mockito.mock; * * @author Artsiom Yudovin */ -public class CassandraReactiveHealthIndicatorTests { +class CassandraReactiveHealthIndicatorTests { @Test - public void testCassandraIsUp() { + void testCassandraIsUp() { ReactiveCqlOperations reactiveCqlOperations = mock(ReactiveCqlOperations.class); given(reactiveCqlOperations.queryForObject(any(Select.class), eq(String.class))).willReturn(Mono.just("6.0.0")); ReactiveCassandraOperations reactiveCassandraOperations = mock(ReactiveCassandraOperations.class); @@ -57,7 +57,7 @@ public class CassandraReactiveHealthIndicatorTests { } @Test - public void testCassandraIsDown() { + void testCassandraIsDown() { ReactiveCassandraOperations reactiveCassandraOperations = mock(ReactiveCassandraOperations.class); given(reactiveCassandraOperations.getReactiveCqlOperations()) .willThrow(new CassandraInternalException("Connection failed")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java index 5c216d04305..d8b8ba1bc0e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java @@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class ShutdownEndpointTests { +class ShutdownEndpointTests { @Test - public void shutdown() { + void shutdown() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(EndpointConfig.class); contextRunner.run((context) -> { @@ -67,7 +67,7 @@ public class ShutdownEndpointTests { } @Test - public void shutdownChild() throws Exception { + void shutdownChild() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EmptyConfig.class) .child(EndpointConfig.class).web(WebApplicationType.NONE).run(); CountDownLatch latch = context.getBean(EndpointConfig.class).latch; @@ -77,7 +77,7 @@ public class ShutdownEndpointTests { } @Test - public void shutdownParent() throws Exception { + void shutdownParent() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EndpointConfig.class) .child(EmptyConfig.class).web(WebApplicationType.NONE).run(); CountDownLatch parentLatch = context.getBean(EndpointConfig.class).latch; diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index c9582013999..571457de8ec 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { +class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test - public void testNaming() { + void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) .withPropertyValues("other.name:foo", "first.name:bar"); contextRunner.run((context) -> { @@ -56,7 +56,7 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { } @Test - public void prefixFromBeanMethodConfigurationPropertiesCanOverridePrefixOnClass() { + void prefixFromBeanMethodConfigurationPropertiesCanOverridePrefixOnClass() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(OverriddenPrefix.class).withPropertyValues("other.name:foo"); contextRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java index 7ac7eb75604..3c3b35b7c36 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java @@ -34,10 +34,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointParentTests { +class ConfigurationPropertiesReportEndpointParentTests { @Test - public void configurationPropertiesClass() { + void configurationPropertiesClass() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class).withParent(parent) .run((child) -> { @@ -54,7 +54,7 @@ public class ConfigurationPropertiesReportEndpointParentTests { } @Test - public void configurationPropertiesBeanMethod() { + void configurationPropertiesBeanMethod() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { new ApplicationContextRunner().withUserConfiguration(BeanMethodConfigurationProperties.class) .withParent(parent).run((child) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java index 23ce16b938e..9bf54902c9f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java @@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointProxyTests { +class ConfigurationPropertiesReportEndpointProxyTests { @Test - public void testWithProxyClass() { + void testWithProxyClass() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class, SqlExecutor.class); contextRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java index 1ede7313982..b6d365f9c2e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.entry; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class ConfigurationPropertiesReportEndpointSerializationTests { +class ConfigurationPropertiesReportEndpointSerializationTests { @Test - public void testNaming() { + void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { @@ -67,7 +67,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") - public void testNestedNaming() { + void testNestedNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) .withPropertyValues("foo.bar.name:foo"); contextRunner.run((context) -> { @@ -86,7 +86,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") - public void testSelfReferentialProperty() { + void testSelfReferentialProperty() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(SelfReferentialConfig.class).withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { @@ -107,7 +107,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { } @Test - public void testCycle() { + void testCycle() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(CycleConfig.class); contextRunner.run((context) -> { @@ -126,7 +126,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") - public void testMap() { + void testMap() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class) .withPropertyValues("foo.map.name:foo"); contextRunner.run((context) -> { @@ -145,7 +145,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { } @Test - public void testEmptyMapIsNotAdded() { + void testEmptyMapIsNotAdded() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context @@ -164,7 +164,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") - public void testList() { + void testList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(ListConfig.class) .withPropertyValues("foo.list[0]:foo"); contextRunner.run((context) -> { @@ -183,7 +183,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { } @Test - public void testInetAddress() { + void testInetAddress() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(AddressedConfig.class).withPropertyValues("foo.address:192.168.1.10"); contextRunner.run((context) -> { @@ -203,7 +203,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { @Test @SuppressWarnings("unchecked") - public void testInitializedMapAndList() { + void testInitializedMapAndList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(InitializedMapAndListPropertiesConfig.class) .withPropertyValues("foo.map.entryOne:true", "foo.list[0]:abc"); @@ -224,7 +224,7 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { } @Test - public void hikariDataSourceConfigurationPropertiesBeanCanBeSerialized() { + void hikariDataSourceConfigurationPropertiesBeanCanBeSerialized() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(HikariDataSourceConfig.class); contextRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java index 509e619c23c..31c2ffeb43e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java @@ -47,10 +47,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class ConfigurationPropertiesReportEndpointTests { +class ConfigurationPropertiesReportEndpointTests { @Test - public void configurationPropertiesAreReturned() { + void configurationPropertiesAreReturned() { load((context, properties) -> { assertThat(properties.getBeans().size()).isGreaterThan(0); ConfigurationPropertiesBeanDescriptor nestedProperties = properties.getBeans().get("testProperties"); @@ -61,7 +61,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void entriesWithNullValuesAreNotIncluded() { + void entriesWithNullValuesAreNotIncluded() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).doesNotContainKey("nullValue"); @@ -69,7 +69,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void defaultKeySanitization() { + void defaultKeySanitization() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); @@ -79,7 +79,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void customKeySanitization() { + void customKeySanitization() { load("property", (context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); @@ -89,7 +89,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void customPatternKeySanitization() { + void customPatternKeySanitization() { load(".*pass.*", (context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties).isNotNull(); @@ -100,7 +100,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test @SuppressWarnings("unchecked") - public void keySanitizationWithCustomPatternUsingCompositeKeys() { + void keySanitizationWithCustomPatternUsingCompositeKeys() { // gh-4415 load(Arrays.asList(".*\\.secrets\\..*", ".*\\.hidden\\..*"), (context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); @@ -114,7 +114,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void nonCamelCaseProperty() { + void nonCamelCaseProperty() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("myURL")).isEqualTo("https://example.com"); @@ -122,7 +122,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void simpleBoolean() { + void simpleBoolean() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("simpleBoolean")).isEqualTo(true); @@ -130,7 +130,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void mixedBoolean() { + void mixedBoolean() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("mixedBoolean")).isEqualTo(true); @@ -138,7 +138,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void mixedCase() { + void mixedCase() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("mIxedCase")).isEqualTo("mixed"); @@ -146,7 +146,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void duration() { + void duration() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("duration")).isEqualTo(Duration.ofSeconds(10).toString()); @@ -154,7 +154,7 @@ public class ConfigurationPropertiesReportEndpointTests { } @Test - public void singleLetterProperty() { + void singleLetterProperty() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("z")).isEqualTo("zzz"); @@ -163,7 +163,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test @SuppressWarnings("unchecked") - public void listsAreSanitized() { + void listsAreSanitized() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("listItems")).isInstanceOf(List.class); @@ -176,7 +176,7 @@ public class ConfigurationPropertiesReportEndpointTests { @Test @SuppressWarnings("unchecked") - public void listsOfListsAreSanitized() { + void listsOfListsAreSanitized() { load((context, properties) -> { Map nestedProperties = properties.getBeans().get("testProperties").getProperties(); assertThat(nestedProperties.get("listOfListItems")).isInstanceOf(List.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java index 3e415686b07..c6f00adcbdf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicatorTests.java @@ -42,11 +42,11 @@ import static org.mockito.Mockito.verify; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CouchbaseHealthIndicatorTests { +class CouchbaseHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void couchbaseClusterIsUp() { + void couchbaseClusterIsUp() { Cluster cluster = mock(Cluster.class); CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(cluster); List endpoints = Arrays.asList(new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, @@ -63,7 +63,7 @@ public class CouchbaseHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void couchbaseClusterIsDown() { + void couchbaseClusterIsDown() { Cluster cluster = mock(Cluster.class); CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(cluster); List endpoints = Arrays.asList( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java index a9240f131c3..fe3923120bd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/couchbase/CouchbaseReactiveHealthIndicatorTests.java @@ -39,11 +39,11 @@ import static org.mockito.Mockito.verify; /** * Tests for {@link CouchbaseReactiveHealthIndicator}. */ -public class CouchbaseReactiveHealthIndicatorTests { +class CouchbaseReactiveHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void couchbaseClusterIsUp() { + void couchbaseClusterIsUp() { Cluster cluster = mock(Cluster.class); CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator(cluster); List endpoints = Arrays.asList(new EndpointHealth(ServiceType.BINARY, LifecycleState.CONNECTED, @@ -60,7 +60,7 @@ public class CouchbaseReactiveHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void couchbaseClusterIsDown() { + void couchbaseClusterIsDown() { Cluster cluster = mock(Cluster.class); CouchbaseReactiveHealthIndicator healthIndicator = new CouchbaseReactiveHealthIndicator(cluster); List endpoints = Arrays.asList( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java index cf2bec594cf..86227c8562d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java @@ -50,7 +50,7 @@ import static org.mockito.BDDMockito.given; * @author Andy Wilkinson */ @Deprecated -public class ElasticsearchHealthIndicatorTests { +class ElasticsearchHealthIndicatorTests { @Mock private Client client; @@ -72,7 +72,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void defaultConfigurationQueriesAllIndicesWith100msTimeout() { + void defaultConfigurationQueriesAllIndicesWith100msTimeout() { TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(ClusterHealthRequest.class); @@ -84,7 +84,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void certainIndices() { + void certainIndices() { this.indicator = new ElasticsearchHealthIndicator(this.client, 100L, "test-index-1", "test-index-2"); PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse()); @@ -96,7 +96,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void customTimeout() { + void customTimeout() { this.indicator = new ElasticsearchHealthIndicator(this.client, 1000L); TestActionFuture responseFuture = new TestActionFuture(); responseFuture.onResponse(new StubClusterHealthResponse()); @@ -107,7 +107,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void healthDetails() { + void healthDetails() { PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse()); given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); @@ -125,7 +125,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void redResponseMapsToDown() { + void redResponseMapsToDown() { PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.RED)); given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); @@ -133,7 +133,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void yellowResponseMapsToUp() { + void yellowResponseMapsToUp() { PlainActionFuture responseFuture = new PlainActionFuture<>(); responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); @@ -141,7 +141,7 @@ public class ElasticsearchHealthIndicatorTests { } @Test - public void responseTimeout() { + void responseTimeout() { PlainActionFuture responseFuture = new PlainActionFuture<>(); given(this.cluster.health(any(ClusterHealthRequest.class))).willReturn(responseFuture); Health health = this.indicator.health(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java index 93109d1bdcf..f322b26bb00 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicatorTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; * @author Julian Devia Serna * @author Brian Clozel */ -public class ElasticsearchJestHealthIndicatorTests { +class ElasticsearchJestHealthIndicatorTests { private final JestClient jestClient = mock(JestClient.class); @@ -53,7 +53,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test - public void elasticsearchIsUp() throws IOException { + void elasticsearchIsUp() throws IOException { given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "green")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -62,7 +62,7 @@ public class ElasticsearchJestHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void elasticsearchWithYellowStatusIsUp() throws IOException { + void elasticsearchWithYellowStatusIsUp() throws IOException { given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "yellow")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -71,7 +71,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test - public void elasticsearchIsDown() throws IOException { + void elasticsearchIsDown() throws IOException { given(this.jestClient.execute(any(Action.class))) .willThrow(new CouldNotConnectException("http://localhost:9200", new IOException())); Health health = this.healthIndicator.health(); @@ -80,7 +80,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test - public void elasticsearchIsDownWhenQueryDidNotSucceed() throws IOException { + void elasticsearchIsDownWhenQueryDidNotSucceed() throws IOException { given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, false, "")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -88,7 +88,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test - public void elasticsearchIsDownByResponseCode() throws IOException { + void elasticsearchIsDownByResponseCode() throws IOException { given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(500, false, "")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -97,7 +97,7 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test - public void elasticsearchIsOutOfServiceByStatus() throws IOException { + void elasticsearchIsOutOfServiceByStatus() throws IOException { given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(200, true, "red")); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java index a4a3b6bac93..b4c0096527a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicatorTest.java @@ -42,7 +42,7 @@ import static org.mockito.Mockito.mock; * @author Artsiom Yudovin * @author Filip Hrisafov */ -public class ElasticsearchRestHealthIndicatorTest { +class ElasticsearchRestHealthIndicatorTest { private final RestClient restClient = mock(RestClient.class); @@ -50,7 +50,7 @@ public class ElasticsearchRestHealthIndicatorTest { this.restClient); @Test - public void elasticsearchIsUp() throws IOException { + void elasticsearchIsUp() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "green").getBytes())); Response response = mock(Response.class); @@ -65,7 +65,7 @@ public class ElasticsearchRestHealthIndicatorTest { } @Test - public void elasticsearchWithYellowStatusIsUp() throws IOException { + void elasticsearchWithYellowStatusIsUp() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "yellow").getBytes())); Response response = mock(Response.class); @@ -80,7 +80,7 @@ public class ElasticsearchRestHealthIndicatorTest { } @Test - public void elasticsearchIsDown() throws IOException { + void elasticsearchIsDown() throws IOException { given(this.restClient.performRequest(any(Request.class))).willThrow(new IOException("Couldn't connect")); Health health = this.elasticsearchRestHealthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -88,7 +88,7 @@ public class ElasticsearchRestHealthIndicatorTest { } @Test - public void elasticsearchIsDownByResponseCode() throws IOException { + void elasticsearchIsDownByResponseCode() throws IOException { Response response = mock(Response.class); StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(500); @@ -102,7 +102,7 @@ public class ElasticsearchRestHealthIndicatorTest { } @Test - public void elasticsearchIsOutOfServiceByStatus() throws IOException { + void elasticsearchIsOutOfServiceByStatus() throws IOException { BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContent(new ByteArrayInputStream(createJsonResult(200, "red").getBytes())); Response response = mock(Response.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java index 3ce7a43af3e..282949e955f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java @@ -31,45 +31,45 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb */ @ExtendWith(OutputCaptureExtension.class) -public class EndpointIdTests { +class EndpointIdTests { @Test - public void ofWhenNullThrowsException() { + void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of(null)) .withMessage("Value must not be empty"); } @Test - public void ofWhenEmptyThrowsException() { + void ofWhenEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("")).withMessage("Value must not be empty"); } @Test - public void ofWhenContainsSlashThrowsException() { + void ofWhenContainsSlashThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo/bar")) .withMessage("Value must only contain valid chars"); } @Test - public void ofWhenHasBadCharThrowsException() { + void ofWhenHasBadCharThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo!bar")) .withMessage("Value must only contain valid chars"); } @Test - public void ofWhenStartsWithNumberThrowsException() { + void ofWhenStartsWithNumberThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("1foo")) .withMessage("Value must not start with a number"); } @Test - public void ofWhenStartsWithUppercaseLetterThrowsException() { + void ofWhenStartsWithUppercaseLetterThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("Foo")) .withMessage("Value must not start with an uppercase letter"); } @Test - public void ofWhenContainsDotIsValid() { + void ofWhenContainsDotIsValid() { // Ideally we wouldn't support this but there are existing endpoints using the // pattern. See gh-14773 EndpointId endpointId = EndpointId.of("foo.bar"); @@ -77,7 +77,7 @@ public class EndpointIdTests { } @Test - public void ofWhenContainsDashIsValid() { + void ofWhenContainsDashIsValid() { // Ideally we wouldn't support this but there are existing endpoints using the // pattern. See gh-14773 EndpointId endpointId = EndpointId.of("foo-bar"); @@ -85,7 +85,7 @@ public class EndpointIdTests { } @Test - public void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput capturedOutput) { + void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput capturedOutput) { EndpointId.resetLoggedWarnings(); EndpointId.of("foo-bar"); assertThat(capturedOutput.toString()) @@ -93,7 +93,7 @@ public class EndpointIdTests { } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { EndpointId one = EndpointId.of("foobar1"); EndpointId two = EndpointId.of("fooBar1"); EndpointId three = EndpointId.of("foo-bar1"); @@ -106,17 +106,17 @@ public class EndpointIdTests { } @Test - public void toLowerCaseStringReturnsLowercase() { + void toLowerCaseStringReturnsLowercase() { assertThat(EndpointId.of("fooBar").toLowerCaseString()).isEqualTo("foobar"); } @Test - public void toStringReturnsString() { + void toStringReturnsString() { assertThat(EndpointId.of("fooBar").toString()).isEqualTo("fooBar"); } @Test - public void fromPropertyValueStripsDashes() { + void fromPropertyValueStripsDashes() { EndpointId fromPropertyValue = EndpointId.fromPropertyValue("foo-bar"); assertThat(fromPropertyValue).isEqualTo(EndpointId.of("fooBar")); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java index bd297eee287..1677cde539d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class SanitizerTests { +class SanitizerTests { @Test - public void defaults() { + void defaults() { Sanitizer sanitizer = new Sanitizer(); assertThat(sanitizer.sanitize("password", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("my-password", "secret")).isEqualTo("******"); @@ -43,7 +43,7 @@ public class SanitizerTests { } @Test - public void regex() { + void regex() { Sanitizer sanitizer = new Sanitizer(".*lock.*"); assertThat(sanitizer.sanitize("verylOCkish", "secret")).isEqualTo("******"); assertThat(sanitizer.sanitize("veryokish", "secret")).isEqualTo("secret"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java index 43b8be1932b..44baee6eeed 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class DiscoveredOperationMethodTests { +class DiscoveredOperationMethodTests { @Test - public void createWhenAnnotationAttributesIsNullShouldThrowException() { + void createWhenAnnotationAttributesIsNullShouldThrowException() { Method method = ReflectionUtils.findMethod(getClass(), "example"); assertThatIllegalArgumentException() .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) @@ -43,7 +43,7 @@ public class DiscoveredOperationMethodTests { } @Test - public void getProducesMediaTypesShouldReturnMediaTypes() { + void getProducesMediaTypesShouldReturnMediaTypes() { Method method = ReflectionUtils.findMethod(getClass(), "example"); AnnotationAttributes annotationAttributes = new AnnotationAttributes(); String[] produces = new String[] { "application/json" }; diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java index bc7d7b21e38..a6d18b82194 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactoryTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class DiscoveredOperationsFactoryTests { +class DiscoveredOperationsFactoryTests { private TestDiscoveredOperationsFactory factory; @@ -59,7 +59,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsWhenHasReadMethodShouldCreateOperation() { + void createOperationsWhenHasReadMethodShouldCreateOperation() { Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleRead()); assertThat(operations).hasSize(1); TestOperation operation = getFirst(operations); @@ -67,7 +67,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsWhenHasWriteMethodShouldCreateOperation() { + void createOperationsWhenHasWriteMethodShouldCreateOperation() { Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleWrite()); assertThat(operations).hasSize(1); TestOperation operation = getFirst(operations); @@ -75,7 +75,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsWhenHasDeleteMethodShouldCreateOperation() { + void createOperationsWhenHasDeleteMethodShouldCreateOperation() { Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleDelete()); assertThat(operations).hasSize(1); @@ -84,7 +84,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsWhenMultipleShouldReturnMultiple() { + void createOperationsWhenMultipleShouldReturnMultiple() { Collection operations = this.factory.createOperations(EndpointId.of("test"), new ExampleMultiple()); assertThat(operations).hasSize(2); @@ -93,7 +93,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsShouldProvideOperationMethod() { + void createOperationsShouldProvideOperationMethod() { TestOperation operation = getFirst( this.factory.createOperations(EndpointId.of("test"), new ExampleWithParams())); OperationMethod operationMethod = operation.getOperationMethod(); @@ -102,7 +102,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationsShouldProviderInvoker() { + void createOperationsShouldProviderInvoker() { TestOperation operation = getFirst( this.factory.createOperations(EndpointId.of("test"), new ExampleWithParams())); Map params = Collections.singletonMap("name", 123); @@ -111,7 +111,7 @@ public class DiscoveredOperationsFactoryTests { } @Test - public void createOperationShouldApplyAdvisors() { + void createOperationShouldApplyAdvisors() { TestOperationInvokerAdvisor advisor = new TestOperationInvokerAdvisor(); this.invokerAdvisors.add(advisor); TestOperation operation = getFirst(this.factory.createOperations(EndpointId.of("test"), new ExampleRead())); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java index 5f28eca0e1f..1f08a914681 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java @@ -37,23 +37,23 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class DiscovererEndpointFilterTests { +class DiscovererEndpointFilterTests { @Test - public void createWhenDiscovererIsNullShouldThrowException() { + void createWhenDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestDiscovererEndpointFilter(null)) .withMessageContaining("Discoverer must not be null"); } @Test - public void matchWhenDiscoveredByDiscovererShouldReturnTrue() { + void matchWhenDiscoveredByDiscovererShouldReturnTrue() { DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter(TestDiscovererA.class); DiscoveredEndpoint endpoint = mockDiscoveredEndpoint(TestDiscovererA.class); assertThat(filter.match(endpoint)).isTrue(); } @Test - public void matchWhenNotDiscoveredByDiscovererShouldReturnFalse() { + void matchWhenNotDiscoveredByDiscovererShouldReturnFalse() { DiscovererEndpointFilter filter = new TestDiscovererEndpointFilter(TestDiscovererA.class); DiscoveredEndpoint endpoint = mockDiscoveredEndpoint(TestDiscovererB.class); assertThat(filter.match(endpoint)).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index 7d84686e5f5..6e5734d8be0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -64,10 +64,10 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class EndpointDiscovererTests { +class EndpointDiscovererTests { @Test - public void createWhenApplicationContextIsNullShouldThrowException() { + void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), Collections.emptyList(), Collections.emptyList())) @@ -75,7 +75,7 @@ public class EndpointDiscovererTests { } @Test - public void createWhenParameterValueMapperIsNullShouldThrowException() { + void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, Collections.emptyList(), Collections.emptyList())) @@ -83,7 +83,7 @@ public class EndpointDiscovererTests { } @Test - public void createWhenInvokerAdvisorsIsNullShouldThrowException() { + void createWhenInvokerAdvisorsIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), mock(ParameterValueMapper.class), null, Collections.emptyList())) @@ -91,7 +91,7 @@ public class EndpointDiscovererTests { } @Test - public void createWhenFiltersIsNullShouldThrowException() { + void createWhenFiltersIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), mock(ParameterValueMapper.class), Collections.emptyList(), null)) @@ -99,7 +99,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { + void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { load(EmptyConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); Collection endpoints = discoverer.getEndpoints(); @@ -108,19 +108,19 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenHasEndpointShouldReturnEndpoint() { + void getEndpointsWhenHasEndpointShouldReturnEndpoint() { load(TestEndpointConfiguration.class, this::hasTestEndpoint); } @Test - public void getEndpointsWhenHasEndpointInParentContextShouldReturnEndpoint() { + void getEndpointsWhenHasEndpointInParentContextShouldReturnEndpoint() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext( TestEndpointConfiguration.class); loadWithParent(parent, EmptyConfiguration.class, this::hasTestEndpoint); } @Test - public void getEndpointsWhenHasSubclassedEndpointShouldReturnEndpoint() { + void getEndpointsWhenHasSubclassedEndpointShouldReturnEndpoint() { load(TestEndpointSubclassConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -134,7 +134,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenTwoEndpointsHaveTheSameIdShouldThrowException() { + void getEndpointsWhenTwoEndpointsHaveTheSameIdShouldThrowException() { load(ClashingEndpointConfiguration.class, (context) -> assertThatIllegalStateException() .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) @@ -142,7 +142,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenEndpointsArePrefixedWithScopedTargetShouldRegisterOnlyOneEndpoint() { + void getEndpointsWhenEndpointsArePrefixedWithScopedTargetShouldRegisterOnlyOneEndpoint() { load(ScopedTargetEndpointConfiguration.class, (context) -> { TestEndpoint expectedEndpoint = context.getBean("testEndpoint", TestEndpoint.class); Collection endpoints = new TestEndpointDiscoverer(context).getEndpoints(); @@ -151,7 +151,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenTtlSetToZeroShouldNotCacheInvokeCalls() { + void getEndpointsWhenTtlSetToZeroShouldNotCacheInvokeCalls() { load(TestEndpointConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, (endpointId) -> 0L); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -163,7 +163,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenTtlSetByIdAndIdDoesNotMatchShouldNotCacheInvokeCalls() { + void getEndpointsWhenTtlSetByIdAndIdDoesNotMatchShouldNotCacheInvokeCalls() { load(TestEndpointConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, (endpointId) -> (endpointId.equals("foo") ? 500L : 0L)); @@ -176,7 +176,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenTtlSetByIdAndIdMatchesShouldCacheInvokeCalls() { + void getEndpointsWhenTtlSetByIdAndIdMatchesShouldCacheInvokeCalls() { load(TestEndpointConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context, (endpointId) -> (endpointId.equals(EndpointId.of("test")) ? 500L : 0L)); @@ -194,7 +194,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenHasSpecializedFiltersInNonSpecializedDiscovererShouldFilterEndpoints() { + void getEndpointsWhenHasSpecializedFiltersInNonSpecializedDiscovererShouldFilterEndpoints() { load(SpecializedEndpointsConfiguration.class, (context) -> { TestEndpointDiscoverer discoverer = new TestEndpointDiscoverer(context); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -203,7 +203,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsWhenHasSpecializedFiltersInSpecializedDiscovererShouldNotFilterEndpoints() { + void getEndpointsWhenHasSpecializedFiltersInSpecializedDiscovererShouldNotFilterEndpoints() { load(SpecializedEndpointsConfiguration.class, (context) -> { SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -212,7 +212,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsShouldApplyExtensions() { + void getEndpointsShouldApplyExtensions() { load(SpecializedEndpointsConfiguration.class, (context) -> { SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -223,7 +223,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointShouldFindParentExtension() { + void getEndpointShouldFindParentExtension() { load(SubSpecializedEndpointsConfiguration.class, (context) -> { SpecializedEndpointDiscoverer discoverer = new SpecializedEndpointDiscoverer(context); Map endpoints = mapEndpoints(discoverer.getEndpoints()); @@ -237,7 +237,7 @@ public class EndpointDiscovererTests { } @Test - public void getEndpointsShouldApplyFilters() { + void getEndpointsShouldApplyFilters() { load(SpecializedEndpointsConfiguration.class, (context) -> { EndpointFilter filter = (endpoint) -> { EndpointId id = endpoint.getEndpointId(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java index 4d762e78962..726d2978042 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java @@ -39,10 +39,10 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ConversionServiceParameterValueMapperTests { +class ConversionServiceParameterValueMapperTests { @Test - public void mapParameterShouldDelegateToConversionService() { + void mapParameterShouldDelegateToConversionService() { DefaultFormattingConversionService conversionService = spy(new DefaultFormattingConversionService()); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); Object mapped = mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); @@ -51,7 +51,7 @@ public class ConversionServiceParameterValueMapperTests { } @Test - public void mapParameterWhenConversionServiceFailsShouldThrowParameterMappingException() { + void mapParameterWhenConversionServiceFailsShouldThrowParameterMappingException() { ConversionService conversionService = mock(ConversionService.class); RuntimeException error = new RuntimeException(); given(conversionService.convert(any(), any())).willThrow(error); @@ -66,7 +66,7 @@ public class ConversionServiceParameterValueMapperTests { } @Test - public void createShouldRegisterIsoOffsetDateTimeConverter() { + void createShouldRegisterIsoOffsetDateTimeConverter() { ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(); Object mapped = mapper.mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00"); @@ -74,7 +74,7 @@ public class ConversionServiceParameterValueMapperTests { } @Test - public void createWithConversionServiceShouldNotRegisterIsoOffsetDateTimeConverter() { + void createWithConversionServiceShouldNotRegisterIsoOffsetDateTimeConverter() { ConversionService conversionService = new DefaultConversionService(); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class).isThrownBy(() -> mapper diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java index db508839652..97debc038e2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/IsoOffsetDateTimeConverterTests.java @@ -29,17 +29,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class IsoOffsetDateTimeConverterTests { +class IsoOffsetDateTimeConverterTests { @Test - public void convertShouldConvertIsoDate() { + void convertShouldConvertIsoDate() { IsoOffsetDateTimeConverter converter = new IsoOffsetDateTimeConverter(); OffsetDateTime time = converter.convert("2011-12-03T10:15:30+01:00"); assertThat(time).isNotNull(); } @Test - public void registerConverterShouldRegister() { + void registerConverterShouldRegister() { DefaultConversionService service = new DefaultConversionService(); IsoOffsetDateTimeConverter.registerConverter(service); OffsetDateTime time = service.convert("2011-12-03T10:15:30+01:00", OffsetDateTime.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java index 77999e76724..5a5a3695457 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParameterTests.java @@ -30,30 +30,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class OperationMethodParameterTests { +class OperationMethodParameterTests { private Method method = ReflectionUtils.findMethod(getClass(), "example", String.class, String.class); @Test - public void getNameShouldReturnName() { + void getNameShouldReturnName() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getName()).isEqualTo("name"); } @Test - public void getTypeShouldReturnType() { + void getTypeShouldReturnType() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.getType()).isEqualTo(String.class); } @Test - public void isMandatoryWhenNoAnnotationShouldReturnTrue() { + void isMandatoryWhenNoAnnotationShouldReturnTrue() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[0]); assertThat(parameter.isMandatory()).isTrue(); } @Test - public void isMandatoryWhenNullableAnnotationShouldReturnFalse() { + void isMandatoryWhenNullableAnnotationShouldReturnFalse() { OperationMethodParameter parameter = new OperationMethodParameter("name", this.method.getParameters()[1]); assertThat(parameter.isMandatory()).isFalse(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java index 6b78ba9a696..f18c92b8eea 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java @@ -42,27 +42,27 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OperationMethodParametersTests { +class OperationMethodParametersTests { private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); private Method exampleNoParamsMethod = ReflectionUtils.findMethod(getClass(), "exampleNoParams"); @Test - public void createWhenMethodIsNullShouldThrowException() { + void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) .withMessageContaining("Method must not be null"); } @Test - public void createWhenParameterNameDiscovererIsNullShouldThrowException() { + void createWhenParameterNameDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) .withMessageContaining("ParameterNameDiscoverer must not be null"); } @Test - public void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { + void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { assertThatIllegalStateException() .isThrownBy( () -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) @@ -70,28 +70,28 @@ public class OperationMethodParametersTests { } @Test - public void hasParametersWhenHasParametersShouldReturnTrue() { + void hasParametersWhenHasParametersShouldReturnTrue() { OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, new DefaultParameterNameDiscoverer()); assertThat(parameters.hasParameters()).isTrue(); } @Test - public void hasParametersWhenHasNoParametersShouldReturnFalse() { + void hasParametersWhenHasNoParametersShouldReturnFalse() { OperationMethodParameters parameters = new OperationMethodParameters(this.exampleNoParamsMethod, new DefaultParameterNameDiscoverer()); assertThat(parameters.hasParameters()).isFalse(); } @Test - public void getParameterCountShouldReturnParameterCount() { + void getParameterCountShouldReturnParameterCount() { OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, new DefaultParameterNameDiscoverer()); assertThat(parameters.getParameterCount()).isEqualTo(1); } @Test - public void iteratorShouldIterateOperationParameters() { + void iteratorShouldIterateOperationParameters() { OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, new DefaultParameterNameDiscoverer()); Iterator iterator = parameters.iterator(); @@ -100,7 +100,7 @@ public class OperationMethodParametersTests { } @Test - public void streamShouldStreamOperationParameters() { + void streamShouldStreamOperationParameters() { OperationMethodParameters parameters = new OperationMethodParameters(this.exampleMethod, new DefaultParameterNameDiscoverer()); assertParameters(parameters.stream()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java index a41a4de1f0a..577e3e63a45 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java @@ -32,36 +32,36 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class OperationMethodTests { +class OperationMethodTests { private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); @Test - public void createWhenMethodIsNullShouldThrowException() { + void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(null, OperationType.READ)) .withMessageContaining("Method must not be null"); } @Test - public void createWhenOperationTypeIsNullShouldThrowException() { + void createWhenOperationTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) .withMessageContaining("OperationType must not be null"); } @Test - public void getMethodShouldReturnMethod() { + void getMethodShouldReturnMethod() { OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); assertThat(operationMethod.getMethod()).isEqualTo(this.exampleMethod); } @Test - public void getOperationTypeShouldReturnOperationType() { + void getOperationTypeShouldReturnOperationType() { OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); assertThat(operationMethod.getOperationType()).isEqualTo(OperationType.READ); } @Test - public void getParametersShouldReturnParameters() { + void getParametersShouldReturnParameters() { OperationMethod operationMethod = new OperationMethod(this.exampleMethod, OperationType.READ); OperationParameters parameters = operationMethod.getParameters(); assertThat(parameters.getParameterCount()).isEqualTo(1); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java index 06072d5a1ef..dcf1a9a3bb3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ReflectiveOperationInvokerTests { +class ReflectiveOperationInvokerTests { private Example target; @@ -56,28 +56,28 @@ public class ReflectiveOperationInvokerTests { } @Test - public void createWhenTargetIsNullShouldThrowException() { + void createWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) .withMessageContaining("Target must not be null"); } @Test - public void createWhenOperationMethodIsNullShouldThrowException() { + void createWhenOperationMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) .withMessageContaining("OperationMethod must not be null"); } @Test - public void createWhenParameterValueMapperIsNullShouldThrowException() { + void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) .withMessageContaining("ParameterValueMapper must not be null"); } @Test - public void invokeShouldInvokeMethod() { + void invokeShouldInvokeMethod() { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker @@ -86,7 +86,7 @@ public class ReflectiveOperationInvokerTests { } @Test - public void invokeWhenMissingNonNullableArgumentShouldThrowException() { + void invokeWhenMissingNonNullableArgumentShouldThrowException() { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); assertThatExceptionOfType(MissingParametersException.class).isThrownBy(() -> invoker @@ -94,7 +94,7 @@ public class ReflectiveOperationInvokerTests { } @Test - public void invokeWhenMissingNullableArgumentShouldInvoke() { + void invokeWhenMissingNullableArgumentShouldInvoke() { OperationMethod operationMethod = new OperationMethod( ReflectionUtils.findMethod(Example.class, "reverseNullable", String.class), OperationType.READ); ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, operationMethod, @@ -105,7 +105,7 @@ public class ReflectiveOperationInvokerTests { } @Test - public void invokeShouldResolveParameters() { + void invokeShouldResolveParameters() { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java index 260a2988672..362c0d69092 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerAdvisorTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Stephane Nicoll */ -public class CachingOperationInvokerAdvisorTests { +class CachingOperationInvokerAdvisorTests { @Mock private OperationInvoker invoker; @@ -61,7 +61,7 @@ public class CachingOperationInvokerAdvisorTests { } @Test - public void applyWhenOperationIsNotReadShouldNotAddAdvise() { + void applyWhenOperationIsNotReadShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.WRITE, parameters, this.invoker); @@ -69,7 +69,7 @@ public class CachingOperationInvokerAdvisorTests { } @Test - public void applyWhenHasAtLeaseOneMandatoryParameterShouldNotAddAdvise() { + void applyWhenHasAtLeaseOneMandatoryParameterShouldNotAddAdvise() { OperationParameters parameters = getParameters("getWithParameters", String.class, String.class); OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, this.invoker); @@ -77,7 +77,7 @@ public class CachingOperationInvokerAdvisorTests { } @Test - public void applyWhenTimeToLiveReturnsNullShouldNotAddAdvise() { + void applyWhenTimeToLiveReturnsNullShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); given(this.timeToLive.apply(any())).willReturn(null); OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, @@ -87,7 +87,7 @@ public class CachingOperationInvokerAdvisorTests { } @Test - public void applyWhenTimeToLiveIsZeroShouldNotAddAdvise() { + void applyWhenTimeToLiveIsZeroShouldNotAddAdvise() { OperationParameters parameters = getParameters("get"); given(this.timeToLive.apply(any())).willReturn(0L); OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, @@ -97,21 +97,21 @@ public class CachingOperationInvokerAdvisorTests { } @Test - public void applyShouldAddCacheAdvise() { + void applyShouldAddCacheAdvise() { OperationParameters parameters = getParameters("get"); given(this.timeToLive.apply(any())).willReturn(100L); assertAdviseIsApplied(parameters); } @Test - public void applyWithAllOptionalParametersShouldAddAdvise() { + void applyWithAllOptionalParametersShouldAddAdvise() { OperationParameters parameters = getParameters("getWithAllOptionalParameters", String.class, String.class); given(this.timeToLive.apply(any())).willReturn(100L); assertAdviseIsApplied(parameters); } @Test - public void applyWithSecurityContextShouldAddAdvise() { + void applyWithSecurityContextShouldAddAdvise() { OperationParameters parameters = getParameters("getWithSecurityContext", SecurityContext.class, String.class); given(this.timeToLive.apply(any())).willReturn(100L); assertAdviseIsApplied(parameters); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java index e1eeffbdd12..322a771ecb8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java @@ -40,22 +40,22 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * * @author Stephane Nicoll */ -public class CachingOperationInvokerTests { +class CachingOperationInvokerTests { @Test - public void createInstanceWithTtlSetToZero() { + void createInstanceWithTtlSetToZero() { assertThatIllegalArgumentException() .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) .withMessageContaining("TimeToLive"); } @Test - public void cacheInTtlRangeWithNoParameter() { + void cacheInTtlRangeWithNoParameter() { assertCacheIsUsed(Collections.emptyMap()); } @Test - public void cacheInTtlWithNullParameters() { + void cacheInTtlWithNullParameters() { Map parameters = new HashMap<>(); parameters.put("first", null); parameters.put("second", null); @@ -77,7 +77,7 @@ public class CachingOperationInvokerTests { } @Test - public void targetAlwaysInvokedWithParameters() { + void targetAlwaysInvokedWithParameters() { OperationInvoker target = mock(OperationInvoker.class); Map parameters = new HashMap<>(); parameters.put("test", "value"); @@ -92,7 +92,7 @@ public class CachingOperationInvokerTests { } @Test - public void targetAlwaysInvokedWithPrincipal() { + void targetAlwaysInvokedWithPrincipal() { OperationInvoker target = mock(OperationInvoker.class); Map parameters = new HashMap<>(); SecurityContext securityContext = mock(SecurityContext.class); @@ -107,7 +107,7 @@ public class CachingOperationInvokerTests { } @Test - public void targetInvokedWhenCacheExpires() throws InterruptedException { + void targetInvokedWhenCacheExpires() throws InterruptedException { OperationInvoker target = mock(OperationInvoker.class); Map parameters = new HashMap<>(); InvocationContext context = new InvocationContext(mock(SecurityContext.class), parameters); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java index e90f62d6978..fa32a928a7f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java @@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Stephane Nicoll */ -public class EndpointMBeanTests { +class EndpointMBeanTests { private static final Object[] NO_PARAMS = {}; @@ -59,35 +59,35 @@ public class EndpointMBeanTests { private TestJmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @Test - public void createWhenResponseMapperIsNullShouldThrowException() { + void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) .withMessageContaining("ResponseMapper must not be null"); } @Test - public void createWhenEndpointIsNullShouldThrowException() { + void createWhenEndpointIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) .withMessageContaining("Endpoint must not be null"); } @Test - public void getMBeanInfoShouldReturnMBeanInfo() { + void getMBeanInfoShouldReturnMBeanInfo() { EndpointMBean bean = createEndpointMBean(); MBeanInfo info = bean.getMBeanInfo(); assertThat(info.getDescription()).isEqualTo("MBean operations for endpoint test"); } @Test - public void invokeShouldInvokeJmxOperation() throws MBeanException, ReflectionException { + void invokeShouldInvokeJmxOperation() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); assertThat(result).isEqualTo("result"); } @Test - public void invokeWhenOperationFailedShouldTranslateException() throws MBeanException, ReflectionException { + void invokeWhenOperationFailedShouldTranslateException() throws MBeanException, ReflectionException { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> { throw new FatalBeanException("test failure"); })); @@ -99,8 +99,7 @@ public class EndpointMBeanTests { } @Test - public void invokeWhenOperationFailedWithJdkExceptionShouldReuseException() - throws MBeanException, ReflectionException { + void invokeWhenOperationFailedWithJdkExceptionShouldReuseException() throws MBeanException, ReflectionException { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> { throw new UnsupportedOperationException("test failure"); })); @@ -111,7 +110,7 @@ public class EndpointMBeanTests { } @Test - public void invokeWhenActionNameIsNotAnOperationShouldThrowException() throws MBeanException, ReflectionException { + void invokeWhenActionNameIsNotAnOperationShouldThrowException() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(ReflectionException.class) .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) @@ -120,7 +119,7 @@ public class EndpointMBeanTests { } @Test - public void invokeShouldInvokeJmxOperationWithBeanClassLoader() throws ReflectionException, MBeanException { + void invokeShouldInvokeJmxOperationWithBeanClassLoader() throws ReflectionException, MBeanException { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( new TestJmxOperation((arguments) -> ClassUtils.getDefaultClassLoader())); @@ -132,7 +131,7 @@ public class EndpointMBeanTests { } @Test - public void invokeWhenOperationIsInvalidShouldThrowException() throws MBeanException, ReflectionException { + void invokeWhenOperationIsInvalidShouldThrowException() throws MBeanException, ReflectionException { TestJmxOperation operation = new TestJmxOperation() { @Override @@ -149,7 +148,7 @@ public class EndpointMBeanTests { } @Test - public void invokeWhenMonoResultShouldBlockOnMono() throws MBeanException, ReflectionException { + void invokeWhenMonoResultShouldBlockOnMono() throws MBeanException, ReflectionException { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( new TestJmxOperation((arguments) -> Mono.just("monoResult"))); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); @@ -158,7 +157,7 @@ public class EndpointMBeanTests { } @Test - public void invokeShouldCallResponseMapper() throws MBeanException, ReflectionException { + void invokeShouldCallResponseMapper() throws MBeanException, ReflectionException { TestJmxOperationResponseMapper responseMapper = spy(this.responseMapper); EndpointMBean bean = new EndpointMBean(responseMapper, null, this.endpoint); bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); @@ -167,15 +166,14 @@ public class EndpointMBeanTests { } @Test - public void getAttributeShouldThrowException() - throws AttributeNotFoundException, MBeanException, ReflectionException { + void getAttributeShouldThrowException() throws AttributeNotFoundException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class).isThrownBy(() -> bean.getAttribute("test")) .withMessageContaining("EndpointMBeans do not support attributes"); } @Test - public void setAttributeShouldThrowException() + void setAttributeShouldThrowException() throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class) @@ -184,14 +182,14 @@ public class EndpointMBeanTests { } @Test - public void getAttributesShouldReturnEmptyAttributeList() { + void getAttributesShouldReturnEmptyAttributeList() { EndpointMBean bean = createEndpointMBean(); AttributeList attributes = bean.getAttributes(new String[] { "test" }); assertThat(attributes).isEmpty(); } @Test - public void setAttributesShouldReturnEmptyAttributeList() { + void setAttributesShouldReturnEmptyAttributeList() { EndpointMBean bean = createEndpointMBean(); AttributeList sourceAttributes = new AttributeList(); sourceAttributes.add(new Attribute("test", "test")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java index 52efb31eedd..09fbc96a418 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapperTests.java @@ -40,21 +40,21 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class JacksonJmxOperationResponseMapperTests { +class JacksonJmxOperationResponseMapperTests { private JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(null); private final BasicJsonTester json = new BasicJsonTester(getClass()); @Test - public void createWhenObjectMapperIsNullShouldUseDefaultObjectMapper() { + void createWhenObjectMapperIsNullShouldUseDefaultObjectMapper() { JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(null); Object mapped = mapper.mapResponse(Collections.singleton("test")); assertThat(this.json.from(mapped.toString())).isEqualToJson("[test]"); } @Test - public void createWhenObjectMapperIsSpecifiedShouldUseObjectMapper() { + void createWhenObjectMapperIsSpecifiedShouldUseObjectMapper() { ObjectMapper objectMapper = spy(ObjectMapper.class); JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(objectMapper); Set response = Collections.singleton("test"); @@ -63,53 +63,53 @@ public class JacksonJmxOperationResponseMapperTests { } @Test - public void mapResponseTypeWhenCharSequenceShouldReturnString() { + void mapResponseTypeWhenCharSequenceShouldReturnString() { assertThat(this.mapper.mapResponseType(String.class)).isEqualTo(String.class); assertThat(this.mapper.mapResponseType(StringBuilder.class)).isEqualTo(String.class); } @Test - public void mapResponseTypeWhenArrayShouldReturnList() { + void mapResponseTypeWhenArrayShouldReturnList() { assertThat(this.mapper.mapResponseType(String[].class)).isEqualTo(List.class); assertThat(this.mapper.mapResponseType(Object[].class)).isEqualTo(List.class); } @Test - public void mapResponseTypeWhenCollectionShouldReturnList() { + void mapResponseTypeWhenCollectionShouldReturnList() { assertThat(this.mapper.mapResponseType(Collection.class)).isEqualTo(List.class); assertThat(this.mapper.mapResponseType(Set.class)).isEqualTo(List.class); assertThat(this.mapper.mapResponseType(List.class)).isEqualTo(List.class); } @Test - public void mapResponseTypeWhenOtherShouldReturnMap() { + void mapResponseTypeWhenOtherShouldReturnMap() { assertThat(this.mapper.mapResponseType(ExampleBean.class)).isEqualTo(Map.class); } @Test - public void mapResponseWhenNullShouldReturnNull() { + void mapResponseWhenNullShouldReturnNull() { assertThat(this.mapper.mapResponse(null)).isNull(); } @Test - public void mapResponseWhenCharSequenceShouldReturnString() { + void mapResponseWhenCharSequenceShouldReturnString() { assertThat(this.mapper.mapResponse(new StringBuilder("test"))).isEqualTo("test"); } @Test - public void mapResponseWhenArrayShouldReturnJsonArray() { + void mapResponseWhenArrayShouldReturnJsonArray() { Object mapped = this.mapper.mapResponse(new int[] { 1, 2, 3 }); assertThat(this.json.from(mapped.toString())).isEqualToJson("[1,2,3]"); } @Test - public void mapResponseWhenCollectionShouldReturnJsonArray() { + void mapResponseWhenCollectionShouldReturnJsonArray() { Object mapped = this.mapper.mapResponse(Arrays.asList("a", "b", "c")); assertThat(this.json.from(mapped.toString())).isEqualToJson("[a,b,c]"); } @Test - public void mapResponseWhenOtherShouldReturnMap() { + void mapResponseWhenOtherShouldReturnMap() { ExampleBean bean = new ExampleBean(); bean.setName("boot"); Object mapped = this.mapper.mapResponse(bean); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java index 01a1de77c44..cd5643ffa1c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java @@ -51,7 +51,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Phillip Webb */ -public class JmxEndpointExporterTests { +class JmxEndpointExporterTests { @Mock private MBeanServer mBeanServer; @@ -78,21 +78,21 @@ public class JmxEndpointExporterTests { } @Test - public void createWhenMBeanServerIsNullShouldThrowException() { + void createWhenMBeanServerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) .withMessageContaining("MBeanServer must not be null"); } @Test - public void createWhenObjectNameFactoryIsNullShouldThrowException() { + void createWhenObjectNameFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) .withMessageContaining("ObjectNameFactory must not be null"); } @Test - public void createWhenResponseMapperIsNullShouldThrowException() { + void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) @@ -100,14 +100,14 @@ public class JmxEndpointExporterTests { } @Test - public void createWhenEndpointsIsNullShouldThrowException() { + void createWhenEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) .withMessageContaining("Endpoints must not be null"); } @Test - public void afterPropertiesSetShouldRegisterMBeans() throws Exception { + void afterPropertiesSetShouldRegisterMBeans() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); verify(this.mBeanServer).registerMBean(this.objectCaptor.capture(), this.objectNameCaptor.capture()); @@ -116,14 +116,14 @@ public class JmxEndpointExporterTests { } @Test - public void registerShouldUseObjectNameFactory() throws Exception { + void registerShouldUseObjectNameFactory() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); verify(this.objectNameFactory).getObjectName(any(ExposableJmxEndpoint.class)); } @Test - public void registerWhenObjectNameIsMalformedShouldThrowException() throws Exception { + void registerWhenObjectNameIsMalformedShouldThrowException() throws Exception { given(this.objectNameFactory.getObjectName(any(ExposableJmxEndpoint.class))) .willThrow(MalformedObjectNameException.class); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); @@ -132,7 +132,7 @@ public class JmxEndpointExporterTests { } @Test - public void registerWhenRegistrationFailsShouldThrowException() throws Exception { + void registerWhenRegistrationFailsShouldThrowException() throws Exception { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); @@ -141,7 +141,7 @@ public class JmxEndpointExporterTests { } @Test - public void destroyShouldUnregisterMBeans() throws Exception { + void destroyShouldUnregisterMBeans() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); this.exporter.destroy(); @@ -150,7 +150,7 @@ public class JmxEndpointExporterTests { } @Test - public void unregisterWhenInstanceNotFoundShouldContinue() throws Exception { + void unregisterWhenInstanceNotFoundShouldContinue() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(InstanceNotFoundException.class).given(this.mBeanServer).unregisterMBean(any(ObjectName.class)); @@ -158,7 +158,7 @@ public class JmxEndpointExporterTests { } @Test - public void unregisterWhenUnregisterThrowsExceptionShouldThrowException() throws Exception { + void unregisterWhenUnregisterThrowsExceptionShouldThrowException() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java index d40ae4b8dba..fbb349313f3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java @@ -37,12 +37,12 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class MBeanInfoFactoryTests { +class MBeanInfoFactoryTests { private MBeanInfoFactory factory = new MBeanInfoFactory(new TestJmxOperationResponseMapper()); @Test - public void getMBeanInfoShouldReturnMBeanInfo() { + void getMBeanInfoShouldReturnMBeanInfo() { MBeanInfo info = this.factory.getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThat(info).isNotNull(); assertThat(info.getClassName()).isEqualTo(EndpointMBean.class.getName()); @@ -59,21 +59,21 @@ public class MBeanInfoFactoryTests { } @Test - public void getMBeanInfoWhenReadOperationShouldHaveInfoImpact() { + void getMBeanInfoWhenReadOperationShouldHaveInfoImpact() { MBeanInfo info = this.factory .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.INFO); } @Test - public void getMBeanInfoWhenWriteOperationShouldHaveActionImpact() { + void getMBeanInfoWhenWriteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); } @Test - public void getMBeanInfoWhenDeleteOperationShouldHaveActionImpact() { + void getMBeanInfoWhenDeleteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); assertThat(info.getOperations()[0].getImpact()).isEqualTo(MBeanOperationInfo.ACTION); @@ -81,7 +81,7 @@ public class MBeanInfoFactoryTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void getMBeanInfoShouldUseJmxOperationResponseMapper() { + void getMBeanInfoShouldUseJmxOperationResponseMapper() { JmxOperationResponseMapper mapper = mock(JmxOperationResponseMapper.class); given(mapper.mapResponseType(String.class)).willReturn((Class) Integer.class); MBeanInfoFactory factory = new MBeanInfoFactory(mapper); @@ -91,7 +91,7 @@ public class MBeanInfoFactoryTests { } @Test - public void getMBeanShouldMapOperationParameters() { + void getMBeanShouldMapOperationParameters() { List parameters = new ArrayList<>(); parameters.add(mockParameter("one", String.class, "myone")); parameters.add(mockParameter("two", Object.class, null)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java index d32b03c78ab..a9165b782c6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperationTests.java @@ -45,16 +45,16 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class DiscoveredJmxOperationTests { +class DiscoveredJmxOperationTests { @Test - public void getNameShouldReturnMethodName() { + void getNameShouldReturnMethodName() { DiscoveredJmxOperation operation = getOperation("getEnum"); assertThat(operation.getName()).isEqualTo("getEnum"); } @Test - public void getOutputTypeShouldReturnJmxType() { + void getOutputTypeShouldReturnJmxType() { assertThat(getOperation("getEnum").getOutputType()).isEqualTo(String.class); assertThat(getOperation("getDate").getOutputType()).isEqualTo(String.class); assertThat(getOperation("getInstant").getOutputType()).isEqualTo(String.class); @@ -64,25 +64,25 @@ public class DiscoveredJmxOperationTests { } @Test - public void getDescriptionWhenHasManagedOperationDescriptionShouldUseValueFromAnnotation() { + void getDescriptionWhenHasManagedOperationDescriptionShouldUseValueFromAnnotation() { DiscoveredJmxOperation operation = getOperation("withManagedOperationDescription"); assertThat(operation.getDescription()).isEqualTo("fromannotation"); } @Test - public void getDescriptionWhenHasNoManagedOperationShouldGenerateDescription() { + void getDescriptionWhenHasNoManagedOperationShouldGenerateDescription() { DiscoveredJmxOperation operation = getOperation("getEnum"); assertThat(operation.getDescription()).isEqualTo("Invoke getEnum for endpoint test"); } @Test - public void getParametersWhenHasNoParametersShouldReturnEmptyList() { + void getParametersWhenHasNoParametersShouldReturnEmptyList() { DiscoveredJmxOperation operation = getOperation("getEnum"); assertThat(operation.getParameters()).isEmpty(); } @Test - public void getParametersShouldReturnJmxTypes() { + void getParametersShouldReturnJmxTypes() { DiscoveredJmxOperation operation = getOperation("params"); List parameters = operation.getParameters(); assertThat(parameters.get(0).getType()).isEqualTo(String.class); @@ -93,7 +93,7 @@ public class DiscoveredJmxOperationTests { } @Test - public void getParametersWhenHasManagedOperationParameterShouldUseValuesFromAnnotation() { + void getParametersWhenHasManagedOperationParameterShouldUseValuesFromAnnotation() { DiscoveredJmxOperation operation = getOperation("withManagedOperationParameters"); List parameters = operation.getParameters(); assertThat(parameters.get(0).getName()).isEqualTo("a1"); @@ -103,7 +103,7 @@ public class DiscoveredJmxOperationTests { } @Test - public void getParametersWhenHasNoManagedOperationParameterShouldDeducedValuesName() { + void getParametersWhenHasNoManagedOperationParameterShouldDeducedValuesName() { DiscoveredJmxOperation operation = getOperation("params"); List parameters = operation.getParameters(); assertThat(parameters.get(0).getName()).isEqualTo("enumParam"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java index 82e755eda09..c6dc8be8889 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java @@ -56,15 +56,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Stephane Nicoll * @author Phillip Webb */ -public class JmxEndpointDiscovererTests { +class JmxEndpointDiscovererTests { @Test - public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { + void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { load(EmptyConfiguration.class, (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); } @Test - public void getEndpointsShouldDiscoverStandardEndpoints() { + void getEndpointsShouldDiscoverStandardEndpoints() { load(TestEndpoint.class, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -95,7 +95,7 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverJmxEndpoints() { + void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverJmxEndpoints() { load(MultipleEndpointsConfiguration.class, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test"), EndpointId.of("jmx")); @@ -103,14 +103,14 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { + void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { load(TestJmxEndpointExtension.class, (discoverer) -> assertThatIllegalStateException() .isThrownBy(discoverer::getEndpoints).withMessageContaining( "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); } @Test - public void getEndpointsWhenHasJmxExtensionShouldOverrideStandardEndpoint() { + void getEndpointsWhenHasJmxExtensionShouldOverrideStandardEndpoint() { load(OverriddenOperationJmxEndpointConfiguration.class, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -119,7 +119,7 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasJmxExtensionWithNewOperationAddsExtraOperation() { + void getEndpointsWhenHasJmxExtensionWithNewOperationAddsExtraOperation() { load(AdditionalOperationJmxEndpointConfiguration.class, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -135,7 +135,7 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { + void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { load(TestEndpoint.class, (id) -> 500L, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -149,7 +149,7 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsShouldCacheReadOperations() { + void getEndpointsShouldCacheReadOperations() { load(AdditionalOperationJmxEndpointConfiguration.class, (id) -> 500L, (discoverer) -> { Map endpoints = discover(discoverer); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -167,35 +167,35 @@ public class JmxEndpointDiscovererTests { } @Test - public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { + void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingJmxEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException() .isThrownBy(discoverer::getEndpoints).withMessageContaining( "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test - public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { + void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test - public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { + void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpoint.class, (discoverer) -> assertThatIllegalStateException() .isThrownBy(discoverer::getEndpoints).withMessageContaining( "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); } @Test - public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { + void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(AdditionalClashingOperationsConfiguration.class, (discoverer) -> assertThatIllegalStateException() .isThrownBy(discoverer::getEndpoints).withMessageContaining( "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); } @Test - public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { + void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidJmxExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException() .isThrownBy(discoverer::getEndpoints).withMessageContaining( "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java index 1e856eed439..8ca98ddd660 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java @@ -37,10 +37,10 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class EndpointLinksResolverTests { +class EndpointLinksResolverTests { @Test - public void linkResolutionWithTrailingSlashStripsSlashOnSelfLink() { + void linkResolutionWithTrailingSlashStripsSlashOnSelfLink() { Map links = new EndpointLinksResolver(Collections.emptyList()) .resolveLinks("https://api.example.com/actuator/"); assertThat(links).hasSize(1); @@ -48,7 +48,7 @@ public class EndpointLinksResolverTests { } @Test - public void linkResolutionWithoutTrailingSlash() { + void linkResolutionWithoutTrailingSlash() { Map links = new EndpointLinksResolver(Collections.emptyList()) .resolveLinks("https://api.example.com/actuator"); assertThat(links).hasSize(1); @@ -56,7 +56,7 @@ public class EndpointLinksResolverTests { } @Test - public void resolvedLinksContainsALinkForEachWebEndpointOperation() { + void resolvedLinksContainsALinkForEachWebEndpointOperation() { List operations = new ArrayList<>(); operations.add(operationWithPath("/alpha", "alpha")); operations.add(operationWithPath("/alpha/{name}", "alpha-name")); @@ -75,7 +75,7 @@ public class EndpointLinksResolverTests { } @Test - public void resolvedLinksContainsALinkForServletEndpoint() { + void resolvedLinksContainsALinkForServletEndpoint() { ExposableServletEndpoint servletEndpoint = mock(ExposableServletEndpoint.class); given(servletEndpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); given(servletEndpoint.isEnableByDefault()).willReturn(true); @@ -89,7 +89,7 @@ public class EndpointLinksResolverTests { } @Test - public void resolvedLinksContainsALinkForControllerEndpoint() { + void resolvedLinksContainsALinkForControllerEndpoint() { ExposableControllerEndpoint controllerEndpoint = mock(ExposableControllerEndpoint.class); given(controllerEndpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); given(controllerEndpoint.isEnableByDefault()).willReturn(true); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java index 266f6bf7b62..243b4932a84 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMappingTests.java @@ -25,55 +25,55 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class EndpointMappingTests { +class EndpointMappingTests { @Test - public void normalizationTurnsASlashIntoAnEmptyString() { + void normalizationTurnsASlashIntoAnEmptyString() { assertThat(new EndpointMapping("/").getPath()).isEqualTo(""); } @Test - public void normalizationLeavesAnEmptyStringAsIs() { + void normalizationLeavesAnEmptyStringAsIs() { assertThat(new EndpointMapping("").getPath()).isEqualTo(""); } @Test - public void normalizationRemovesATrailingSlash() { + void normalizationRemovesATrailingSlash() { assertThat(new EndpointMapping("/test/").getPath()).isEqualTo("/test"); } @Test - public void normalizationAddsALeadingSlash() { + void normalizationAddsALeadingSlash() { assertThat(new EndpointMapping("test").getPath()).isEqualTo("/test"); } @Test - public void normalizationAddsALeadingSlashAndRemovesATrailingSlash() { + void normalizationAddsALeadingSlashAndRemovesATrailingSlash() { assertThat(new EndpointMapping("test/").getPath()).isEqualTo("/test"); } @Test - public void normalizationLeavesAPathWithALeadingSlashAndNoTrailingSlashAsIs() { + void normalizationLeavesAPathWithALeadingSlashAndNoTrailingSlashAsIs() { assertThat(new EndpointMapping("/test").getPath()).isEqualTo("/test"); } @Test - public void subPathForAnEmptyStringReturnsBasePath() { + void subPathForAnEmptyStringReturnsBasePath() { assertThat(new EndpointMapping("/test").createSubPath("")).isEqualTo("/test"); } @Test - public void subPathWithALeadingSlashIsSeparatedFromBasePathBySingleSlash() { + void subPathWithALeadingSlashIsSeparatedFromBasePathBySingleSlash() { assertThat(new EndpointMapping("/test").createSubPath("/one")).isEqualTo("/test/one"); } @Test - public void subPathWithoutALeadingSlashIsSeparatedFromBasePathBySingleSlash() { + void subPathWithoutALeadingSlashIsSeparatedFromBasePathBySingleSlash() { assertThat(new EndpointMapping("/test").createSubPath("one")).isEqualTo("/test/one"); } @Test - public void trailingSlashIsRemovedFromASubPath() { + void trailingSlashIsRemovedFromASubPath() { assertThat(new EndpointMapping("/test").createSubPath("one/")).isEqualTo("/test/one"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java index baad9ade1ee..2874f85014b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java @@ -30,29 +30,29 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class EndpointMediaTypesTests { +class EndpointMediaTypesTests { @Test - public void createWhenProducedIsNullShouldThrowException() { + void createWhenProducedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) .withMessageContaining("Produced must not be null"); } @Test - public void createWhenConsumedIsNullShouldThrowException() { + void createWhenConsumedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) .withMessageContaining("Consumed must not be null"); } @Test - public void getProducedShouldReturnProduced() { + void getProducedShouldReturnProduced() { List produced = Arrays.asList("a", "b", "c"); EndpointMediaTypes types = new EndpointMediaTypes(produced, Collections.emptyList()); assertThat(types.getProduced()).isEqualTo(produced); } @Test - public void getConsumedShouldReturnConsumed() { + void getConsumedShouldReturnConsumed() { List consumed = Arrays.asList("a", "b", "c"); EndpointMediaTypes types = new EndpointMediaTypes(Collections.emptyList(), consumed); assertThat(types.getConsumed()).isEqualTo(consumed); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java index 791fe23e5ca..df1568b11b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java @@ -37,53 +37,53 @@ import static org.assertj.core.api.Assertions.entry; * @author Phillip Webb * @author Stephane Nicoll */ -public class EndpointServletTests { +class EndpointServletTests { @Test - public void createWhenServletClassIsNullShouldThrowException() { + void createWhenServletClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Class) null)) .withMessageContaining("Servlet must not be null"); } @Test - public void createWhenServletIsNullShouldThrowException() { + void createWhenServletIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Servlet) null)) .withMessageContaining("Servlet must not be null"); } @Test - public void createWithServletClassShouldCreateServletInstance() { + void createWithServletClassShouldCreateServletInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.getServlet()).isInstanceOf(TestServlet.class); } @Test - public void getServletShouldGetServlet() { + void getServletShouldGetServlet() { TestServlet servlet = new TestServlet(); EndpointServlet endpointServlet = new EndpointServlet(servlet); assertThat(endpointServlet.getServlet()).isEqualTo(servlet); } @Test - public void withInitParameterNullName() { + void withInitParameterNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet.withInitParameter(null, "value")); } @Test - public void withInitParameterEmptyName() { + void withInitParameterEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet.withInitParameter(" ", "value")); } @Test - public void withInitParameterShouldReturnNewInstance() { + void withInitParameterShouldReturnNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.withInitParameter("spring", "boot")).isNotSameAs(endpointServlet); } @Test - public void withInitParameterWhenHasExistingShouldMergeParameters() { + void withInitParameterWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") .withInitParameter("c", "d"); assertThat(endpointServlet.withInitParameter("a", "b1").withInitParameter("e", "f").getInitParameters()) @@ -91,28 +91,28 @@ public class EndpointServletTests { } @Test - public void withInitParametersNullName() { + void withInitParametersNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); } @Test - public void withInitParametersEmptyName() { + void withInitParametersEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); } @Test - public void withInitParametersShouldCreateNewInstance() { + void withInitParametersShouldCreateNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.withInitParameters(Collections.singletonMap("spring", "boot"))) .isNotSameAs(endpointServlet); } @Test - public void withInitParametersWhenHasExistingShouldMergeParameters() { + void withInitParametersWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") .withInitParameter("c", "d"); Map extra = new LinkedHashMap<>(); @@ -123,13 +123,13 @@ public class EndpointServletTests { } @Test - public void withLoadOnStartupNotSetShouldReturnDefaultValue() { + void withLoadOnStartupNotSetShouldReturnDefaultValue() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.getLoadOnStartup()).isEqualTo(-1); } @Test - public void withLoadOnStartupSetShouldReturnValue() { + void withLoadOnStartupSetShouldReturnValue() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withLoadOnStartup(3); assertThat(endpointServlet.getLoadOnStartup()).isEqualTo(3); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java index ff5ad0af81d..7921b178ccc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java @@ -26,30 +26,30 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class LinkTests { +class LinkTests { @Test - public void createWhenHrefIsNullShouldThrowException() { + void createWhenHrefIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Link(null)) .withMessageContaining("HREF must not be null"); } @Test - public void getHrefShouldReturnHref() { + void getHrefShouldReturnHref() { String href = "https://example.com"; Link link = new Link(href); assertThat(link.getHref()).isEqualTo(href); } @Test - public void isTemplatedWhenContainsPlaceholderShouldReturnTrue() { + void isTemplatedWhenContainsPlaceholderShouldReturnTrue() { String href = "https://example.com/{path}"; Link link = new Link(href); assertThat(link.isTemplated()).isTrue(); } @Test - public void isTemplatedWhenContainsNoPlaceholderShouldReturnFalse() { + void isTemplatedWhenContainsNoPlaceholderShouldReturnFalse() { String href = "https://example.com/path"; Link link = new Link(href); assertThat(link.isTemplated()).isFalse(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index 599af2bc88b..8ff649d4e96 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java @@ -37,80 +37,80 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class PathMappedEndpointsTests { +class PathMappedEndpointsTests { @Test - public void createWhenSupplierIsNullShouldThrowException() { + void createWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) .withMessageContaining("Supplier must not be null"); } @Test - public void createWhenSuppliersIsNullShouldThrowException() { + void createWhenSuppliersIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) .withMessageContaining("Suppliers must not be null"); } @Test - public void iteratorShouldReturnPathMappedEndpoints() { + void iteratorShouldReturnPathMappedEndpoints() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped).hasSize(2); assertThat(mapped).extracting("endpointId").containsExactly(EndpointId.of("e2"), EndpointId.of("e3")); } @Test - public void streamShouldReturnPathMappedEndpoints() { + void streamShouldReturnPathMappedEndpoints() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.stream()).hasSize(2); assertThat(mapped.stream()).extracting("endpointId").containsExactly(EndpointId.of("e2"), EndpointId.of("e3")); } @Test - public void getRootPathWhenContainsIdShouldReturnRootPath() { + void getRootPathWhenContainsIdShouldReturnRootPath() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getRootPath(EndpointId.of("e2"))).isEqualTo("p2"); } @Test - public void getRootPathWhenMissingIdShouldReturnNull() { + void getRootPathWhenMissingIdShouldReturnNull() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getRootPath(EndpointId.of("xx"))).isNull(); } @Test - public void getPathWhenContainsIdShouldReturnRootPath() { + void getPathWhenContainsIdShouldReturnRootPath() { assertThat(createTestMapped(null).getPath(EndpointId.of("e2"))).isEqualTo("/p2"); assertThat(createTestMapped("/x").getPath(EndpointId.of("e2"))).isEqualTo("/x/p2"); } @Test - public void getPathWhenMissingIdShouldReturnNull() { + void getPathWhenMissingIdShouldReturnNull() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getPath(EndpointId.of("xx"))).isNull(); } @Test - public void getAllRootPathsShouldReturnAllPaths() { + void getAllRootPathsShouldReturnAllPaths() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getAllRootPaths()).containsExactly("p2", "p3"); } @Test - public void getAllPathsShouldReturnAllPaths() { + void getAllPathsShouldReturnAllPaths() { assertThat(createTestMapped(null).getAllPaths()).containsExactly("/p2", "/p3"); assertThat(createTestMapped("/x").getAllPaths()).containsExactly("/x/p2", "/x/p3"); } @Test - public void getEndpointWhenContainsIdShouldReturnPathMappedEndpoint() { + void getEndpointWhenContainsIdShouldReturnPathMappedEndpoint() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getEndpoint(EndpointId.of("e2")).getRootPath()).isEqualTo("p2"); } @Test - public void getEndpointWhenMissingIdShouldReturnNull() { + void getEndpointWhenMissingIdShouldReturnNull() { PathMappedEndpoints mapped = createTestMapped(null); assertThat(mapped.getEndpoint(EndpointId.of("xx"))).isNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java index 16fde1aa4f4..8651d2a5343 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java @@ -49,7 +49,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Stephane Nicoll */ -public class ServletEndpointRegistrarTests { +class ServletEndpointRegistrarTests { @Mock private ServletContext servletContext; @@ -67,28 +67,28 @@ public class ServletEndpointRegistrarTests { } @Test - public void createWhenServletEndpointsIsNullShouldThrowException() { + void createWhenServletEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null)) .withMessageContaining("ServletEndpoints must not be null"); } @Test - public void onStartupShouldRegisterServlets() throws ServletException { + void onStartupShouldRegisterServlets() throws ServletException { assertBasePath(null, "/test/*"); } @Test - public void onStartupWhenHasBasePathShouldIncludeBasePath() throws ServletException { + void onStartupWhenHasBasePathShouldIncludeBasePath() throws ServletException { assertBasePath("/actuator", "/actuator/test/*"); } @Test - public void onStartupWhenHasEmptyBasePathShouldPrefixWithSlash() throws ServletException { + void onStartupWhenHasEmptyBasePathShouldPrefixWithSlash() throws ServletException { assertBasePath("", "/test/*"); } @Test - public void onStartupWhenHasRootBasePathShouldNotAddDuplicateSlash() throws ServletException { + void onStartupWhenHasRootBasePathShouldNotAddDuplicateSlash() throws ServletException { assertBasePath("/", "/test/*"); } @@ -102,7 +102,7 @@ public class ServletEndpointRegistrarTests { } @Test - public void onStartupWhenHasInitParametersShouldRegisterInitParameters() throws Exception { + void onStartupWhenHasInitParametersShouldRegisterInitParameters() throws Exception { ExposableServletEndpoint endpoint = mockEndpoint( new EndpointServlet(TestServlet.class).withInitParameter("a", "b")); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); @@ -111,7 +111,7 @@ public class ServletEndpointRegistrarTests { } @Test - public void onStartupWhenHasLoadOnStartupShouldRegisterLoadOnStartup() throws Exception { + void onStartupWhenHasLoadOnStartupShouldRegisterLoadOnStartup() throws Exception { ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class).withLoadOnStartup(7)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); @@ -119,7 +119,7 @@ public class ServletEndpointRegistrarTests { } @Test - public void onStartupWhenHasNotLoadOnStartupShouldRegisterDefaultValue() throws Exception { + void onStartupWhenHasNotLoadOnStartupShouldRegisterDefaultValue() throws Exception { ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebEndpointResponseTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebEndpointResponseTests.java index d02b75f7c5a..c6ac235bac4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebEndpointResponseTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebEndpointResponseTests.java @@ -25,31 +25,31 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class WebEndpointResponseTests { +class WebEndpointResponseTests { @Test - public void createWithNoParamsShouldReturn200() { + void createWithNoParamsShouldReturn200() { WebEndpointResponse response = new WebEndpointResponse<>(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getBody()).isNull(); } @Test - public void createWithStatusShouldReturnStatus() { + void createWithStatusShouldReturnStatus() { WebEndpointResponse response = new WebEndpointResponse<>(404); assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getBody()).isNull(); } @Test - public void createWithBodyShouldReturnBody() { + void createWithBodyShouldReturnBody() { WebEndpointResponse response = new WebEndpointResponse<>("body"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getBody()).isEqualTo("body"); } @Test - public void createWithBodyAndStatusShouldReturnStatusAndBody() { + void createWithBodyAndStatusShouldReturnStatusAndBody() { WebEndpointResponse response = new WebEndpointResponse<>("body", 500); assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getBody()).isEqualTo("body"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java index 06a819afa90..a2e0006b1f3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java @@ -27,35 +27,35 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class WebOperationRequestPredicateTests { +class WebOperationRequestPredicateTests { @Test - public void predicatesWithIdenticalPathsAreEqual() { + void predicatesWithIdenticalPathsAreEqual() { assertThat(predicateWithPath("/path")).isEqualTo(predicateWithPath("/path")); } @Test - public void predicatesWithDifferentPathsAreNotEqual() { + void predicatesWithDifferentPathsAreNotEqual() { assertThat(predicateWithPath("/one")).isNotEqualTo(predicateWithPath("/two")); } @Test - public void predicatesWithIdenticalPathsWithVariablesAreEqual() { + void predicatesWithIdenticalPathsWithVariablesAreEqual() { assertThat(predicateWithPath("/path/{foo}")).isEqualTo(predicateWithPath("/path/{foo}")); } @Test - public void predicatesWhereOneHasAPathAndTheOtherHasAVariableAreNotEqual() { + void predicatesWhereOneHasAPathAndTheOtherHasAVariableAreNotEqual() { assertThat(predicateWithPath("/path/{foo}")).isNotEqualTo(predicateWithPath("/path/foo")); } @Test - public void predicatesWithSinglePathVariablesInTheSamplePlaceAreEqual() { + void predicatesWithSinglePathVariablesInTheSamplePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}")).isEqualTo(predicateWithPath("/path/{foo2}")); } @Test - public void predicatesWithMultiplePathVariablesInTheSamplePlaceAreEqual() { + void predicatesWithMultiplePathVariablesInTheSamplePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}/more/{bar1}")) .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java index 7d3fb3b0b20..3d034bfd52f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java @@ -79,31 +79,31 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() .expectBody().jsonPath("All").isEqualTo(true)); } @Test - public void readOperationWithEndpointsMappedToTheRoot() { + void readOperationWithEndpointsMappedToTheRoot() { load(TestEndpointConfiguration.class, "", (client) -> client.get().uri("/test").exchange().expectStatus().isOk() .expectBody().jsonPath("All").isEqualTo(true)); } @Test - public void readOperationWithSelector() { + void readOperationWithSelector() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/one").exchange().expectStatus().isOk() .expectBody().jsonPath("part").isEqualTo("one")); } @Test - public void readOperationWithSelectorContainingADot() { + void readOperationWithSelectorContainingADot() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/foo.bar").exchange().expectStatus() .isOk().expectBody().jsonPath("part").isEqualTo("foo.bar")); } @Test - public void linksToOtherEndpointsAreProvided() { + void linksToOtherEndpointsAreProvided() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("").exchange().expectStatus().isOk().expectBody() .jsonPath("_links.length()").isEqualTo(3).jsonPath("_links.self.href").isNotEmpty() @@ -113,43 +113,43 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("").exchange().expectStatus().isNotFound()); } @Test - public void operationWithTrailingSlashShouldMatch() { + void operationWithTrailingSlashShouldMatch() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/").exchange().expectStatus().isOk() .expectBody().jsonPath("All").isEqualTo(true)); } @Test - public void readOperationWithSingleQueryParameters() { + void readOperationWithSingleQueryParameters() { load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 2")); } @Test - public void readOperationWithSingleQueryParametersAndMultipleValues() { + void readOperationWithSingleQueryParametersAndMultipleValues() { load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&one=1&two=2").exchange() .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1,1 2")); } @Test - public void readOperationWithListQueryParameterAndSingleValue() { + void readOperationWithListQueryParameterAndSingleValue() { load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2]")); } @Test - public void readOperationWithListQueryParameterAndMultipleValues() { + void readOperationWithListQueryParameterAndMultipleValues() { load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2&two=2") .exchange().expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2, 2]")); } @Test - public void readOperationWithMappingFailureProducesBadRequestResponse() { + void readOperationWithMappingFailureProducesBadRequestResponse() { load(QueryEndpointConfiguration.class, (client) -> { WebTestClient.BodyContentSpec body = client.get().uri("/query?two=two").accept(MediaType.APPLICATION_JSON) .exchange().expectStatus().isBadRequest().expectBody(); @@ -158,7 +158,7 @@ public abstract class AbstractWebEndpointIntegrationTests { Map body = new HashMap<>(); body.put("foo", "one"); @@ -168,7 +168,7 @@ public abstract class AbstractWebEndpointIntegrationTests { client.post().uri("/voidwrite").exchange().expectStatus().isNoContent().expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).write(); @@ -176,13 +176,13 @@ public abstract class AbstractWebEndpointIntegrationTests client.delete().uri("/test/one").exchange().expectStatus() .isOk().expectBody().jsonPath("part").isEqualTo("one")); } @Test - public void deleteOperationWithVoidResponse() { + void deleteOperationWithVoidResponse() { load(VoidDeleteResponseEndpointConfiguration.class, (context, client) -> { client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent().expectBody().isEmpty(); verify(context.getBean(EndpointDelegate.class)).delete(); @@ -190,7 +190,7 @@ public abstract class AbstractWebEndpointIntegrationTests { Map body = new HashMap<>(); body.put("foo", "one"); @@ -200,7 +200,7 @@ public abstract class AbstractWebEndpointIntegrationTests { client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent() .expectBody().isEmpty(); @@ -209,25 +209,25 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/nullread").exchange().expectStatus().isNotFound()); } @Test - public void nullResponseFromDeleteOperationResultsInNoContentResponseStatus() { + void nullResponseFromDeleteOperationResultsInNoContentResponseStatus() { load(NullDeleteResponseEndpointConfiguration.class, (context, client) -> client.delete().uri("/nulldelete").exchange().expectStatus().isNoContent()); } @Test - public void nullResponseFromWriteOperationResultsInNoContentResponseStatus() { + void nullResponseFromWriteOperationResultsInNoContentResponseStatus() { load(NullWriteResponseEndpointConfiguration.class, (context, client) -> client.post().uri("/nullwrite").exchange().expectStatus().isNoContent()); } @Test - public void readOperationWithResourceResponse() { + void readOperationWithResourceResponse() { load(ResourceEndpointConfiguration.class, (context, client) -> { byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) @@ -237,7 +237,7 @@ public abstract class AbstractWebEndpointIntegrationTests { byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) @@ -247,19 +247,19 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/mono").exchange().expectStatus() .isOk().expectBody().jsonPath("a").isEqualTo("alpha")); } @Test - public void readOperationWithCustomMediaType() { + void readOperationWithCustomMediaType() { load(CustomMediaTypesEndpointConfiguration.class, (client) -> client.get().uri("/custommediatypes").exchange() .expectStatus().isOk().expectHeader().valueMatches("Content-Type", "text/plain(;charset=.*)?")); } @Test - public void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() { + void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() { load(RequiredParameterEndpointConfiguration.class, (client) -> { WebTestClient.BodyContentSpec body = client.get().uri("/requiredparameters") .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest().expectBody(); @@ -268,44 +268,44 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/requiredparameters?foo=hello").exchange().expectStatus().isOk()); } @Test - public void endpointsProducePrimaryMediaTypeByDefault() { + void endpointsProducePrimaryMediaTypeByDefault() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").exchange().expectStatus().isOk() .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test - public void endpointsProduceSecondaryMediaTypeWhenRequested() { + void endpointsProduceSecondaryMediaTypeWhenRequested() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").accept(MediaType.APPLICATION_JSON) .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test - public void linksProducesPrimaryMediaTypeByDefault() { + void linksProducesPrimaryMediaTypeByDefault() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("").exchange().expectStatus().isOk() .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test - public void linksProducesSecondaryMediaTypeWhenRequested() { + void linksProducesSecondaryMediaTypeWhenRequested() { load(TestEndpointConfiguration.class, (client) -> client.get().uri("").accept(MediaType.APPLICATION_JSON) .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test - public void principalIsNullWhenRequestHasNoPrincipal() { + void principalIsNullWhenRequestHasNoPrincipal() { load(PrincipalEndpointConfiguration.class, (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() .isOk().expectBody(String.class).isEqualTo("None")); } @Test - public void principalIsAvailableWhenRequestHasAPrincipal() { + void principalIsAvailableWhenRequestHasAPrincipal() { load((context) -> { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalEndpointConfiguration.class); @@ -314,7 +314,7 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalQueryEndpointConfiguration.class); @@ -323,14 +323,14 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange() .expectStatus().isOk().expectBody(String.class).isEqualTo("None")); } @Test - public void securityContextIsAvailableAndHasPrincipalWhenRequestHasPrincipal() { + void securityContextIsAvailableAndHasPrincipalWhenRequestHasPrincipal() { load((context) -> { this.authenticatedContextCustomizer.accept(context); context.register(SecurityContextEndpointConfiguration.class); @@ -339,14 +339,14 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); } @Test - public void userInRoleReturnsFalseWhenUserIsNotInRole() { + void userInRoleReturnsFalseWhenUserIsNotInRole() { load((context) -> { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); @@ -355,7 +355,7 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java index 7cab2b4783d..726fdec1443 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java @@ -47,18 +47,18 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Stephane Nicoll */ -public class ControllerEndpointDiscovererTests { +class ControllerEndpointDiscovererTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { + void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test - public void getEndpointsShouldIncludeControllerEndpoints() { + void getEndpointsShouldIncludeControllerEndpoints() { this.contextRunner.withUserConfiguration(TestControllerEndpoint.class).run(assertDiscoverer((discoverer) -> { Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); @@ -70,7 +70,7 @@ public class ControllerEndpointDiscovererTests { } @Test - public void getEndpointsShouldDiscoverProxyControllerEndpoints() { + void getEndpointsShouldDiscoverProxyControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyControllerEndpoint.class) .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { @@ -84,7 +84,7 @@ public class ControllerEndpointDiscovererTests { } @Test - public void getEndpointsShouldIncludeRestControllerEndpoints() { + void getEndpointsShouldIncludeRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestRestControllerEndpoint.class) .run(assertDiscoverer((discoverer) -> { Collection endpoints = discoverer.getEndpoints(); @@ -96,7 +96,7 @@ public class ControllerEndpointDiscovererTests { } @Test - public void getEndpointsShouldDiscoverProxyRestControllerEndpoints() { + void getEndpointsShouldDiscoverProxyRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyRestControllerEndpoint.class) .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { @@ -110,7 +110,7 @@ public class ControllerEndpointDiscovererTests { } @Test - public void getEndpointsShouldNotDiscoverRegularEndpoints() { + void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) .run(assertDiscoverer((discoverer) -> { Collection endpoints = discoverer.getEndpoints(); @@ -121,7 +121,7 @@ public class ControllerEndpointDiscovererTests { } @Test - public void getEndpointWhenEndpointHasOperationsShouldThrowException() { + void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(discoverer::getEndpoints) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java index ac359db7325..515ae926e3a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java @@ -56,18 +56,18 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Stephane Nicoll */ -public class ServletEndpointDiscovererTests { +class ServletEndpointDiscovererTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { + void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test - public void getEndpointsShouldIncludeServletEndpoints() { + void getEndpointsShouldIncludeServletEndpoints() { this.contextRunner.withUserConfiguration(TestServletEndpoint.class).run(assertDiscoverer((discoverer) -> { Collection endpoints = discoverer.getEndpoints(); assertThat(endpoints).hasSize(1); @@ -79,7 +79,7 @@ public class ServletEndpointDiscovererTests { } @Test - public void getEndpointsShouldDiscoverProxyServletEndpoints() { + void getEndpointsShouldDiscoverProxyServletEndpoints() { this.contextRunner.withUserConfiguration(TestProxyServletEndpoint.class) .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run(assertDiscoverer((discoverer) -> { @@ -93,7 +93,7 @@ public class ServletEndpointDiscovererTests { } @Test - public void getEndpointsShouldNotDiscoverRegularEndpoints() { + void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) .run(assertDiscoverer((discoverer) -> { Collection endpoints = discoverer.getEndpoints(); @@ -104,7 +104,7 @@ public class ServletEndpointDiscovererTests { } @Test - public void getEndpointWhenEndpointHasOperationsShouldThrowException() { + void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(discoverer::getEndpoints) @@ -112,21 +112,21 @@ public class ServletEndpointDiscovererTests { } @Test - public void getEndpointWhenEndpointNotASupplierShouldThrowException() { + void getEndpointWhenEndpointNotASupplierShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointNotASupplier.class) .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(discoverer::getEndpoints).withMessageContaining("must be a supplier"))); } @Test - public void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { + void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(discoverer::getEndpoints).withMessageContaining("must supply an EndpointServlet"))); } @Test - public void getEndpointWhenEndpointSuppliesNullShouldThrowException() { + void getEndpointWhenEndpointSuppliesNullShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfNull.class) .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(discoverer::getEndpoints).withMessageContaining("must not supply null"))); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java index 8f5a0c4545f..da985443bea 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java @@ -66,15 +66,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Stephane Nicoll * @author Phillip Webb */ -public class WebEndpointDiscovererTests { +class WebEndpointDiscovererTests { @Test - public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { + void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { load(EmptyConfiguration.class, (discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty()); } @Test - public void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { + void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { load(TestWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining( @@ -82,7 +82,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverWebEndpoints() { + void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverWebEndpoints() { load(MultipleEndpointsConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -90,7 +90,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasWebExtensionShouldOverrideStandardEndpoint() { + void getEndpointsWhenHasWebExtensionShouldOverrideStandardEndpoint() { load(OverriddenOperationWebEndpointExtensionConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -101,7 +101,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenExtensionAddsOperationShouldHaveBothOperations() { + void getEndpointsWhenExtensionAddsOperationShouldHaveBothOperations() { load(AdditionalOperationWebEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -113,7 +113,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenPredicateForWriteOperationThatReturnsVoidShouldHaveNoProducedMediaTypes() { + void getEndpointsWhenPredicateForWriteOperationThatReturnsVoidShouldHaveNoProducedMediaTypes() { load(VoidWriteOperationEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("voidwrite")); @@ -124,7 +124,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { + void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingWebEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Found multiple extensions for the endpoint bean " @@ -132,14 +132,14 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { + void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test - public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { + void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Unable to map duplicate endpoint operations: " @@ -148,7 +148,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { + void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidWebExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " @@ -156,7 +156,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { + void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingSelectorsWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) .withMessageContaining("Unable to map duplicate endpoint operations") @@ -164,7 +164,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { + void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { load((id) -> 500L, EndpointId::toString, TestEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); @@ -178,7 +178,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenOperationReturnsResourceShouldProduceApplicationOctetStream() { + void getEndpointsWhenOperationReturnsResourceShouldProduceApplicationOctetStream() { load(ResourceEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("resource")); @@ -189,7 +189,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasCustomMediaTypeShouldProduceCustomMediaType() { + void getEndpointsWhenHasCustomMediaTypeShouldProduceCustomMediaType() { load(CustomMediaTypesEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("custommediatypes")); @@ -203,7 +203,7 @@ public class WebEndpointDiscovererTests { } @Test - public void getEndpointsWhenHasCustomPathShouldReturnCustomPath() { + void getEndpointsWhenHasCustomPathShouldReturnCustomPath() { load((id) -> null, (id) -> "custom/" + id, AdditionalOperationWebEndpointConfiguration.class, (discoverer) -> { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java index be6b93444cb..3c7c04aee4e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java @@ -58,27 +58,27 @@ import org.springframework.web.util.DefaultUriBuilderFactory; * @author Phillip Webb * @author Stephane Nicoll */ -public class ControllerEndpointHandlerMappingIntegrationTests { +class ControllerEndpointHandlerMappingIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, ExampleWebFluxEndpoint.class); @Test - public void get() { + void get() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); } @Test - public void getWithUnacceptableContentType() { + void getWithUnacceptableContentType() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test - public void post() { + void post() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") .syncBody(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() .valueEquals(HttpHeaders.LOCATION, "/example/test"))); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java index 841c75ac1d6..3b218cacadb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java @@ -46,12 +46,12 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Stephane Nicoll */ -public class ControllerEndpointHandlerMappingTests { +class ControllerEndpointHandlerMappingTests { private final StaticApplicationContext context = new StaticApplicationContext(); @Test - public void mappingWithNoPrefix() throws Exception { + void mappingWithNoPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("", first, second); @@ -62,7 +62,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingWithPrefix() throws Exception { + void mappingWithPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); @@ -75,7 +75,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingWithNoPath() throws Exception { + void mappingWithNoPath() throws Exception { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/pathless")) @@ -85,7 +85,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingNarrowedToMethod() throws Exception { + void mappingNarrowedToMethod() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(MethodNotAllowedException.class) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java index f493387a6a8..685145a68c0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java @@ -54,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @see WebFluxEndpointHandlerMapping */ -public class WebFluxEndpointIntegrationTests +class WebFluxEndpointIntegrationTests extends AbstractWebEndpointIntegrationTests { public WebFluxEndpointIntegrationTests() { @@ -74,7 +74,7 @@ public class WebFluxEndpointIntegrationTests } @Test - public void responseToOptionsRequestIncludesCorsHeaders() { + void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") @@ -84,7 +84,7 @@ public class WebFluxEndpointIntegrationTests } @Test - public void readOperationsThatReturnAResourceSupportRangeRequests() { + void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java index 3206c09a7af..6a87ab9e179 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java @@ -57,27 +57,27 @@ import org.springframework.web.util.DefaultUriBuilderFactory; * @author Phillip Webb * @author Stephane Nicoll */ -public class ControllerEndpointHandlerMappingIntegrationTests { +class ControllerEndpointHandlerMappingIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, ExampleMvcEndpoint.class); @Test - public void get() { + void get() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); } @Test - public void getWithUnacceptableContentType() { + void getWithUnacceptableContentType() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test - public void post() { + void post() { this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") .syncBody(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() .valueEquals(HttpHeaders.LOCATION, "/example/test"))); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java index 0a370439cd3..41462ceca4c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java @@ -43,12 +43,12 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Stephane Nicoll */ -public class ControllerEndpointHandlerMappingTests { +class ControllerEndpointHandlerMappingTests { private final StaticApplicationContext context = new StaticApplicationContext(); @Test - public void mappingWithNoPrefix() throws Exception { + void mappingWithNoPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("", first, second); @@ -60,7 +60,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingWithPrefix() throws Exception { + void mappingWithPrefix() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); @@ -73,7 +73,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingNarrowedToMethod() throws Exception { + void mappingNarrowedToMethod() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class) @@ -81,7 +81,7 @@ public class ControllerEndpointHandlerMappingTests { } @Test - public void mappingWithNoPath() throws Exception { + void mappingWithNoPath() throws Exception { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(mapping.getHandler(request("GET", "/actuator/pathless")).getHandler()) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java index 21f24e2dce4..cbf49e69963 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java @@ -64,7 +64,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @see WebMvcEndpointHandlerMapping */ -public class MvcWebEndpointIntegrationTests +class MvcWebEndpointIntegrationTests extends AbstractWebEndpointIntegrationTests { public MvcWebEndpointIntegrationTests() { @@ -83,7 +83,7 @@ public class MvcWebEndpointIntegrationTests } @Test - public void responseToOptionsRequestIncludesCorsHeaders() { + void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") @@ -93,7 +93,7 @@ public class MvcWebEndpointIntegrationTests } @Test - public void readOperationsThatReturnAResourceSupportRangeRequests() { + void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() @@ -104,12 +104,12 @@ public class MvcWebEndpointIntegrationTests } @Test - public void matchWhenRequestHasTrailingSlashShouldNotBeNull() { + void matchWhenRequestHasTrailingSlashShouldNotBeNull() { assertThat(getMatchResult("/spring/")).isNotNull(); } @Test - public void matchWhenRequestHasSuffixShouldBeNull() { + void matchWhenRequestHasSuffixShouldBeNull() { assertThat(getMatchResult("/spring.do")).isNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java index fe1c40c6a9e..4125ca31c8a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcTagsTests.java @@ -34,14 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel * @author Michael McFadyen */ -public class WebMvcTagsTests { +class WebMvcTagsTests { private final MockHttpServletRequest request = new MockHttpServletRequest(); private final MockHttpServletResponse response = new MockHttpServletResponse(); @Test - public void uriTagIsDataRestsEffectiveRepositoryLookupPathWhenAvailable() { + void uriTagIsDataRestsEffectiveRepositoryLookupPathWhenAvailable() { this.request.setAttribute( "org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping.EFFECTIVE_REPOSITORY_RESOURCE_LOOKUP_PATH", new PathPatternParser().parse("/api/cities")); @@ -51,7 +51,7 @@ public class WebMvcTagsTests { } @Test - public void uriTagValueIsBestMatchingPatternWhenAvailable() { + void uriTagValueIsBestMatchingPatternWhenAvailable() { this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/spring"); this.response.setStatus(301); Tag tag = WebMvcTags.uri(this.request, this.response); @@ -59,85 +59,85 @@ public class WebMvcTagsTests { } @Test - public void uriTagValueIsRootWhenRequestHasNoPatternOrPathInfo() { + void uriTagValueIsRootWhenRequestHasNoPatternOrPathInfo() { assertThat(WebMvcTags.uri(this.request, null).getValue()).isEqualTo("root"); } @Test - public void uriTagValueIsRootWhenRequestHasNoPatternAndSlashPathInfo() { + void uriTagValueIsRootWhenRequestHasNoPatternAndSlashPathInfo() { this.request.setPathInfo("/"); assertThat(WebMvcTags.uri(this.request, null).getValue()).isEqualTo("root"); } @Test - public void uriTagValueIsUnknownWhenRequestHasNoPatternAndNonRootPathInfo() { + void uriTagValueIsUnknownWhenRequestHasNoPatternAndNonRootPathInfo() { this.request.setPathInfo("/example"); assertThat(WebMvcTags.uri(this.request, null).getValue()).isEqualTo("UNKNOWN"); } @Test - public void uriTagValueIsRedirectionWhenResponseStatusIs3xx() { + void uriTagValueIsRedirectionWhenResponseStatusIs3xx() { this.response.setStatus(301); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void uriTagValueIsNotFoundWhenResponseStatusIs404() { + void uriTagValueIsNotFoundWhenResponseStatusIs404() { this.response.setStatus(404); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("NOT_FOUND"); } @Test - public void uriTagToleratesCustomResponseStatus() { + void uriTagToleratesCustomResponseStatus() { this.response.setStatus(601); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("root"); } @Test - public void uriTagIsUnknownWhenRequestIsNull() { + void uriTagIsUnknownWhenRequestIsNull() { Tag tag = WebMvcTags.uri(null, null); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); } @Test - public void outcomeTagIsUnknownWhenResponseIsNull() { + void outcomeTagIsUnknownWhenResponseIsNull() { Tag tag = WebMvcTags.outcome(null); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); } @Test - public void outcomeTagIsInformationalWhenResponseIs1xx() { + void outcomeTagIsInformationalWhenResponseIs1xx() { this.response.setStatus(100); Tag tag = WebMvcTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("INFORMATIONAL"); } @Test - public void outcomeTagIsSuccessWhenResponseIs2xx() { + void outcomeTagIsSuccessWhenResponseIs2xx() { this.response.setStatus(200); Tag tag = WebMvcTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("SUCCESS"); } @Test - public void outcomeTagIsRedirectionWhenResponseIs3xx() { + void outcomeTagIsRedirectionWhenResponseIs3xx() { this.response.setStatus(301); Tag tag = WebMvcTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void outcomeTagIsClientErrorWhenResponseIs4xx() { + void outcomeTagIsClientErrorWhenResponseIs4xx() { this.response.setStatus(400); Tag tag = WebMvcTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("CLIENT_ERROR"); } @Test - public void outcomeTagIsServerErrorWhenResponseIs5xx() { + void outcomeTagIsServerErrorWhenResponseIs5xx() { this.response.setStatus(500); Tag tag = WebMvcTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("SERVER_ERROR"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java deleted file mode 100644 index 2d9b2f5deef..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/AbstractWebEndpointRunner.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.endpoint.web.test; - -import java.lang.reflect.Modifier; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.MergedAnnotations; -import org.springframework.core.annotation.MergedAnnotations.SearchStrategy; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySource; -import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.util.DefaultUriBuilderFactory; -import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode; - -/** - * Base class for web endpoint runners. - * - * @author Andy Wilkinson - * @author Phillip Webb - */ -abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { - - private static final Duration TIMEOUT = Duration.ofMinutes(6); - - private final String name; - - private final TestContext testContext; - - protected AbstractWebEndpointRunner(Class testClass, String name, ContextFactory contextFactory) - throws InitializationError { - super(testClass); - this.name = name; - this.testContext = new TestContext(testClass, contextFactory); - } - - @Override - protected final String getName() { - return this.name; - } - - @Override - protected String testName(FrameworkMethod method) { - return super.testName(method) + "[" + getName() + "]"; - } - - @Override - protected Statement withBeforeClasses(Statement statement) { - Statement delegate = super.withBeforeClasses(statement); - return new Statement() { - - @Override - public void evaluate() throws Throwable { - AbstractWebEndpointRunner.this.testContext.beforeClass(); - delegate.evaluate(); - } - - }; - } - - @Override - protected Statement withAfterClasses(Statement statement) { - Statement delegate = super.withAfterClasses(statement); - return new Statement() { - - @Override - public void evaluate() throws Throwable { - try { - delegate.evaluate(); - } - finally { - AbstractWebEndpointRunner.this.testContext.afterClass(); - } - } - - }; - } - - @Override - protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { - Statement delegate = super.withBefores(method, target, statement); - return new Statement() { - - @Override - public void evaluate() throws Throwable { - AbstractWebEndpointRunner.this.testContext.beforeTest(); - delegate.evaluate(); - } - - }; - } - - @Override - protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { - Statement delegate = super.withAfters(method, target, statement); - return new Statement() { - - @Override - public void evaluate() throws Throwable { - try { - delegate.evaluate(); - } - finally { - AbstractWebEndpointRunner.this.testContext.afterTest(); - } - } - - }; - } - - final class TestContext { - - private final Class testClass; - - private final ContextFactory contextFactory; - - private ConfigurableApplicationContext applicationContext; - - private List> propertySources; - - TestContext(Class testClass, ContextFactory contextFactory) { - this.testClass = testClass; - this.contextFactory = contextFactory; - } - - void beforeClass() { - this.applicationContext = createApplicationContext(); - WebTestClient webTestClient = createWebTestClient(); - injectIfPossible(this.testClass, webTestClient); - injectIfPossible(this.testClass, this.applicationContext); - } - - void beforeTest() { - capturePropertySources(); - } - - void afterTest() { - restorePropertySources(); - } - - void afterClass() { - if (this.applicationContext != null) { - this.applicationContext.close(); - } - } - - private ConfigurableApplicationContext createApplicationContext() { - Class[] members = this.testClass.getDeclaredClasses(); - List> configurationClasses = Stream.of(members).filter(this::isConfiguration) - .collect(Collectors.toList()); - return this.contextFactory.createContext(new ArrayList<>(configurationClasses)); - } - - private boolean isConfiguration(Class candidate) { - return MergedAnnotations.from(candidate, SearchStrategy.EXHAUSTIVE).isPresent(Configuration.class); - } - - private WebTestClient createWebTestClient() { - DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( - "http://localhost:" + determinePort()); - uriBuilderFactory.setEncodingMode(EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(TIMEOUT).build(); - } - - private int determinePort() { - if (this.applicationContext instanceof AnnotationConfigServletWebServerApplicationContext) { - return ((AnnotationConfigServletWebServerApplicationContext) this.applicationContext).getWebServer() - .getPort(); - } - return this.applicationContext.getBean(PortHolder.class).getPort(); - } - - private void injectIfPossible(Class target, Object value) { - ReflectionUtils.doWithFields(target, (field) -> { - if (Modifier.isStatic(field.getModifiers()) && field.getType().isInstance(value)) { - ReflectionUtils.makeAccessible(field); - ReflectionUtils.setField(field, null, value); - } - }); - } - - private void capturePropertySources() { - this.propertySources = new ArrayList<>(); - this.applicationContext.getEnvironment().getPropertySources().forEach(this.propertySources::add); - } - - private void restorePropertySources() { - List names = new ArrayList<>(); - MutablePropertySources propertySources = this.applicationContext.getEnvironment().getPropertySources(); - propertySources.forEach((propertySource) -> names.add(propertySource.getName())); - names.forEach(propertySources::remove); - this.propertySources.forEach(propertySources::addLast); - } - - } - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java deleted file mode 100644 index 7f8e7d398fa..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/JerseyEndpointsRunner.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.endpoint.web.test; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import javax.ws.rs.core.MediaType; - -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.server.model.Resource; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; - -import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType; -import org.springframework.boot.actuate.endpoint.invoke.convert.ConversionServiceParameterValueMapper; -import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver; -import org.springframework.boot.actuate.endpoint.web.EndpointMapping; -import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes; -import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpointDiscoverer; -import org.springframework.boot.actuate.endpoint.web.jersey.JerseyEndpointResourceFactory; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration; -import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer; -import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ClassUtils; - -/** - * {@link BlockJUnit4ClassRunner} for Jersey. - * - * @author Andy Wilkinson - * @author Phillip Webb - */ -class JerseyEndpointsRunner extends AbstractWebEndpointRunner { - - JerseyEndpointsRunner(Class testClass) throws InitializationError { - super(testClass, "Jersey", JerseyEndpointsRunner::createContext); - } - - private static ConfigurableApplicationContext createContext(List> classes) { - AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); - classes.add(JerseyEndpointConfiguration.class); - context.register(ClassUtils.toClassArray(classes)); - context.refresh(); - return context; - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, JerseyAutoConfiguration.class }) - static class JerseyEndpointConfiguration { - - private final ApplicationContext applicationContext; - - JerseyEndpointConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - public TomcatServletWebServerFactory tomcat() { - return new TomcatServletWebServerFactory(0); - } - - @Bean - public ResourceConfig resourceConfig() { - return new ResourceConfig(); - } - - @Bean - public ResourceConfigCustomizer webEndpointRegistrar() { - return this::customize; - } - - private void customize(ResourceConfig config) { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON, ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, - new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); - Collection resources = new JerseyEndpointResourceFactory().createEndpointResources( - new EndpointMapping("/actuator"), discoverer.getEndpoints(), endpointMediaTypes, - new EndpointLinksResolver(discoverer.getEndpoints())); - config.registerResources(new HashSet<>(resources)); - } - - } - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java deleted file mode 100644 index 88ce60914a2..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointRunners.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.endpoint.web.test; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.runner.Runner; -import org.junit.runners.Suite; -import org.junit.runners.model.InitializationError; - -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.PropertySource; -import org.springframework.test.web.reactive.server.WebTestClient; - -/** - * A custom {@link Runner} that tests web endpoints that are made available over HTTP - * using Jersey, Spring MVC, and WebFlux. - *

- * The following types can be automatically injected into static fields on the test class: - *

    - *
  • {@link WebTestClient}
  • - *
  • {@link ConfigurableApplicationContext}
  • - *
- *

- * The {@link PropertySource PropertySources} that belong to the application context's - * {@link org.springframework.core.env.Environment} are reset at the end of every test. - * This means that {@link TestPropertyValues} can be used in a test without affecting the - * {@code Environment} of other tests in the same class. The runner always sets the flag - * {@code management.endpoints.web.exposure.include} to {@code *} so that web endpoints - * are enabled. - * - * @author Andy Wilkinson - * @author Phillip Webb - */ -public class WebEndpointRunners extends Suite { - - public WebEndpointRunners(Class testClass) throws InitializationError { - super(testClass, createRunners(testClass)); - } - - private static List createRunners(Class testClass) throws InitializationError { - List runners = new ArrayList<>(); - runners.add(new WebFluxEndpointsRunner(testClass)); - runners.add(new WebMvcEndpointRunner(testClass)); - runners.add(new JerseyEndpointsRunner(testClass)); - return runners; - } - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/ContextFactory.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTest.java similarity index 50% rename from spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/ContextFactory.java rename to spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTest.java index 7337969b545..395fd4de9ad 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/ContextFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,24 @@ package org.springframework.boot.actuate.endpoint.web.test; -import java.util.List; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; -import org.springframework.context.ConfigurableApplicationContext; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; /** - * @author Phillip Webb + * Signals that a test should be performed against all web endpoint implementations + * (Jersey, Web MVC, and WebFlux) + * + * @author Andy Wilkinson */ -@FunctionalInterface -interface ContextFactory { - - ConfigurableApplicationContext createContext(List> configurationClasses); +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@TestTemplate +@ExtendWith(WebEndpointTestInvocationContextProvider.class) +public @interface WebEndpointTest { } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java new file mode 100644 index 00000000000..5589d9c6518 --- /dev/null +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java @@ -0,0 +1,325 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.actuate.endpoint.web.test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.server.model.Resource; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestTemplateInvocationContext; +import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; + +import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType; +import org.springframework.boot.actuate.endpoint.invoke.convert.ConversionServiceParameterValueMapper; +import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver; +import org.springframework.boot.actuate.endpoint.web.EndpointMapping; +import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes; +import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpointDiscoverer; +import org.springframework.boot.actuate.endpoint.web.jersey.JerseyEndpointResourceFactory; +import org.springframework.boot.actuate.endpoint.web.reactive.WebFluxEndpointHandlerMapping; +import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration; +import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer; +import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.boot.web.context.WebServerInitializedEvent; +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext; +import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigRegistry; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.core.annotation.MergedAnnotations.SearchStrategy; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.util.ClassUtils; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; +import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode; + +/** + * {@link TestTemplateInvocationContextProvider} for + * {@link WebEndpointTest @WebEndpointTest}. + * + * @author Andy Wilkinson + */ +class WebEndpointTestInvocationContextProvider implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext context) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts( + ExtensionContext extensionContext) { + return Stream.of( + new WebEndpointsInvocationContext("Jersey", + WebEndpointTestInvocationContextProvider::createJerseyContext), + new WebEndpointsInvocationContext("WebMvc", + WebEndpointTestInvocationContextProvider::createWebMvcContext), + new WebEndpointsInvocationContext("WebFlux", + WebEndpointTestInvocationContextProvider::createWebFluxContext)); + } + + private static ConfigurableApplicationContext createJerseyContext(List> classes) { + AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); + classes.add(JerseyEndpointConfiguration.class); + context.register(ClassUtils.toClassArray(classes)); + context.refresh(); + return context; + } + + private static ConfigurableApplicationContext createWebMvcContext(List> classes) { + AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); + classes.add(WebMvcEndpointConfiguration.class); + context.register(ClassUtils.toClassArray(classes)); + context.refresh(); + return context; + } + + private static ConfigurableApplicationContext createWebFluxContext(List> classes) { + AnnotationConfigReactiveWebServerApplicationContext context = new AnnotationConfigReactiveWebServerApplicationContext(); + classes.add(WebFluxEndpointConfiguration.class); + context.register(ClassUtils.toClassArray(classes)); + context.refresh(); + return context; + + } + + private static class WebEndpointsInvocationContext + implements TestTemplateInvocationContext, BeforeEachCallback, AfterEachCallback, ParameterResolver { + + private static final Duration TIMEOUT = Duration.ofMinutes(6); + + private final String name; + + private final Function>, ConfigurableApplicationContext> contextFactory; + + private ConfigurableApplicationContext context; + + WebEndpointsInvocationContext(String name, + Function>, ConfigurableApplicationContext> contextFactory) { + this.name = name; + this.contextFactory = contextFactory; + } + + @Override + public void beforeEach(ExtensionContext extensionContext) throws Exception { + List> configurationClasses = Stream + .of(extensionContext.getRequiredTestClass().getDeclaredClasses()).filter(this::isConfiguration) + .collect(Collectors.toList()); + this.context = this.contextFactory.apply(configurationClasses); + } + + private boolean isConfiguration(Class candidate) { + return MergedAnnotations.from(candidate, SearchStrategy.EXHAUSTIVE).isPresent(Configuration.class); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + if (this.context != null) { + this.context.close(); + } + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Class type = parameterContext.getParameter().getType(); + return type.equals(WebTestClient.class) || type.isAssignableFrom(ConfigurableApplicationContext.class); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Class type = parameterContext.getParameter().getType(); + if (type.equals(WebTestClient.class)) { + return createWebTestClient(); + } + else { + return this.context; + } + } + + @Override + public List getAdditionalExtensions() { + return Collections.singletonList(this); + } + + @Override + public String getDisplayName(int invocationIndex) { + return this.name; + } + + private WebTestClient createWebTestClient() { + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( + "http://localhost:" + determinePort()); + uriBuilderFactory.setEncodingMode(EncodingMode.NONE); + return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(TIMEOUT).build(); + } + + private int determinePort() { + if (this.context instanceof AnnotationConfigServletWebServerApplicationContext) { + return ((AnnotationConfigServletWebServerApplicationContext) this.context).getWebServer().getPort(); + } + return this.context.getBean(PortHolder.class).getPort(); + } + + } + + @Configuration(proxyBeanMethods = false) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, JerseyAutoConfiguration.class }) + static class JerseyEndpointConfiguration { + + private final ApplicationContext applicationContext; + + JerseyEndpointConfiguration(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + public TomcatServletWebServerFactory tomcat() { + return new TomcatServletWebServerFactory(0); + } + + @Bean + public ResourceConfig resourceConfig() { + return new ResourceConfig(); + } + + @Bean + public ResourceConfigCustomizer webEndpointRegistrar() { + return this::customize; + } + + private void customize(ResourceConfig config) { + List mediaTypes = Arrays.asList(javax.ws.rs.core.MediaType.APPLICATION_JSON, + ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), + Collections.emptyList()); + Collection resources = new JerseyEndpointResourceFactory().createEndpointResources( + new EndpointMapping("/actuator"), discoverer.getEndpoints(), endpointMediaTypes, + new EndpointLinksResolver(discoverer.getEndpoints())); + config.registerResources(new HashSet<>(resources)); + } + + } + + @Configuration(proxyBeanMethods = false) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, WebFluxAutoConfiguration.class }) + static class WebFluxEndpointConfiguration implements ApplicationListener { + + private final ApplicationContext applicationContext; + + private final PortHolder portHolder = new PortHolder(); + + WebFluxEndpointConfiguration(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + public NettyReactiveWebServerFactory netty() { + return new NettyReactiveWebServerFactory(0); + } + + @Bean + public PortHolder portHolder() { + return this.portHolder; + } + + @Override + public void onApplicationEvent(WebServerInitializedEvent event) { + this.portHolder.setPort(event.getWebServer().getPort()); + } + + @Bean + public HttpHandler httpHandler(ApplicationContext applicationContext) { + return WebHttpHandlerBuilder.applicationContext(applicationContext).build(); + } + + @Bean + public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping() { + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), + Collections.emptyList()); + return new WebFluxEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), + endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); + } + + } + + @Configuration(proxyBeanMethods = false) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) + static class WebMvcEndpointConfiguration { + + private final ApplicationContext applicationContext; + + WebMvcEndpointConfiguration(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + @Bean + public TomcatServletWebServerFactory tomcat() { + return new TomcatServletWebServerFactory(0); + } + + @Bean + public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping() { + List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), + Collections.emptyList()); + return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), + endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); + } + + } + +} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java deleted file mode 100644 index 9c5a17633f2..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebFluxEndpointsRunner.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.endpoint.web.test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; - -import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType; -import org.springframework.boot.actuate.endpoint.invoke.convert.ConversionServiceParameterValueMapper; -import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver; -import org.springframework.boot.actuate.endpoint.web.EndpointMapping; -import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes; -import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpointDiscoverer; -import org.springframework.boot.actuate.endpoint.web.reactive.WebFluxEndpointHandlerMapping; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; -import org.springframework.boot.web.context.WebServerInitializedEvent; -import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; -import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.util.ClassUtils; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.server.adapter.WebHttpHandlerBuilder; - -/** - * {@link BlockJUnit4ClassRunner} for Spring WebFlux. - * - * @author Andy Wilkinson - * @author Phillip Webb - */ -class WebFluxEndpointsRunner extends AbstractWebEndpointRunner { - - WebFluxEndpointsRunner(Class testClass) throws InitializationError { - super(testClass, "Reactive", WebFluxEndpointsRunner::createContext); - } - - private static ConfigurableApplicationContext createContext(List> classes) { - AnnotationConfigReactiveWebServerApplicationContext context = new AnnotationConfigReactiveWebServerApplicationContext(); - classes.add(WebFluxEndpointConfiguration.class); - context.register(ClassUtils.toClassArray(classes)); - context.refresh(); - return context; - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, WebFluxAutoConfiguration.class }) - static class WebFluxEndpointConfiguration implements ApplicationListener { - - private final ApplicationContext applicationContext; - - private final PortHolder portHolder = new PortHolder(); - - WebFluxEndpointConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - public NettyReactiveWebServerFactory netty() { - return new NettyReactiveWebServerFactory(0); - } - - @Bean - public PortHolder portHolder() { - return this.portHolder; - } - - @Override - public void onApplicationEvent(WebServerInitializedEvent event) { - this.portHolder.setPort(event.getWebServer().getPort()); - } - - @Bean - public HttpHandler httpHandler(ApplicationContext applicationContext) { - return WebHttpHandlerBuilder.applicationContext(applicationContext).build(); - } - - @Bean - public WebFluxEndpointHandlerMapping webEndpointReactiveHandlerMapping() { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, - new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); - return new WebFluxEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), - endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); - } - - } - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java deleted file mode 100644 index 947bcb4116a..00000000000 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebMvcEndpointRunner.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.endpoint.web.test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; - -import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType; -import org.springframework.boot.actuate.endpoint.invoke.convert.ConversionServiceParameterValueMapper; -import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver; -import org.springframework.boot.actuate.endpoint.web.EndpointMapping; -import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes; -import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpointDiscoverer; -import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; -import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; -import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.util.ClassUtils; -import org.springframework.web.cors.CorsConfiguration; - -/** - * {@link BlockJUnit4ClassRunner} for Spring MVC. - * - * @author Andy Wilkinson - * @author Phillip Webb - */ -class WebMvcEndpointRunner extends AbstractWebEndpointRunner { - - WebMvcEndpointRunner(Class testClass) throws InitializationError { - super(testClass, "Spring MVC", WebMvcEndpointRunner::createContext); - } - - private static ConfigurableApplicationContext createContext(List> classes) { - AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); - classes.add(WebMvcEndpointConfiguration.class); - context.register(ClassUtils.toClassArray(classes)); - context.refresh(); - return context; - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) - static class WebMvcEndpointConfiguration { - - private final ApplicationContext applicationContext; - - WebMvcEndpointConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean - public TomcatServletWebServerFactory tomcat() { - return new TomcatServletWebServerFactory(0); - } - - @Bean - public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping() { - List mediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_VALUE, ActuatorMediaType.V2_JSON); - EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); - WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, - new ConversionServiceParameterValueMapper(), endpointMediaTypes, null, Collections.emptyList(), - Collections.emptyList()); - return new WebMvcEndpointHandlerMapping(new EndpointMapping("/actuator"), discoverer.getEndpoints(), - endpointMediaTypes, new CorsConfiguration(), new EndpointLinksResolver(discoverer.getEndpoints())); - } - - } - -} diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java index 7a891e65545..9117649fb03 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Andy Wilkinson */ -public class EnvironmentEndpointTests { +class EnvironmentEndpointTests { @AfterEach public void close() { @@ -58,7 +58,7 @@ public class EnvironmentEndpointTests { } @Test - public void basicResponse() { + void basicResponse() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources().addLast(singleKeyPropertySource("one", "my.key", "first")); environment.getPropertySources().addLast(singleKeyPropertySource("two", "my.key", "second")); @@ -71,7 +71,7 @@ public class EnvironmentEndpointTests { } @Test - public void compositeSourceIsHandledCorrectly() { + void compositeSourceIsHandledCorrectly() { ConfigurableEnvironment environment = emptyEnvironment(); CompositePropertySource source = new CompositePropertySource("composite"); source.addPropertySource(new MapPropertySource("one", Collections.singletonMap("foo", "bar"))); @@ -85,7 +85,7 @@ public class EnvironmentEndpointTests { } @Test - public void sensitiveKeysHaveTheirValuesSanitized() { + void sensitiveKeysHaveTheirValuesSanitized() { TestPropertyValues.of("dbPassword=123456", "apiKey=123456", "mySecret=123456", "myCredentials=123456", "VCAP_SERVICES=123456").applyToSystemProperties(() -> { EnvironmentDescriptor descriptor = new EnvironmentEndpoint(new StandardEnvironment()) @@ -106,7 +106,7 @@ public class EnvironmentEndpointTests { } @Test - public void sensitiveKeysMatchingCredentialsPatternHaveTheirValuesSanitized() { + void sensitiveKeysMatchingCredentialsPatternHaveTheirValuesSanitized() { TestPropertyValues .of("my.services.amqp-free.credentials.uri=123456", "credentials.http_api_uri=123456", "my.services.cleardb-free.credentials=123456", "foo.mycredentials.uri=123456") @@ -126,7 +126,7 @@ public class EnvironmentEndpointTests { } @Test - public void sensitiveKeysMatchingCustomNameHaveTheirValuesSanitized() { + void sensitiveKeysMatchingCustomNameHaveTheirValuesSanitized() { TestPropertyValues.of("dbPassword=123456", "apiKey=123456").applyToSystemProperties(() -> { EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment()); endpoint.setKeysToSanitize("key"); @@ -140,7 +140,7 @@ public class EnvironmentEndpointTests { } @Test - public void sensitiveKeysMatchingCustomPatternHaveTheirValuesSanitized() { + void sensitiveKeysMatchingCustomPatternHaveTheirValuesSanitized() { TestPropertyValues.of("dbPassword=123456", "apiKey=123456").applyToSystemProperties(() -> { EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment()); endpoint.setKeysToSanitize(".*pass.*"); @@ -154,7 +154,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyWithPlaceholderResolved() { + void propertyWithPlaceholderResolved() { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: ${bar.blah}", "bar.blah: hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); @@ -162,7 +162,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyWithPlaceholderNotResolved() { + void propertyWithPlaceholderNotResolved() { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: ${bar.blah}").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); @@ -171,7 +171,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyWithSensitivePlaceholderResolved() { + void propertyWithSensitivePlaceholderResolved() { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: http://${bar.password}://hello", "bar.password: hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); @@ -180,7 +180,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyWithSensitivePlaceholderNotResolved() { + void propertyWithSensitivePlaceholderNotResolved() { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: http://${bar.password}://hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment).environment(null); @@ -190,7 +190,7 @@ public class EnvironmentEndpointTests { @Test @SuppressWarnings("unchecked") - public void propertyWithTypeOtherThanStringShouldNotFail() { + void propertyWithTypeOtherThanStringShouldNotFail() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources() .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); @@ -201,7 +201,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyEntry() { + void propertyEntry() { TestPropertyValues.of("my.foo=another").applyToSystemProperties(() -> { StandardEnvironment environment = new StandardEnvironment(); TestPropertyValues.of("my.foo=bar", "my.foo2=bar2").applyTo(environment, TestPropertyValues.Type.MAP, @@ -221,7 +221,7 @@ public class EnvironmentEndpointTests { } @Test - public void propertyEntryNotFound() { + void propertyEntryNotFound() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources().addFirst(singleKeyPropertySource("test", "foo", "bar")); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment).environmentEntry("does.not.exist"); @@ -233,7 +233,7 @@ public class EnvironmentEndpointTests { } @Test - public void multipleSourcesWithSameProperty() { + void multipleSourcesWithSameProperty() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources().addFirst(singleKeyPropertySource("one", "a", "alpha")); environment.getPropertySources().addFirst(singleKeyPropertySource("two", "a", "apple")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java index 5f9f033b331..e140c7061b9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java @@ -19,11 +19,9 @@ package org.springframework.boot.actuate.env; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @@ -32,87 +30,89 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(WebEndpointRunners.class) -public class EnvironmentEndpointWebIntegrationTests { +class EnvironmentEndpointWebIntegrationTests { - private static WebTestClient client; + private ConfigurableApplicationContext context; - private static ConfigurableApplicationContext context; + private WebTestClient client; - @Before - public void prepareEnvironment() { + @BeforeEach + public void prepareEnvironment(ConfigurableApplicationContext context, WebTestClient client) { TestPropertyValues.of("foo:bar", "fool:baz").applyTo(context); + this.client = client; + this.context = context; } - @Test - public void home() { - client.get().uri("/actuator/env").exchange().expectStatus().isOk().expectBody() + @WebEndpointTest + void home() { + this.client.get().uri("/actuator/env").exchange().expectStatus().isOk().expectBody() .jsonPath("propertySources[?(@.name=='systemProperties')]").exists(); } - @Test - public void sub() { - client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk().expectBody().jsonPath("property.source") - .isEqualTo("test").jsonPath("property.value").isEqualTo("bar"); + @WebEndpointTest + void sub() { + this.client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk().expectBody() + .jsonPath("property.source").isEqualTo("test").jsonPath("property.value").isEqualTo("bar"); } - @Test - public void regex() { + @WebEndpointTest + void regex() { Map map = new HashMap<>(); map.put("food", null); - EnvironmentEndpointWebIntegrationTests.context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("null-value", map)); - client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk().expectBody() + this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("null-value", map)); + this.client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk().expectBody() .jsonPath(forProperty("test", "foo")).isEqualTo("bar").jsonPath(forProperty("test", "fool")) .isEqualTo("baz"); } - @Test - public void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { + @WebEndpointTest + void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("unresolved-placeholder", map)); - client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() + this.context.getEnvironment().getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() .jsonPath("property.value").isEqualTo("${my.bar}").jsonPath(forPropertyEntry("unresolved-placeholder")) .isEqualTo("${my.bar}"); } - @Test - public void nestedPathWithSensitivePlaceholderShouldSanitize() { + @WebEndpointTest + void nestedPathWithSensitivePlaceholderShouldSanitize() { Map map = new HashMap<>(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); - context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); - client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() + this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); + this.client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() .jsonPath("property.value").isEqualTo("******").jsonPath(forPropertyEntry("placeholder")) .isEqualTo("******"); } - @Test - public void nestedPathForUnknownKeyShouldReturn404AndBody() { - client.get().uri("/actuator/env/this.does.not.exist").exchange().expectStatus().isNotFound().expectBody() + @WebEndpointTest + void nestedPathForUnknownKeyShouldReturn404AndBody() { + this.client.get().uri("/actuator/env/this.does.not.exist").exchange().expectStatus().isNotFound().expectBody() .jsonPath("property").doesNotExist().jsonPath("propertySources[?(@.name=='test')]").exists() .jsonPath("propertySources[?(@.name=='systemProperties')]").exists() .jsonPath("propertySources[?(@.name=='systemEnvironment')]").exists(); } - @Test - public void nestedPathMatchedByRegexWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { + @WebEndpointTest + void nestedPathMatchedByRegexWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("unresolved-placeholder", map)); - client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() + this.context.getEnvironment().getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") .isEqualTo("${my.bar}"); } - @Test - public void nestedPathMatchedByRegexWithSensitivePlaceholderShouldSanitize() { + @WebEndpointTest + void nestedPathMatchedByRegexWithSensitivePlaceholderShouldSanitize() { Map map = new HashMap<>(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); - context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); - client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() + this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("placeholder", map)); + this.client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() .jsonPath(forProperty("placeholder", "my.foo")).isEqualTo("******"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java index 9eb805a64c2..3e92e000621 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java @@ -36,14 +36,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Phillip Webb */ -public class FlywayEndpointTests { +class FlywayEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) .withUserConfiguration(EmbeddedDataSourceConfiguration.class).withBean("endpoint", FlywayEndpoint.class); @Test - public void flywayReportIsProduced() { + void flywayReportIsProduced() { this.contextRunner.run((context) -> { Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() .getContexts().get(context.getId()).getFlywayBeans(); @@ -54,7 +54,7 @@ public class FlywayEndpointTests { @Test @SuppressWarnings("deprecation") - public void whenFlywayHasBeenBaselinedFlywayReportIsProduced() { + void whenFlywayHasBeenBaselinedFlywayReportIsProduced() { this.contextRunner.withBean(FlywayMigrationStrategy.class, () -> (flyway) -> { flyway.setBaselineVersionAsString("2"); flyway.baseline(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java index c5f364504d0..0a02398dc57 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java @@ -25,10 +25,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ApplicationHealthIndicatorTests { +class ApplicationHealthIndicatorTests { @Test - public void indicatesUp() { + void indicatesUp() { ApplicationHealthIndicator healthIndicator = new ApplicationHealthIndicator(); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UP); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java index a7c990213b2..7a6e0efc5e1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java @@ -36,7 +36,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb * @author Christian Dupuis */ -public class CompositeHealthIndicatorTests { +class CompositeHealthIndicatorTests { private HealthAggregator healthAggregator; @@ -56,7 +56,7 @@ public class CompositeHealthIndicatorTests { } @Test - public void createWithIndicators() { + void createWithIndicators() { Map indicators = new HashMap<>(); indicators.put("one", this.one); indicators.put("two", this.two); @@ -70,7 +70,7 @@ public class CompositeHealthIndicatorTests { } @Test - public void testSerialization() throws Exception { + void testSerialization() throws Exception { Map indicators = new HashMap<>(); indicators.put("db1", this.one); indicators.put("db2", this.two); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java index c18ca8aca45..7789402ff1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CompositeReactiveHealthIndicatorTests { +class CompositeReactiveHealthIndicatorTests { private static final Health UNKNOWN_HEALTH = Health.unknown().withDetail("detail", "value").build(); @@ -41,7 +41,7 @@ public class CompositeReactiveHealthIndicatorTests { private OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); @Test - public void singleIndicator() { + void singleIndicator() { CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator, new DefaultReactiveHealthIndicatorRegistry(Collections.singletonMap("test", () -> Mono.just(HEALTHY)))); StepVerifier.create(indicator.health()).consumeNextWith((h) -> { @@ -52,7 +52,7 @@ public class CompositeReactiveHealthIndicatorTests { } @Test - public void longHealth() { + void longHealth() { Map indicators = new HashMap<>(); for (int i = 0; i < 50; i++) { indicators.put("test" + i, new TimeoutHealth(10000, Status.UP)); @@ -68,7 +68,7 @@ public class CompositeReactiveHealthIndicatorTests { } @Test - public void timeoutReachedUsesFallback() { + void timeoutReachedUsesFallback() { Map indicators = new HashMap<>(); indicators.put("slow", new TimeoutHealth(10000, Status.UP)); indicators.put("fast", new TimeoutHealth(10, Status.UP)); @@ -83,7 +83,7 @@ public class CompositeReactiveHealthIndicatorTests { } @Test - public void timeoutNotReached() { + void timeoutNotReached() { Map indicators = new HashMap<>(); indicators.put("slow", new TimeoutHealth(10000, Status.UP)); indicators.put("fast", new TimeoutHealth(10, Status.UP)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java index 3f38d58b863..5cbf406b59e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.mock; * @author Vedran Pavic * @author Stephane Nicoll */ -public class DefaultHealthIndicatorRegistryTests { +class DefaultHealthIndicatorRegistryTests { private HealthIndicator one = mock(HealthIndicator.class); @@ -49,7 +49,7 @@ public class DefaultHealthIndicatorRegistryTests { } @Test - public void register() { + void register() { this.registry.register("one", this.one); this.registry.register("two", this.two); assertThat(this.registry.getAll()).hasSize(2); @@ -58,14 +58,14 @@ public class DefaultHealthIndicatorRegistryTests { } @Test - public void registerAlreadyUsedName() { + void registerAlreadyUsedName() { this.registry.register("one", this.one); assertThatIllegalStateException().isThrownBy(() -> this.registry.register("one", this.two)) .withMessageContaining("HealthIndicator with name 'one' already registered"); } @Test - public void unregister() { + void unregister() { this.registry.register("one", this.one); this.registry.register("two", this.two); assertThat(this.registry.getAll()).hasSize(2); @@ -75,7 +75,7 @@ public class DefaultHealthIndicatorRegistryTests { } @Test - public void unregisterUnknown() { + void unregisterUnknown() { this.registry.register("one", this.one); assertThat(this.registry.getAll()).hasSize(1); HealthIndicator two = this.registry.unregister("two"); @@ -84,7 +84,7 @@ public class DefaultHealthIndicatorRegistryTests { } @Test - public void getAllIsASnapshot() { + void getAllIsASnapshot() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); assertThat(snapshot).containsOnlyKeys("one"); @@ -93,7 +93,7 @@ public class DefaultHealthIndicatorRegistryTests { } @Test - public void getAllIsImmutable() { + void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(snapshot::clear); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java index 5e584c0579e..d95b7f62b74 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.mock; * @author Vedran Pavic * @author Stephane Nicoll */ -public class DefaultReactiveHealthIndicatorRegistryTests { +class DefaultReactiveHealthIndicatorRegistryTests { private ReactiveHealthIndicator one = mock(ReactiveHealthIndicator.class); @@ -50,7 +50,7 @@ public class DefaultReactiveHealthIndicatorRegistryTests { } @Test - public void register() { + void register() { this.registry.register("one", this.one); this.registry.register("two", this.two); assertThat(this.registry.getAll()).hasSize(2); @@ -59,14 +59,14 @@ public class DefaultReactiveHealthIndicatorRegistryTests { } @Test - public void registerAlreadyUsedName() { + void registerAlreadyUsedName() { this.registry.register("one", this.one); assertThatIllegalStateException().isThrownBy(() -> this.registry.register("one", this.two)) .withMessageContaining("HealthIndicator with name 'one' already registered"); } @Test - public void unregister() { + void unregister() { this.registry.register("one", this.one); this.registry.register("two", this.two); assertThat(this.registry.getAll()).hasSize(2); @@ -76,7 +76,7 @@ public class DefaultReactiveHealthIndicatorRegistryTests { } @Test - public void unregisterUnknown() { + void unregisterUnknown() { this.registry.register("one", this.one); assertThat(this.registry.getAll()).hasSize(1); ReactiveHealthIndicator two = this.registry.unregister("two"); @@ -85,7 +85,7 @@ public class DefaultReactiveHealthIndicatorRegistryTests { } @Test - public void getAllIsASnapshot() { + void getAllIsASnapshot() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); assertThat(snapshot).containsOnlyKeys("one"); @@ -94,7 +94,7 @@ public class DefaultReactiveHealthIndicatorRegistryTests { } @Test - public void getAllIsImmutable() { + void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(snapshot::clear); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java index ec80e6853f1..bece2beb4c0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.entry; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class HealthEndpointTests { +class HealthEndpointTests { private static final HealthIndicator one = () -> new Health.Builder().status(Status.UP).withDetail("first", "1") .build(); @@ -42,7 +42,7 @@ public class HealthEndpointTests { .build(); @Test - public void statusAndFullDetailsAreExposed() { + void statusAndFullDetailsAreExposed() { Map healthIndicators = new HashMap<>(); healthIndicators.put("up", one); healthIndicators.put("upAgain", two); @@ -57,7 +57,7 @@ public class HealthEndpointTests { } @Test - public void statusForComponentIsExposed() { + void statusForComponentIsExposed() { HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(Collections.singletonMap("test", one))); Health health = endpoint.healthForComponent("test"); assertThat(health).isNotNull(); @@ -66,14 +66,14 @@ public class HealthEndpointTests { } @Test - public void statusForUnknownComponentReturnNull() { + void statusForUnknownComponentReturnNull() { HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(Collections.emptyMap())); Health health = endpoint.healthForComponent("does-not-exist"); assertThat(health).isNull(); } @Test - public void statusForComponentInstanceIsExposed() { + void statusForComponentInstanceIsExposed() { CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("sub", () -> Health.down().build())); HealthEndpoint endpoint = new HealthEndpoint( @@ -85,7 +85,7 @@ public class HealthEndpointTests { } @Test - public void statusForUnknownComponentInstanceReturnNull() { + void statusForUnknownComponentInstanceReturnNull() { CompositeHealthIndicator compositeIndicator = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("sub", () -> Health.down().build())); HealthEndpoint endpoint = new HealthEndpoint( @@ -95,7 +95,7 @@ public class HealthEndpointTests { } @Test - public void statusForComponentInstanceThatIsNotACompositeReturnNull() { + void statusForComponentInstanceThatIsNotACompositeReturnNull() { HealthEndpoint endpoint = new HealthEndpoint( createHealthIndicator(Collections.singletonMap("test", () -> Health.up().build()))); Health health = endpoint.healthForComponentInstance("test", "does-not-exist"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java index 5a3470ec827..5c92e2b8253 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java @@ -23,15 +23,13 @@ import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Consumer; -import org.junit.Test; -import org.junit.runner.RunWith; import reactor.core.publisher.Mono; import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; -import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @@ -43,55 +41,55 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class HealthEndpointWebIntegrationTests { +class HealthEndpointWebIntegrationTests { - private static WebTestClient client; - - private static ConfigurableApplicationContext context; - - @Test - public void whenHealthIsUp200ResponseIsReturned() { + @WebEndpointTest + void whenHealthIsUp200ResponseIsReturned(WebTestClient client) { client.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody().jsonPath("status") .isEqualTo("UP").jsonPath("details.alpha.status").isEqualTo("UP").jsonPath("details.bravo.status") .isEqualTo("UP"); } - @Test - public void whenHealthIsDown503ResponseIsReturned() throws Exception { - withHealthIndicator("charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), () -> { - client.get().uri("/actuator/health").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) - .expectBody().jsonPath("status").isEqualTo("DOWN").jsonPath("details.alpha.status").isEqualTo("UP") - .jsonPath("details.bravo.status").isEqualTo("UP").jsonPath("details.charlie.status") - .isEqualTo("DOWN"); - return null; - }); + @WebEndpointTest + void whenHealthIsDown503ResponseIsReturned(ApplicationContext context, WebTestClient client) throws Exception { + withHealthIndicator(context, "charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), + () -> { + client.get().uri("/actuator/health").exchange().expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN") + .jsonPath("details.alpha.status").isEqualTo("UP").jsonPath("details.bravo.status") + .isEqualTo("UP").jsonPath("details.charlie.status").isEqualTo("DOWN"); + return null; + }); } - @Test - public void whenComponentHealthIsDown503ResponseIsReturned() throws Exception { - withHealthIndicator("charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), () -> { - client.get().uri("/actuator/health/charlie").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN"); - return null; - }); + @WebEndpointTest + void whenComponentHealthIsDown503ResponseIsReturned(ApplicationContext context, WebTestClient client) + throws Exception { + withHealthIndicator(context, "charlie", () -> Health.down().build(), () -> Mono.just(Health.down().build()), + () -> { + client.get().uri("/actuator/health/charlie").exchange().expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") + .isEqualTo("DOWN"); + return null; + }); } - @Test - public void whenComponentInstanceHealthIsDown503ResponseIsReturned() throws Exception { + @WebEndpointTest + void whenComponentInstanceHealthIsDown503ResponseIsReturned(ApplicationContext context, WebTestClient client) + throws Exception { CompositeHealthIndicator composite = new CompositeHealthIndicator(new OrderedHealthAggregator(), Collections.singletonMap("one", () -> Health.down().build())); CompositeReactiveHealthIndicator reactiveComposite = new CompositeReactiveHealthIndicator( new OrderedHealthAggregator(), new DefaultReactiveHealthIndicatorRegistry( Collections.singletonMap("one", () -> Mono.just(Health.down().build())))); - withHealthIndicator("charlie", composite, reactiveComposite, () -> { + withHealthIndicator(context, "charlie", composite, reactiveComposite, () -> { client.get().uri("/actuator/health/charlie/one").exchange().expectStatus() .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN"); return null; }); } - private void withHealthIndicator(String name, HealthIndicator healthIndicator, + private void withHealthIndicator(ApplicationContext context, String name, HealthIndicator healthIndicator, ReactiveHealthIndicator reactiveHealthIndicator, Callable action) throws Exception { Consumer unregister; Consumer reactiveUnregister; @@ -116,8 +114,8 @@ public class HealthEndpointWebIntegrationTests { } } - @Test - public void whenHealthIndicatorIsRemovedResponseIsAltered() { + @WebEndpointTest + void whenHealthIndicatorIsRemovedResponseIsAltered(WebTestClient client, ApplicationContext context) { Consumer reactiveRegister = null; try { ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java index fd5cfd5144c..e7f89cdc384 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java @@ -27,10 +27,10 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class HealthIndicatorReactiveAdapterTests { +class HealthIndicatorReactiveAdapterTests { @Test - public void delegateReturnsHealth() { + void delegateReturnsHealth() { HealthIndicator delegate = mock(HealthIndicator.class); HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); Health status = Health.up().build(); @@ -39,7 +39,7 @@ public class HealthIndicatorReactiveAdapterTests { } @Test - public void delegateThrowError() { + void delegateThrowError() { HealthIndicator delegate = mock(HealthIndicator.class); HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); given(delegate.health()).willThrow(new IllegalStateException("Expected")); @@ -47,7 +47,7 @@ public class HealthIndicatorReactiveAdapterTests { } @Test - public void delegateRunsOnTheElasticScheduler() { + void delegateRunsOnTheElasticScheduler() { String currentThread = Thread.currentThread().getName(); HealthIndicator delegate = () -> Health .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP).build(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index c30b05ef0fb..a65810e55e7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -33,30 +33,30 @@ import static org.assertj.core.api.Assertions.entry; * @author Michael Pratt * @author Stephane Nicoll */ -public class HealthTests { +class HealthTests { @Test - public void statusMustNotBeNull() { + void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Health.Builder(null, null)) .withMessageContaining("Status must not be null"); } @Test - public void createWithStatus() { + void createWithStatus() { Health health = Health.status(Status.UP).build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).isEmpty(); } @Test - public void createWithDetails() { + void createWithDetails() { Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsOnly(entry("a", "b")); } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { Health h1 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).build(); Health h3 = new Health.Builder(Status.UP).build(); @@ -69,7 +69,7 @@ public class HealthTests { } @Test - public void withException() { + void withException() { RuntimeException ex = new RuntimeException("bang"); Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withException(ex).build(); assertThat(health.getDetails()).containsOnly(entry("a", "b"), @@ -77,13 +77,13 @@ public class HealthTests { } @Test - public void withDetails() { + void withDetails() { Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")).withDetail("c", "d").build(); assertThat(health.getDetails()).containsOnly(entry("a", "b"), entry("c", "d")); } @Test - public void withDetailsMap() { + void withDetailsMap() { Map details = new LinkedHashMap<>(); details.put("a", "b"); details.put("c", "d"); @@ -92,7 +92,7 @@ public class HealthTests { } @Test - public void withDetailsMapDuplicateKeys() { + void withDetailsMapDuplicateKeys() { Map details = new LinkedHashMap<>(); details.put("c", "d"); details.put("a", "e"); @@ -101,7 +101,7 @@ public class HealthTests { } @Test - public void withDetailsMultipleMaps() { + void withDetailsMultipleMaps() { Map details1 = new LinkedHashMap<>(); details1.put("a", "b"); details1.put("c", "d"); @@ -113,35 +113,35 @@ public class HealthTests { } @Test - public void unknownWithDetails() { + void unknownWithDetails() { Health health = new Health.Builder().unknown().withDetail("a", "b").build(); assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN); assertThat(health.getDetails()).containsOnly(entry("a", "b")); } @Test - public void unknown() { + void unknown() { Health health = new Health.Builder().unknown().build(); assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN); assertThat(health.getDetails()).isEmpty(); } @Test - public void upWithDetails() { + void upWithDetails() { Health health = new Health.Builder().up().withDetail("a", "b").build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsOnly(entry("a", "b")); } @Test - public void up() { + void up() { Health health = new Health.Builder().up().build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).isEmpty(); } @Test - public void downWithException() { + void downWithException() { RuntimeException ex = new RuntimeException("bang"); Health health = Health.down(ex).build(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); @@ -149,28 +149,28 @@ public class HealthTests { } @Test - public void down() { + void down() { Health health = Health.down().build(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getDetails()).isEmpty(); } @Test - public void outOfService() { + void outOfService() { Health health = Health.outOfService().build(); assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); assertThat(health.getDetails()).isEmpty(); } @Test - public void statusCode() { + void statusCode() { Health health = Health.status("UP").build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).isEmpty(); } @Test - public void status() { + void status() { Health health = Health.status(Status.UP).build(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).isEmpty(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java index fc442fbd0aa..5f1165fc9b3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthWebEndpointResponseMapperTests.java @@ -42,14 +42,14 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Stephane Nicoll */ -public class HealthWebEndpointResponseMapperTests { +class HealthWebEndpointResponseMapperTests { private final HealthStatusHttpMapper statusHttpMapper = new HealthStatusHttpMapper(); private Set authorizedRoles = Collections.singleton("ACTUATOR"); @Test - public void mapDetailsWithDisableDetailsDoesNotInvokeSupplier() { + void mapDetailsWithDisableDetailsDoesNotInvokeSupplier() { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.NEVER); Supplier supplier = mockSupplier(); SecurityContext securityContext = mock(SecurityContext.class); @@ -60,7 +60,7 @@ public class HealthWebEndpointResponseMapperTests { } @Test - public void mapDetailsWithUnauthorizedUserDoesNotInvokeSupplier() { + void mapDetailsWithUnauthorizedUserDoesNotInvokeSupplier() { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.WHEN_AUTHORIZED); Supplier supplier = mockSupplier(); SecurityContext securityContext = mockSecurityContext("USER"); @@ -72,7 +72,7 @@ public class HealthWebEndpointResponseMapperTests { } @Test - public void mapDetailsWithAuthorizedUserInvokeSupplier() { + void mapDetailsWithAuthorizedUserInvokeSupplier() { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.WHEN_AUTHORIZED); Supplier supplier = mockSupplier(); given(supplier.get()).willReturn(Health.down().build()); @@ -85,7 +85,7 @@ public class HealthWebEndpointResponseMapperTests { } @Test - public void mapDetailsWithUnavailableHealth() { + void mapDetailsWithUnavailableHealth() { HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.ALWAYS); Supplier supplier = mockSupplier(); SecurityContext securityContext = mock(SecurityContext.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java index 76f3068c93a..5872363e2a1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Christian Dupuis */ -public class OrderedHealthAggregatorTests { +class OrderedHealthAggregatorTests { private OrderedHealthAggregator healthAggregator; @@ -40,7 +40,7 @@ public class OrderedHealthAggregatorTests { } @Test - public void defaultOrder() { + void defaultOrder() { Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); @@ -50,7 +50,7 @@ public class OrderedHealthAggregatorTests { } @Test - public void customOrder() { + void customOrder() { this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP, Status.OUT_OF_SERVICE, Status.DOWN); Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); @@ -61,7 +61,7 @@ public class OrderedHealthAggregatorTests { } @Test - public void defaultOrderWithCustomStatus() { + void defaultOrderWithCustomStatus() { Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); healths.put("h2", new Health.Builder().status(Status.UP).build()); @@ -72,7 +72,7 @@ public class OrderedHealthAggregatorTests { } @Test - public void customOrderWithCustomStatus() { + void customOrderWithCustomStatus() { this.healthAggregator.setStatusOrder(Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM")); Map healths = new HashMap<>(); healths.put("h1", new Health.Builder().status(Status.DOWN).build()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java index b5c073fdc30..ab26ea7811f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ReactiveHealthIndicatorRegistryFactoryTests { +class ReactiveHealthIndicatorRegistryFactoryTests { private static final Health UP = new Health.Builder().status(Status.UP).build(); @@ -38,14 +38,14 @@ public class ReactiveHealthIndicatorRegistryFactoryTests { private final ReactiveHealthIndicatorRegistryFactory factory = new ReactiveHealthIndicatorRegistryFactory(); @Test - public void defaultHealthIndicatorNameFactory() { + void defaultHealthIndicatorNameFactory() { ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry( Collections.singletonMap("myHealthIndicator", () -> Mono.just(UP)), null); assertThat(registry.getAll()).containsOnlyKeys("my"); } @Test - public void healthIndicatorIsAdapted() { + void healthIndicatorIsAdapted() { ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry( Collections.singletonMap("test", () -> Mono.just(UP)), Collections.singletonMap("regular", () -> DOWN)); assertThat(registry.getAll()).containsOnlyKeys("test", "regular"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java index 37f8ff78084..6f94f0d11fc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java @@ -36,10 +36,10 @@ import static org.mockito.Mockito.verify; * * @author Eddú Meléndez */ -public class InfluxDbHealthIndicatorTests { +class InfluxDbHealthIndicatorTests { @Test - public void influxDbIsUp() { + void influxDbIsUp() { Pong pong = mock(Pong.class); given(pong.getVersion()).willReturn("0.9"); InfluxDB influxDB = mock(InfluxDB.class); @@ -52,7 +52,7 @@ public class InfluxDbHealthIndicatorTests { } @Test - public void influxDbIsDown() { + void influxDbIsDown() { InfluxDB influxDB = mock(InfluxDB.class); given(influxDB.ping()).willThrow(new InfluxDBException(new IOException("Connection failed"))); InfluxDbHealthIndicator healthIndicator = new InfluxDbHealthIndicator(influxDB); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java index f9036979fcb..e00cb8018b8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/EnvironmentInfoContributorTests.java @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class EnvironmentInfoContributorTests { +class EnvironmentInfoContributorTests { private final StandardEnvironment environment = new StandardEnvironment(); @Test - public void extractOnlyInfoProperty() { + void extractOnlyInfoProperty() { TestPropertyValues.of("info.app=my app", "info.version=1.0.0", "foo=bar").applyTo(this.environment); Info actual = contributeFrom(this.environment); assertThat(actual.get("app", String.class)).isEqualTo("my app"); @@ -46,7 +46,7 @@ public class EnvironmentInfoContributorTests { } @Test - public void extractNoEntry() { + void extractNoEntry() { TestPropertyValues.of("foo=bar").applyTo(this.environment); Info actual = contributeFrom(this.environment); assertThat(actual.getDetails()).isEmpty(); @@ -54,7 +54,7 @@ public class EnvironmentInfoContributorTests { @Test @SuppressWarnings("unchecked") - public void propertiesFromEnvironmentShouldBindCorrectly() { + void propertiesFromEnvironmentShouldBindCorrectly() { TestPropertyValues.of("INFO_ENVIRONMENT_FOO=green").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); Info actual = contributeFrom(this.environment); assertThat(actual.get("environment", Map.class)).containsEntry("foo", "green"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java index 848f6551289..c2534723845 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java @@ -32,11 +32,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class GitInfoContributorTests { +class GitInfoContributorTests { @Test @SuppressWarnings("unchecked") - public void coerceDate() { + void coerceDate() { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.time", "2016-03-04T14:36:33+0100"); @@ -51,7 +51,7 @@ public class GitInfoContributorTests { @Test @SuppressWarnings("unchecked") - public void shortenCommitId() { + void shortenCommitId() { Properties properties = new Properties(); properties.put("branch", "master"); properties.put("commit.id", "8e29a0b0d423d2665c6ee5171947c101a5c15681"); @@ -64,7 +64,7 @@ public class GitInfoContributorTests { @Test @SuppressWarnings("unchecked") - public void withGitIdAndAbbrev() { + void withGitIdAndAbbrev() { // gh-11892 Properties properties = new Properties(); properties.put("branch", "master"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java index 0334e87d8be..ec0fe4e9403 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointTests.java @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Meang Akira Tanaka * @author Andy Wilkinson */ -public class InfoEndpointTests { +class InfoEndpointTests { @Test - public void info() { + void info() { InfoEndpoint endpoint = new InfoEndpoint(Arrays.asList((builder) -> builder.withDetail("key1", "value1"), (builder) -> builder.withDetail("key2", "value2"))); Map info = endpoint.info(); @@ -45,7 +45,7 @@ public class InfoEndpointTests { } @Test - public void infoWithNoContributorsProducesEmptyMap() { + void infoWithNoContributorsProducesEmptyMap() { InfoEndpoint endpoint = new InfoEndpoint(Collections.emptyList()); Map info = endpoint.info(); assertThat(info).isEmpty(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java index 7a28647f245..e4f04ccb2c6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java @@ -20,11 +20,8 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; -import org.junit.Test; -import org.junit.runner.RunWith; - import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -38,14 +35,11 @@ import org.springframework.test.web.reactive.server.WebTestClient; * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) @TestPropertySource(properties = { "info.app.name=MyService" }) -public class InfoEndpointWebIntegrationTests { +class InfoEndpointWebIntegrationTests { - private static WebTestClient client; - - @Test - public void info() { + @WebEndpointTest + void info(WebTestClient client) { client.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() .expectBody().jsonPath("beanName1.key11").isEqualTo("value11").jsonPath("beanName1.key12") .isEqualTo("value12").jsonPath("beanName2.key21").isEqualTo("value21").jsonPath("beanName2.key22") diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java index 02107342fe9..b4a870ee117 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java @@ -27,16 +27,16 @@ import static org.assertj.core.api.Assertions.entry; * * @author Stephane Nicoll */ -public class InfoTests { +class InfoTests { @Test - public void infoIsImmutable() { + void infoIsImmutable() { Info info = new Info.Builder().withDetail("foo", "bar").build(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(info.getDetails()::clear); } @Test - public void infoTakesCopyOfMap() { + void infoTakesCopyOfMap() { Info.Builder builder = new Info.Builder(); builder.withDetail("foo", "bar"); Info build = builder.build(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java index a8c533e3101..f82597cab12 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java @@ -26,15 +26,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Stephane Nicoll */ -public class SimpleInfoContributorTests { +class SimpleInfoContributorTests { @Test - public void prefixIsMandatory() { + void prefixIsMandatory() { assertThatIllegalArgumentException().isThrownBy(() -> new SimpleInfoContributor(null, new Object())); } @Test - public void mapSimpleObject() { + void mapSimpleObject() { Object o = new Object(); Info info = contributeFrom("test", o); assertThat(info.get("test")).isSameAs(o); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointTests.java index 8bcbbbe2c8d..243b80642e5 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointTests.java @@ -35,7 +35,7 @@ import static org.mockito.Mockito.verify; * * @author Tim Ysewyn */ -public class IntegrationGraphEndpointTests { +class IntegrationGraphEndpointTests { @Mock private IntegrationGraphServer integrationGraphServer; @@ -49,7 +49,7 @@ public class IntegrationGraphEndpointTests { } @Test - public void readOperationShouldReturnGraph() { + void readOperationShouldReturnGraph() { Graph mockedGraph = mock(Graph.class); given(this.integrationGraphServer.getGraph()).willReturn(mockedGraph); Graph graph = this.integrationGraphEndpoint.graph(); @@ -58,7 +58,7 @@ public class IntegrationGraphEndpointTests { } @Test - public void writeOperationShouldRebuildGraph() { + void writeOperationShouldRebuildGraph() { this.integrationGraphEndpoint.rebuild(); verify(this.integrationGraphServer).rebuild(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java index 86c7e4752e3..3a20d75c5d5 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java @@ -16,10 +16,7 @@ package org.springframework.boot.actuate.integration; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -33,21 +30,18 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Tim Ysewyn */ -@RunWith(WebEndpointRunners.class) -public class IntegrationGraphEndpointWebIntegrationTests { +class IntegrationGraphEndpointWebIntegrationTests { - private static WebTestClient client; - - @Test - public void graph() { + @WebEndpointTest + void graph(WebTestClient client) { client.get().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() .isOk().expectBody().jsonPath("contentDescriptor.providerVersion").isNotEmpty() .jsonPath("contentDescriptor.providerFormatVersion").isEqualTo(1.0f) .jsonPath("contentDescriptor.provider").isEqualTo("spring-integration"); } - @Test - public void rebuild() { + @WebEndpointTest + void rebuild(WebTestClient client) { client.post().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() .isNoContent(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java index ded220843cd..2ad4facce87 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicatorTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Stephane Nicoll */ -public class DataSourceHealthIndicatorTests { +class DataSourceHealthIndicatorTests { private final DataSourceHealthIndicator indicator = new DataSourceHealthIndicator(); @@ -65,7 +65,7 @@ public class DataSourceHealthIndicatorTests { } @Test - public void healthIndicatorWithDefaultSettings() { + void healthIndicatorWithDefaultSettings() { this.indicator.setDataSource(this.dataSource); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -74,7 +74,7 @@ public class DataSourceHealthIndicatorTests { } @Test - public void healthIndicatorWithCustomValidationQuery() { + void healthIndicatorWithCustomValidationQuery() { String customValidationQuery = "SELECT COUNT(*) from FOO"; new JdbcTemplate(this.dataSource).execute("CREATE TABLE FOO (id INTEGER IDENTITY PRIMARY KEY)"); this.indicator.setDataSource(this.dataSource); @@ -86,7 +86,7 @@ public class DataSourceHealthIndicatorTests { } @Test - public void healthIndicatorWithInvalidValidationQuery() { + void healthIndicatorWithInvalidValidationQuery() { String invalidValidationQuery = "SELECT COUNT(*) from BAR"; this.indicator.setDataSource(this.dataSource); this.indicator.setQuery(invalidValidationQuery); @@ -98,7 +98,7 @@ public class DataSourceHealthIndicatorTests { } @Test - public void healthIndicatorCloseConnection() throws Exception { + void healthIndicatorCloseConnection() throws Exception { DataSource dataSource = mock(DataSource.class); Connection connection = mock(Connection.class); given(connection.getMetaData()).willReturn(this.dataSource.getConnection().getMetaData()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java index 7f520357282..93d39f95c67 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/jms/JmsHealthIndicatorTests.java @@ -41,10 +41,10 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class JmsHealthIndicatorTests { +class JmsHealthIndicatorTests { @Test - public void jmsBrokerIsUp() throws JMSException { + void jmsBrokerIsUp() throws JMSException { ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); given(connectionMetaData.getJMSProviderName()).willReturn("JMS test provider"); Connection connection = mock(Connection.class); @@ -59,7 +59,7 @@ public class JmsHealthIndicatorTests { } @Test - public void jmsBrokerIsDown() throws JMSException { + void jmsBrokerIsDown() throws JMSException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); given(connectionFactory.createConnection()).willThrow(new JMSException("test", "123")); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); @@ -69,7 +69,7 @@ public class JmsHealthIndicatorTests { } @Test - public void jmsBrokerCouldNotRetrieveProviderMetadata() throws JMSException { + void jmsBrokerCouldNotRetrieveProviderMetadata() throws JMSException { ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); given(connectionMetaData.getJMSProviderName()).willThrow(new JMSException("test", "123")); Connection connection = mock(Connection.class); @@ -84,7 +84,7 @@ public class JmsHealthIndicatorTests { } @Test - public void jmsBrokerUsesFailover() throws JMSException { + void jmsBrokerUsesFailover() throws JMSException { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); given(connectionMetaData.getJMSProviderName()).willReturn("JMS test provider"); @@ -99,7 +99,7 @@ public class JmsHealthIndicatorTests { } @Test - public void whenConnectionStartIsUnresponsiveStatusIsDown() throws JMSException { + void whenConnectionStartIsUnresponsiveStatusIsDown() throws JMSException { ConnectionMetaData connectionMetaData = mock(ConnectionMetaData.class); given(connectionMetaData.getJMSProviderName()).willReturn("JMS test provider"); Connection connection = mock(Connection.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java index de264b5358e..76e93fe1779 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java @@ -35,11 +35,11 @@ import static org.mockito.Mockito.verify; * * @author Eddú Meléndez */ -public class LdapHealthIndicatorTests { +class LdapHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void ldapIsUp() { + void ldapIsUp() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())).willReturn("3"); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); @@ -51,7 +51,7 @@ public class LdapHealthIndicatorTests { @Test @SuppressWarnings("unchecked") - public void ldapIsDown() { + void ldapIsDown() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())) .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java index 852e737051f..3f82ae80641 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class LiquibaseEndpointTests { +class LiquibaseEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( @@ -50,7 +50,7 @@ public class LiquibaseEndpointTests { .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test - public void liquibaseReportIsReturned() { + void liquibaseReportIsReturned() { this.contextRunner.withUserConfiguration(Config.class).run((context) -> { Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class).liquibaseBeans() .getContexts().get(context.getId()).getLiquibaseBeans(); @@ -59,7 +59,7 @@ public class LiquibaseEndpointTests { } @Test - public void invokeWithCustomSchema() { + void invokeWithCustomSchema() { this.contextRunner.withUserConfiguration(Config.class) .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA", "spring.datasource.schema=classpath:/db/create-custom-schema.sql") @@ -71,7 +71,7 @@ public class LiquibaseEndpointTests { } @Test - public void invokeWithCustomTables() { + void invokeWithCustomTables() { this.contextRunner.withUserConfiguration(Config.class) .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", "spring.liquibase.database-change-log-table=liquibase_database_changelog") @@ -83,7 +83,7 @@ public class LiquibaseEndpointTests { } @Test - public void connectionAutoCommitPropertyIsReset() { + void connectionAutoCommitPropertyIsReset() { this.contextRunner.withUserConfiguration(Config.class).run((context) -> { DataSource dataSource = context.getBean(DataSource.class); assertThat(getAutoCommit(dataSource)).isTrue(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java index beca8a574bd..2354def0d1c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointTests.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class LogFileWebEndpointTests { +class LogFileWebEndpointTests { private final MockEnvironment environment = new MockEnvironment(); @@ -55,18 +55,18 @@ public class LogFileWebEndpointTests { } @Test - public void nullResponseWithoutLogFile() { + void nullResponseWithoutLogFile() { assertThat(this.endpoint.logFile()).isNull(); } @Test - public void nullResponseWithMissingLogFile() { + void nullResponseWithMissingLogFile() { this.environment.setProperty("logging.file.name", "no_test.log"); assertThat(this.endpoint.logFile()).isNull(); } @Test - public void resourceResponseWithLogFile() throws Exception { + void resourceResponseWithLogFile() throws Exception { this.environment.setProperty("logging.file.name", this.logFile.getAbsolutePath()); Resource resource = this.endpoint.logFile(); assertThat(resource).isNotNull(); @@ -75,7 +75,7 @@ public class LogFileWebEndpointTests { @Test @Deprecated - public void resourceResponseWithLogFileAndDeprecatedProperty() throws Exception { + void resourceResponseWithLogFileAndDeprecatedProperty() throws Exception { this.environment.setProperty("logging.file", this.logFile.getAbsolutePath()); Resource resource = this.endpoint.logFile(); assertThat(resource).isNotNull(); @@ -83,7 +83,7 @@ public class LogFileWebEndpointTests { } @Test - public void resourceResponseWithExternalLogFile() throws Exception { + void resourceResponseWithExternalLogFile() throws Exception { LogFileWebEndpoint endpoint = new LogFileWebEndpoint(this.environment, this.logFile); Resource resource = endpoint.logFile(); assertThat(resource).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java index fee3560c8a2..49326d69a61 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java @@ -19,13 +19,10 @@ package org.springframework.boot.actuate.logging; import java.io.File; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @@ -41,40 +38,39 @@ import org.springframework.util.FileCopyUtils; * * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class LogFileWebEndpointWebIntegrationTests { +class LogFileWebEndpointWebIntegrationTests { - private static ConfigurableApplicationContext context; + private ConfigurableApplicationContext context; - private static WebTestClient client; - - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + private WebTestClient client; private File logFile; - @Before - public void setUp() throws IOException { - this.logFile = this.temp.newFile(); + @BeforeEach + public void setUp(@TempDir File temp, WebTestClient client, ConfigurableApplicationContext context) + throws IOException { + this.logFile = new File(temp, "test.log"); + this.client = client; + this.context = context; FileCopyUtils.copy("--TEST--".getBytes(), this.logFile); } - @Test - public void getRequestProduces404ResponseWhenLogFileNotFound() { - client.get().uri("/actuator/logfile").exchange().expectStatus().isNotFound(); + @WebEndpointTest + void getRequestProduces404ResponseWhenLogFileNotFound() { + this.client.get().uri("/actuator/logfile").exchange().expectStatus().isNotFound(); } - @Test - public void getRequestProducesResponseWithLogFile() { - TestPropertyValues.of("logging.file.name:" + this.logFile.getAbsolutePath()).applyTo(context); - client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectHeader() + @WebEndpointTest + void getRequestProducesResponseWithLogFile() { + TestPropertyValues.of("logging.file.name:" + this.logFile.getAbsolutePath()).applyTo(this.context); + this.client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectHeader() .contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); } - @Test - public void getRequestThatAcceptsTextPlainProducesResponseWithLogFile() { - TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()).applyTo(context); - client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() + @WebEndpointTest + void getRequestThatAcceptsTextPlainProducesResponseWithLogFile() { + TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()).applyTo(this.context); + this.client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() .expectHeader().contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java index 50e07fc489a..a83034508e9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java @@ -39,13 +39,13 @@ import static org.mockito.Mockito.verify; * @author Ben Hale * @author Andy Wilkinson */ -public class LoggersEndpointTests { +class LoggersEndpointTests { private final LoggingSystem loggingSystem = mock(LoggingSystem.class); @Test @SuppressWarnings("unchecked") - public void loggersShouldReturnLoggerConfigurations() { + void loggersShouldReturnLoggerConfigurations() { given(this.loggingSystem.getLoggerConfigurations()) .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); @@ -60,7 +60,7 @@ public class LoggersEndpointTests { } @Test - public void loggerLevelsWhenNameSpecifiedShouldReturnLevels() { + void loggerLevelsWhenNameSpecifiedShouldReturnLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); LoggerLevels levels = new LoggersEndpoint(this.loggingSystem).loggerLevels("ROOT"); @@ -69,13 +69,13 @@ public class LoggersEndpointTests { } @Test - public void configureLogLevelShouldSetLevelOnLoggingSystem() { + void configureLogLevelShouldSetLevelOnLoggingSystem() { new LoggersEndpoint(this.loggingSystem).configureLogLevel("ROOT", LogLevel.DEBUG); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } @Test - public void configureLogLevelWithNullSetsLevelOnLoggingSystemToNull() { + void configureLogLevelWithNullSetsLevelOnLoggingSystemToNull() { new LoggersEndpoint(this.loggingSystem).configureLogLevel("ROOT", null); verify(this.loggingSystem).setLogLevel("ROOT", null); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java index 830dd0a19c7..d0ced02224c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java @@ -21,14 +21,12 @@ import java.util.Collections; import java.util.EnumSet; import net.minidev.json.JSONArray; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; @@ -53,28 +51,26 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class LoggersEndpointWebIntegrationTests { +class LoggersEndpointWebIntegrationTests { - private static ConfigurableApplicationContext context; - - private static WebTestClient client; + private WebTestClient client; private LoggingSystem loggingSystem; - @Before - @After - public void resetMocks() { + @BeforeEach + @AfterEach + public void resetMocks(ConfigurableApplicationContext context, WebTestClient client) { + this.client = client; this.loggingSystem = context.getBean(LoggingSystem.class); Mockito.reset(this.loggingSystem); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); } - @Test - public void getLoggerShouldReturnAllLoggerConfigurations() { + @WebEndpointTest + void getLoggerShouldReturnAllLoggerConfigurations() { given(this.loggingSystem.getLoggerConfigurations()) .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - client.get().uri("/actuator/loggers").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") + this.client.get().uri("/actuator/loggers").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") .isEqualTo(2).jsonPath("levels") .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) .jsonPath("loggers.length()").isEqualTo(1).jsonPath("loggers.ROOT.length()").isEqualTo(2) @@ -82,60 +78,64 @@ public class LoggersEndpointWebIntegrationTests { .isEqualTo("DEBUG"); } - @Test - public void getLoggerShouldReturnLogLevels() { + @WebEndpointTest + void getLoggerShouldReturnLogLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); - client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") - .isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null).jsonPath("effectiveLevel").isEqualTo("DEBUG"); + this.client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk().expectBody() + .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) + .jsonPath("effectiveLevel").isEqualTo("DEBUG"); } - @Test - public void getLoggersWhenLoggerNotFoundShouldReturnNotFound() { - client.get().uri("/actuator/loggers/com.does.not.exist").exchange().expectStatus().isNotFound(); + @WebEndpointTest + void getLoggersWhenLoggerNotFoundShouldReturnNotFound() { + this.client.get().uri("/actuator/loggers/com.does.not.exist").exchange().expectStatus().isNotFound(); } - @Test - public void setLoggerUsingApplicationJsonShouldSetLogLevel() { - client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) + @WebEndpointTest + void setLoggerUsingApplicationJsonShouldSetLogLevel() { + this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } - @Test - public void setLoggerUsingActuatorV2JsonShouldSetLogLevel() { - client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) + @WebEndpointTest + void setLoggerUsingActuatorV2JsonShouldSetLogLevel() { + this.client.post().uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) .syncBody(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); } - @Test - public void setLoggerWithWrongLogLevelResultInBadRequestResponse() { - client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) + @WebEndpointTest + void setLoggerWithWrongLogLevelResultInBadRequestResponse() { + this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) .syncBody(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus() .isBadRequest(); verifyZeroInteractions(this.loggingSystem); } - @Test - public void setLoggerWithNullLogLevel() { - client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) + @WebEndpointTest + void setLoggerWithNullLogLevel() { + this.client.post().uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) .syncBody(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", null); } - @Test - public void setLoggerWithNoLogLevel() { - client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)) - .syncBody(Collections.emptyMap()).exchange().expectStatus().isNoContent(); + @WebEndpointTest + void setLoggerWithNoLogLevel() { + this.client.post().uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(ActuatorMediaType.V2_JSON)).syncBody(Collections.emptyMap()) + .exchange().expectStatus().isNoContent(); verify(this.loggingSystem).setLogLevel("ROOT", null); } - @Test - public void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() { + @WebEndpointTest + void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() { given(this.loggingSystem.getLoggerConfiguration("com.png")) .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); - client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk().expectBody() + this.client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk().expectBody() .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) .jsonPath("effectiveLevel").isEqualTo("DEBUG"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java index 4a3bb6a1ec7..09150771622 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mail/MailHealthIndicatorTests.java @@ -45,7 +45,7 @@ import static org.mockito.Mockito.mock; * @author Johannes Edmeier * @author Stephane Nicoll */ -public class MailHealthIndicatorTests { +class MailHealthIndicatorTests { private JavaMailSenderImpl mailSender; @@ -63,7 +63,7 @@ public class MailHealthIndicatorTests { } @Test - public void smtpIsUp() { + void smtpIsUp() { given(this.mailSender.getProtocol()).willReturn("success"); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -71,7 +71,7 @@ public class MailHealthIndicatorTests { } @Test - public void smtpIsDown() throws MessagingException { + void smtpIsDown() throws MessagingException { willThrow(new MessagingException("A test exception")).given(this.mailSender).testConnection(); Health health = this.indicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java index 079dbf8bb00..6a861b65924 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointTests.java @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class HeapDumpWebEndpointTests { +class HeapDumpWebEndpointTests { @Test - public void parallelRequestProducesTooManyRequestsResponse() throws InterruptedException { + void parallelRequestProducesTooManyRequestsResponse() throws InterruptedException { CountDownLatch dumpingLatch = new CountDownLatch(1); CountDownLatch blockingLatch = new CountDownLatch(1); HeapDumpWebEndpoint slowEndpoint = new HeapDumpWebEndpoint(2500) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java index c81e4528d21..da37f6672d3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java @@ -20,12 +20,10 @@ import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; -import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @@ -42,29 +40,24 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class HeapDumpWebEndpointWebIntegrationTests { - - private static WebTestClient client; - - private static ConfigurableApplicationContext context; +class HeapDumpWebEndpointWebIntegrationTests { private TestHeapDumpWebEndpoint endpoint; - @Before - public void configureEndpoint() { + @BeforeEach + public void configureEndpoint(ApplicationContext context) { this.endpoint = context.getBean(TestHeapDumpWebEndpoint.class); this.endpoint.setAvailable(true); } - @Test - public void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus() { + @WebEndpointTest + void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus(WebTestClient client) { this.endpoint.setAvailable(false); client.get().uri("/actuator/heapdump").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } - @Test - public void getRequestShouldReturnHeapDumpInResponseBody() throws Exception { + @WebEndpointTest + void getRequestShouldReturnHeapDumpInResponseBody(WebTestClient client) throws Exception { client.get().uri("/actuator/heapdump").exchange().expectStatus().isOk().expectHeader() .contentType(MediaType.APPLICATION_OCTET_STREAM).expectBody(String.class).isEqualTo("HEAPDUMP"); assertHeapDumpFileIsDeleted(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java index 16fcdfdad46..9ba758d32d0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class ThreadDumpEndpointTests { +class ThreadDumpEndpointTests { @Test - public void dumpThreads() { + void dumpThreads() { assertThat(new ThreadDumpEndpoint().threadDump().getThreads().size()).isGreaterThan(0); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java index 5430adcd8ca..12e3aae028b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java @@ -40,20 +40,20 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Andy Wilkinson * @author Jon Schneider */ -public class MetricsEndpointTests { +class MetricsEndpointTests { private final MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); private final MetricsEndpoint endpoint = new MetricsEndpoint(this.registry); @Test - public void listNamesHandlesEmptyListOfMeters() { + void listNamesHandlesEmptyListOfMeters() { MetricsEndpoint.ListNamesResponse result = this.endpoint.listNames(); assertThat(result.getNames()).isEmpty(); } @Test - public void listNamesProducesListOfUniqueMeterNames() { + void listNamesProducesListOfUniqueMeterNames() { this.registry.counter("com.example.foo"); this.registry.counter("com.example.bar"); this.registry.counter("com.example.foo"); @@ -62,7 +62,7 @@ public class MetricsEndpointTests { } @Test - public void listNamesRecursesOverCompositeRegistries() { + void listNamesRecursesOverCompositeRegistries() { CompositeMeterRegistry composite = new CompositeMeterRegistry(); SimpleMeterRegistry reg1 = new SimpleMeterRegistry(); SimpleMeterRegistry reg2 = new SimpleMeterRegistry(); @@ -75,7 +75,7 @@ public class MetricsEndpointTests { } @Test - public void metricValuesAreTheSumOfAllTimeSeriesMatchingTags() { + void metricValuesAreTheSumOfAllTimeSeriesMatchingTags() { this.registry.counter("cache", "result", "hit", "host", "1").increment(2); this.registry.counter("cache", "result", "miss", "host", "1").increment(2); this.registry.counter("cache", "result", "hit", "host", "2").increment(2); @@ -89,7 +89,7 @@ public class MetricsEndpointTests { } @Test - public void findFirstMatchingMetersFromNestedRegistries() { + void findFirstMatchingMetersFromNestedRegistries() { CompositeMeterRegistry composite = new CompositeMeterRegistry(); SimpleMeterRegistry firstLevel0 = new SimpleMeterRegistry(); CompositeMeterRegistry firstLevel1 = new CompositeMeterRegistry(); @@ -111,7 +111,7 @@ public class MetricsEndpointTests { } @Test - public void matchingMeterNotFoundInNestedRegistries() { + void matchingMeterNotFoundInNestedRegistries() { CompositeMeterRegistry composite = new CompositeMeterRegistry(); CompositeMeterRegistry firstLevel = new CompositeMeterRegistry(); SimpleMeterRegistry secondLevel = new SimpleMeterRegistry(); @@ -123,7 +123,7 @@ public class MetricsEndpointTests { } @Test - public void metricTagValuesAreDeduplicated() { + void metricTagValuesAreDeduplicated() { this.registry.counter("cache", "host", "1", "region", "east", "result", "hit"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", Collections.singletonList("host:1")); @@ -132,7 +132,7 @@ public class MetricsEndpointTests { } @Test - public void metricWithSpaceInTagValue() { + void metricWithSpaceInTagValue() { this.registry.counter("counter", "key", "a space").increment(2); MetricsEndpoint.MetricResponse response = this.endpoint.metric("counter", Collections.singletonList("key:a space")); @@ -142,13 +142,13 @@ public class MetricsEndpointTests { } @Test - public void metricWithInvalidTag() { + void metricWithInvalidTag() { assertThatExceptionOfType(InvalidEndpointRequestException.class) .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); } @Test - public void metricPresentInOneRegistryOfACompositeAndNotAnother() { + void metricPresentInOneRegistryOfACompositeAndNotAnother() { CompositeMeterRegistry composite = new CompositeMeterRegistry(); SimpleMeterRegistry reg1 = new SimpleMeterRegistry(); SimpleMeterRegistry reg2 = new SimpleMeterRegistry(); @@ -162,13 +162,13 @@ public class MetricsEndpointTests { } @Test - public void nonExistentMetric() { + void nonExistentMetric() { MetricsEndpoint.MetricResponse response = this.endpoint.metric("does.not.exist", Collections.emptyList()); assertThat(response).isNull(); } @Test - public void maxAggregation() { + void maxAggregation() { SimpleMeterRegistry reg = new SimpleMeterRegistry(); reg.timer("timer", "k", "v1").record(1, TimeUnit.SECONDS); reg.timer("timer", "k", "v2").record(2, TimeUnit.SECONDS); @@ -176,7 +176,7 @@ public class MetricsEndpointTests { } @Test - public void countAggregation() { + void countAggregation() { SimpleMeterRegistry reg = new SimpleMeterRegistry(); reg.counter("counter", "k", "v1").increment(); reg.counter("counter", "k", "v2").increment(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java index 8d83a17f3ed..71be9821c2f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java @@ -26,10 +26,8 @@ import io.micrometer.core.instrument.MockClock; import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics; import io.micrometer.core.instrument.simple.SimpleConfig; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.web.reactive.server.WebTestClient; @@ -42,32 +40,29 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Jon Schneider * @author Andy Wilkinson */ -@RunWith(WebEndpointRunners.class) -public class MetricsEndpointWebIntegrationTests { +class MetricsEndpointWebIntegrationTests { private static MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); - private static WebTestClient client; - private final ObjectMapper mapper = new ObjectMapper(); - @Test + @WebEndpointTest @SuppressWarnings("unchecked") - public void listNames() throws IOException { + void listNames(WebTestClient client) throws IOException { String responseBody = client.get().uri("/actuator/metrics").exchange().expectStatus().isOk() .expectBody(String.class).returnResult().getResponseBody(); Map> names = this.mapper.readValue(responseBody, Map.class); assertThat(names.get("names")).containsOnlyOnce("jvm.memory.used"); } - @Test - public void selectByName() { + @WebEndpointTest + void selectByName(WebTestClient client) { client.get().uri("/actuator/metrics/jvm.memory.used").exchange().expectStatus().isOk().expectBody() .jsonPath("$.name").isEqualTo("jvm.memory.used"); } - @Test - public void selectByTag() { + @WebEndpointTest + void selectByTag(WebTestClient client) { client.get().uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space").exchange() .expectStatus().isOk().expectBody().jsonPath("$.name").isEqualTo("jvm.memory.used"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java index 4e371618f60..a186e6f2317 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/amqp/RabbitMetricsTests.java @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class RabbitMetricsTests { +class RabbitMetricsTests { @Test - public void connectionFactoryIsInstrumented() { + void connectionFactoryIsInstrumented() { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); SimpleMeterRegistry registry = new SimpleMeterRegistry(); new RabbitMetrics(connectionFactory, null).bindTo(registry); @@ -40,7 +40,7 @@ public class RabbitMetricsTests { } @Test - public void connectionFactoryWithTagsIsInstrumented() { + void connectionFactoryWithTagsIsInstrumented() { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); SimpleMeterRegistry registry = new SimpleMeterRegistry(); new RabbitMetrics(connectionFactory, Tags.of("env", "prod")).bindTo(registry); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java index 80b55be9348..150601e176e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java @@ -33,12 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CacheMetricsRegistrarTests { +class CacheMetricsRegistrarTests { private final MeterRegistry meterRegistry = new SimpleMeterRegistry(); @Test - public void bindToSupportedCache() { + void bindToSupportedCache() { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); assertThat(registrar.bindCacheToRegistry(new CaffeineCache("test", Caffeine.newBuilder().build()))).isTrue(); @@ -46,7 +46,7 @@ public class CacheMetricsRegistrarTests { } @Test - public void bindToSupportedCacheWrappedInTransactionProxy() { + void bindToSupportedCacheWrappedInTransactionProxy() { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); assertThat(registrar.bindCacheToRegistry( @@ -55,7 +55,7 @@ public class CacheMetricsRegistrarTests { } @Test - public void bindToUnsupportedCache() { + void bindToUnsupportedCache() { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.emptyList()); assertThat(registrar.bindCacheToRegistry(new CaffeineCache("test", Caffeine.newBuilder().build()))).isFalse(); assertThat(this.meterRegistry.find("cache.gets").tags("name", "test").meter()).isNull(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java index 7727ea7238c..187d5c2f03d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CaffeineCacheMeterBinderProviderTests.java @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CaffeineCacheMeterBinderProviderTests { +class CaffeineCacheMeterBinderProviderTests { @Test - public void caffeineCacheProvider() { + void caffeineCacheProvider() { CaffeineCache cache = new CaffeineCache("test", Caffeine.newBuilder().build()); MeterBinder meterBinder = new CaffeineCacheMeterBinderProvider().getMeterBinder(cache, Collections.emptyList()); assertThat(meterBinder).isInstanceOf(CaffeineCacheMetrics.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java index 61913206f6b..c67750074a8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/EhCache2CacheMeterBinderProviderTests.java @@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class EhCache2CacheMeterBinderProviderTests { +class EhCache2CacheMeterBinderProviderTests { @Test - public void ehCache2CacheProvider() { + void ehCache2CacheProvider() { CacheManager cacheManager = new CacheManager( new Configuration().name("EhCacheCacheTests").defaultCache(new CacheConfiguration("default", 100))); try { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java index 77e8af5f2f8..6bd2b383cf7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java @@ -33,11 +33,11 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class HazelcastCacheMeterBinderProviderTests { +class HazelcastCacheMeterBinderProviderTests { @SuppressWarnings("unchecked") @Test - public void hazelcastCacheProvider() { + void hazelcastCacheProvider() { IMap nativeCache = mock(IMap.class); given(nativeCache.getName()).willReturn("test"); HazelcastCache cache = new HazelcastCache(nativeCache); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java index 8a794374fdb..2e1b97ad955 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/JCacheCacheMeterBinderProviderTests.java @@ -39,13 +39,13 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll */ @ExtendWith(MockitoExtension.class) -public class JCacheCacheMeterBinderProviderTests { +class JCacheCacheMeterBinderProviderTests { @Mock private javax.cache.Cache nativeCache; @Test - public void jCacheCacheProvider() throws URISyntaxException { + void jCacheCacheProvider() throws URISyntaxException { javax.cache.CacheManager cacheManager = mock(javax.cache.CacheManager.class); given(cacheManager.getURI()).willReturn(new URI("/test")); given(this.nativeCache.getCacheManager()).willReturn(cacheManager); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java index 8c62e6b5ce4..b841bad3953 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java @@ -51,7 +51,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class PrometheusPushGatewayManagerTests { +class PrometheusPushGatewayManagerTests { @Mock private PushGateway pushGateway; @@ -78,41 +78,41 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void createWhenPushGatewayIsNullThrowsException() { + void createWhenPushGatewayIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, null)) .withMessage("PushGateway must not be null"); } @Test - public void createWhenCollectorRegistryIsNullThrowsException() { + void createWhenCollectorRegistryIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, this.scheduler, this.pushRate, "job", this.groupingKey, null)).withMessage("Registry must not be null"); } @Test - public void createWhenSchedulerIsNullThrowsException() { + void createWhenSchedulerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, null, this.pushRate, "job", this.groupingKey, null)) .withMessage("Scheduler must not be null"); } @Test - public void createWhenPushRateIsNullThrowsException() { + void createWhenPushRateIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, null, "job", this.groupingKey, null)) .withMessage("PushRate must not be null"); } @Test - public void createWhenJobIsEmptyThrowsException() { + void createWhenJobIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "", this.groupingKey, null)) .withMessage("Job must not be empty"); } @Test - public void createShouldSchedulePushAsFixedRate() throws Exception { + void createShouldSchedulePushAsFixedRate() throws Exception { new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, null); verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); @@ -121,7 +121,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void shutdownWhenOwnsSchedulerDoesShutdownScheduler() { + void shutdownWhenOwnsSchedulerDoesShutdownScheduler() { PushGatewayTaskScheduler ownedScheduler = mockScheduler(PushGatewayTaskScheduler.class); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, ownedScheduler, this.pushRate, "job", this.groupingKey, null); @@ -130,7 +130,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void shutdownWhenDoesNotOwnSchedulerDoesNotShutdownScheduler() { + void shutdownWhenDoesNotOwnSchedulerDoesNotShutdownScheduler() { ThreadPoolTaskScheduler otherScheduler = mockScheduler(ThreadPoolTaskScheduler.class); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, otherScheduler, this.pushRate, "job", this.groupingKey, null); @@ -139,7 +139,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void shutdownWhenShutdownOperationIsPushPerformsPushOnShutdown() throws Exception { + void shutdownWhenShutdownOperationIsPushPerformsPushOnShutdown() throws Exception { PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.PUSH); manager.shutdown(); @@ -148,7 +148,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void shutdownWhenShutdownOperationIsDeletePerformsDeleteOnShutdown() throws Exception { + void shutdownWhenShutdownOperationIsDeletePerformsDeleteOnShutdown() throws Exception { PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.DELETE); manager.shutdown(); @@ -157,7 +157,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void shutdownWhenShutdownOperationIsNoneDoesNothing() { + void shutdownWhenShutdownOperationIsNoneDoesNothing() { PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.NONE); manager.shutdown(); @@ -166,7 +166,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void pushWhenUnknownHostExceptionIsThrownDoesShutdown() throws Exception { + void pushWhenUnknownHostExceptionIsThrownDoesShutdown() throws Exception { new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, null); verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); @@ -177,7 +177,7 @@ public class PrometheusPushGatewayManagerTests { } @Test - public void pushDoesNotThrowException() throws Exception { + void pushDoesNotThrowException() throws Exception { new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, null); verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java index 6ff8cfd946c..0e519b8e4fe 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java @@ -21,10 +21,8 @@ import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.exporter.common.TextFormat; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -35,13 +33,10 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Jon Schneider */ -@RunWith(WebEndpointRunners.class) -public class PrometheusScrapeEndpointIntegrationTests { +class PrometheusScrapeEndpointIntegrationTests { - private static WebTestClient client; - - @Test - public void scrapeHasContentTypeText004() { + @WebEndpointTest + void scrapeHasContentTypeText004(WebTestClient client) { client.get().uri("/actuator/prometheus").exchange().expectStatus().isOk().expectHeader() .contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java index 97e5a729d5c..34764a4053d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java @@ -38,10 +38,10 @@ import org.springframework.context.annotation.Configuration; * @author Jon Schneider * @author Andy Wilkinson */ -public class DataSourcePoolMetricsTests { +class DataSourcePoolMetricsTests { @Test - public void dataSourceIsInstrumented() { + void dataSourceIsInstrumented() { new ApplicationContextRunner().withUserConfiguration(DataSourceConfig.class, MetricsApp.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java index cc8567d86f4..acfda13ab79 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/MetricsRestTemplateCustomizerTests.java @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Jon Schneider * @author Brian Clozel */ -public class MetricsRestTemplateCustomizerTests { +class MetricsRestTemplateCustomizerTests { private MeterRegistry registry; @@ -64,7 +64,7 @@ public class MetricsRestTemplateCustomizerTests { } @Test - public void interceptRestTemplate() { + void interceptRestTemplate() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); @@ -78,7 +78,7 @@ public class MetricsRestTemplateCustomizerTests { } @Test - public void avoidDuplicateRegistration() { + void avoidDuplicateRegistration() { this.customizer.customize(this.restTemplate); assertThat(this.restTemplate.getInterceptors()).hasSize(1); this.customizer.customize(this.restTemplate); @@ -86,7 +86,7 @@ public class MetricsRestTemplateCustomizerTests { } @Test - public void normalizeUriToContainLeadingSlash() { + void normalizeUriToContainLeadingSlash() { this.mockServer.expect(MockRestRequestMatchers.requestTo("/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); @@ -97,7 +97,7 @@ public class MetricsRestTemplateCustomizerTests { } @Test - public void interceptRestTemplateWithUri() throws URISyntaxException { + void interceptRestTemplateWithUri() throws URISyntaxException { this.mockServer.expect(MockRestRequestMatchers.requestTo("http://localhost/test/123")) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(MockRestResponseCreators.withSuccess("OK", MediaType.APPLICATION_JSON)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java index 5d9348a26af..02493390832 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/RestTemplateExchangeTagsTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.actuate.metrics.web.client; import java.io.IOException; import io.micrometer.core.instrument.Tag; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; @@ -35,51 +35,51 @@ import static org.mockito.Mockito.mock; * @author Nishant Raut * @author Brian Clozel */ -public class RestTemplateExchangeTagsTests { +class RestTemplateExchangeTagsTests { @Test - public void outcomeTagIsUnknownWhenResponseIsNull() { + void outcomeTagIsUnknownWhenResponseIsNull() { Tag tag = RestTemplateExchangeTags.outcome(null); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); } @Test - public void outcomeTagIsInformationalWhenResponseIs1xx() { + void outcomeTagIsInformationalWhenResponseIs1xx() { ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.CONTINUE); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("INFORMATIONAL"); } @Test - public void outcomeTagIsSuccessWhenResponseIs2xx() { + void outcomeTagIsSuccessWhenResponseIs2xx() { ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.OK); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("SUCCESS"); } @Test - public void outcomeTagIsRedirectionWhenResponseIs3xx() { + void outcomeTagIsRedirectionWhenResponseIs3xx() { ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.MOVED_PERMANENTLY); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void outcomeTagIsClientErrorWhenResponseIs4xx() { + void outcomeTagIsClientErrorWhenResponseIs4xx() { ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.BAD_REQUEST); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("CLIENT_ERROR"); } @Test - public void outcomeTagIsServerErrorWhenResponseIs5xx() { + void outcomeTagIsServerErrorWhenResponseIs5xx() { ClientHttpResponse response = new MockClientHttpResponse("foo".getBytes(), HttpStatus.BAD_GATEWAY); Tag tag = RestTemplateExchangeTags.outcome(response); assertThat(tag.getValue()).isEqualTo("SERVER_ERROR"); } @Test - public void outcomeTagIsUnknownWhenResponseThrowsIOException() throws Exception { + void outcomeTagIsUnknownWhenResponseThrowsIOException() throws Exception { ClientHttpResponse response = mock(ClientHttpResponse.class); given(response.getStatusCode()).willThrow(IOException.class); Tag tag = RestTemplateExchangeTags.outcome(response); @@ -87,7 +87,7 @@ public class RestTemplateExchangeTagsTests { } @Test - public void outcomeTagIsUnknownForCustomResponseStatus() throws Exception { + void outcomeTagIsUnknownForCustomResponseStatus() throws Exception { ClientHttpResponse response = mock(ClientHttpResponse.class); given(response.getStatusCode()).willThrow(IllegalArgumentException.class); Tag tag = RestTemplateExchangeTags.outcome(response); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java index 21c8de5262d..1de116f44cf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Nishant Raut */ -public class DefaultWebClientExchangeTagsProviderTests { +class DefaultWebClientExchangeTagsProviderTests { private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; @@ -58,14 +58,14 @@ public class DefaultWebClientExchangeTagsProviderTests { } @Test - public void tagsShouldBePopulated() { + void tagsShouldBePopulated() { Iterable tags = this.tagsProvider.tags(this.request, this.response, null); assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); } @Test - public void tagsWhenNoUriTemplateShouldProvideUriPath() { + void tagsWhenNoUriTemplateShouldProvideUriPath() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")).build(); Iterable tags = this.tagsProvider.tags(request, this.response, null); @@ -74,14 +74,14 @@ public class DefaultWebClientExchangeTagsProviderTests { } @Test - public void tagsWhenIoExceptionShouldReturnIoErrorStatus() { + void tagsWhenIoExceptionShouldReturnIoErrorStatus() { Iterable tags = this.tagsProvider.tags(this.request, null, new IOException()); assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), Tag.of("status", "IO_ERROR")); } @Test - public void tagsWhenExceptionShouldReturnClientErrorStatus() { + void tagsWhenExceptionShouldReturnClientErrorStatus() { Iterable tags = this.tagsProvider.tags(this.request, null, new IllegalArgumentException()); assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/{project}"), Tag.of("clientName", "example.org"), Tag.of("status", "CLIENT_ERROR")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java index 1899ddc1546..372758a3e8e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientCustomizerTests.java @@ -31,7 +31,7 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class MetricsWebClientCustomizerTests { +class MetricsWebClientCustomizerTests { private MetricsWebClientCustomizer customizer; @@ -45,7 +45,7 @@ public class MetricsWebClientCustomizerTests { } @Test - public void customizeShouldAddFilterFunction() { + void customizeShouldAddFilterFunction() { this.clientBuilder.filter(mock(ExchangeFilterFunction.class)); this.customizer.customize(this.clientBuilder); this.clientBuilder.filters( @@ -53,7 +53,7 @@ public class MetricsWebClientCustomizerTests { } @Test - public void customizeShouldNotAddDuplicateFilterFunction() { + void customizeShouldNotAddDuplicateFilterFunction() { this.customizer.customize(this.clientBuilder); this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(1)); this.customizer.customize(this.clientBuilder); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java index 145f30892b2..70b53d80548 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/MetricsWebClientFilterFunctionTests.java @@ -47,7 +47,7 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class MetricsWebClientFilterFunctionTests { +class MetricsWebClientFilterFunctionTests { private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; @@ -69,7 +69,7 @@ public class MetricsWebClientFilterFunctionTests { } @Test - public void filterShouldRecordTimer() { + void filterShouldRecordTimer() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); given(this.response.statusCode()).willReturn(HttpStatus.OK); @@ -79,7 +79,7 @@ public class MetricsWebClientFilterFunctionTests { } @Test - public void filterWhenUriTemplatePresentShouldRecordTimer() { + void filterWhenUriTemplatePresentShouldRecordTimer() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")) .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); @@ -90,7 +90,7 @@ public class MetricsWebClientFilterFunctionTests { } @Test - public void filterWhenIoExceptionThrownShouldRecordTimer() { + void filterWhenIoExceptionThrownShouldRecordTimer() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction errorExchange = (r) -> Mono.error(new IOException()); @@ -102,7 +102,7 @@ public class MetricsWebClientFilterFunctionTests { } @Test - public void filterWhenExceptionThrownShouldRecordTimer() { + void filterWhenExceptionThrownShouldRecordTimer() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()); @@ -114,7 +114,7 @@ public class MetricsWebClientFilterFunctionTests { } @Test - public void filterWhenExceptionAndRetryShouldNotCumulateRecordTime() { + void filterWhenExceptionAndRetryShouldNotCumulateRecordTime() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://example.com/projects/spring-boot")).build(); ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException()) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java index c438e19ae6a..4b126643539 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Nishant Raut */ -public class WebClientExchangeTagsTests { +class WebClientExchangeTagsTests { private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; @@ -56,93 +56,93 @@ public class WebClientExchangeTagsTests { } @Test - public void method() { + void method() { assertThat(WebClientExchangeTags.method(this.request)).isEqualTo(Tag.of("method", "GET")); } @Test - public void uriWhenAbsoluteTemplateIsAvailableShouldReturnTemplate() { + void uriWhenAbsoluteTemplateIsAvailableShouldReturnTemplate() { assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test - public void uriWhenRelativeTemplateIsAvailableShouldReturnTemplate() { + void uriWhenRelativeTemplateIsAvailableShouldReturnTemplate() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test - public void uriWhenTemplateIsMissingShouldReturnPath() { + void uriWhenTemplateIsMissingShouldReturnPath() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) .build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/spring-boot")); } @Test - public void clientName() { + void clientName() { assertThat(WebClientExchangeTags.clientName(this.request)).isEqualTo(Tag.of("clientName", "example.org")); } @Test - public void status() { + void status() { assertThat(WebClientExchangeTags.status(this.response)).isEqualTo(Tag.of("status", "200")); } @Test - public void statusWhenIOException() { + void statusWhenIOException() { assertThat(WebClientExchangeTags.status(new IOException())).isEqualTo(Tag.of("status", "IO_ERROR")); } @Test - public void statusWhenClientException() { + void statusWhenClientException() { assertThat(WebClientExchangeTags.status(new IllegalArgumentException())) .isEqualTo(Tag.of("status", "CLIENT_ERROR")); } @Test - public void outcomeTagIsUnknownWhenResponseIsNull() { + void outcomeTagIsUnknownWhenResponseIsNull() { Tag tag = WebClientExchangeTags.outcome(null); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); } @Test - public void outcomeTagIsInformationalWhenResponseIs1xx() { + void outcomeTagIsInformationalWhenResponseIs1xx() { given(this.response.statusCode()).willReturn(HttpStatus.CONTINUE); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("INFORMATIONAL"); } @Test - public void outcomeTagIsSuccessWhenResponseIs2xx() { + void outcomeTagIsSuccessWhenResponseIs2xx() { given(this.response.statusCode()).willReturn(HttpStatus.OK); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("SUCCESS"); } @Test - public void outcomeTagIsRedirectionWhenResponseIs3xx() { + void outcomeTagIsRedirectionWhenResponseIs3xx() { given(this.response.statusCode()).willReturn(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void outcomeTagIsClientErrorWhenResponseIs4xx() { + void outcomeTagIsClientErrorWhenResponseIs4xx() { given(this.response.statusCode()).willReturn(HttpStatus.BAD_REQUEST); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("CLIENT_ERROR"); } @Test - public void outcomeTagIsServerErrorWhenResponseIs5xx() { + void outcomeTagIsServerErrorWhenResponseIs5xx() { given(this.response.statusCode()).willReturn(HttpStatus.BAD_GATEWAY); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("SERVER_ERROR"); } @Test - public void outcomeTagIsUnknownWhenResponseStatusIsUnknown() { + void outcomeTagIsUnknownWhenResponseStatusIsUnknown() { given(this.response.statusCode()).willThrow(IllegalArgumentException.class); Tag tag = WebClientExchangeTags.outcome(this.response); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java index 112b5e17903..4ead61c21a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilterTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class MetricsWebFilterTests { +class MetricsWebFilterTests { private static final String REQUEST_METRICS_NAME = "http.server.requests"; @@ -55,7 +55,7 @@ public class MetricsWebFilterTests { } @Test - public void filterAddsTagsToRegistry() { + void filterAddsTagsToRegistry() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> exchange.getResponse().setComplete()) .block(Duration.ofSeconds(30)); @@ -64,7 +64,7 @@ public class MetricsWebFilterTests { } @Test - public void filterAddsTagsToRegistryForExceptions() { + void filterAddsTagsToRegistryForExceptions() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> Mono.error(new IllegalStateException("test error"))) .onErrorResume((t) -> { @@ -77,7 +77,7 @@ public class MetricsWebFilterTests { } @Test - public void filterAddsNonEmptyTagsToRegistryForAnonymousExceptions() { + void filterAddsNonEmptyTagsToRegistryForAnonymousExceptions() { final Exception anonymous = new Exception("test error") { }; @@ -92,7 +92,7 @@ public class MetricsWebFilterTests { } @Test - public void filterAddsTagsToRegistryForExceptionsAndCommittedResponse() { + void filterAddsTagsToRegistryForExceptionsAndCommittedResponse() { MockServerWebExchange exchange = createExchange("/projects/spring-boot", "/projects/{project}"); this.webFilter.filter(exchange, (serverWebExchange) -> { exchange.getResponse().setStatusCodeValue(500); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java index 26db50cdfe1..8612a0a7f38 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Michael McFadyen */ -public class WebFluxTagsTests { +class WebFluxTagsTests { private MockServerWebExchange exchange; @@ -50,7 +50,7 @@ public class WebFluxTagsTests { } @Test - public void uriTagValueIsBestMatchingPatternWhenAvailable() { + void uriTagValueIsBestMatchingPatternWhenAvailable() { this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring")); this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.uri(this.exchange); @@ -58,34 +58,34 @@ public class WebFluxTagsTests { } @Test - public void uriTagValueIsRedirectionWhenResponseStatusIs3xx() { + void uriTagValueIsRedirectionWhenResponseStatusIs3xx() { this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void uriTagValueIsNotFoundWhenResponseStatusIs404() { + void uriTagValueIsNotFoundWhenResponseStatusIs404() { this.exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("NOT_FOUND"); } @Test - public void uriTagToleratesCustomResponseStatus() { + void uriTagToleratesCustomResponseStatus() { this.exchange.getResponse().setStatusCodeValue(601); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("root"); } @Test - public void uriTagValueIsRootWhenRequestHasNoPatternOrPathInfo() { + void uriTagValueIsRootWhenRequestHasNoPatternOrPathInfo() { Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("root"); } @Test - public void uriTagValueIsRootWhenRequestHasNoPatternAndSlashPathInfo() { + void uriTagValueIsRootWhenRequestHasNoPatternAndSlashPathInfo() { MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); ServerWebExchange exchange = MockServerWebExchange.from(request); Tag tag = WebFluxTags.uri(exchange); @@ -93,7 +93,7 @@ public class WebFluxTagsTests { } @Test - public void uriTagValueIsUnknownWhenRequestHasNoPatternAndNonRootPathInfo() { + void uriTagValueIsUnknownWhenRequestHasNoPatternAndNonRootPathInfo() { MockServerHttpRequest request = MockServerHttpRequest.get("/example").build(); ServerWebExchange exchange = MockServerWebExchange.from(request); Tag tag = WebFluxTags.uri(exchange); @@ -101,7 +101,7 @@ public class WebFluxTagsTests { } @Test - public void methodTagToleratesNonStandardHttpMethods() { + void methodTagToleratesNonStandardHttpMethods() { ServerWebExchange exchange = mock(ServerWebExchange.class); ServerHttpRequest request = mock(ServerHttpRequest.class); given(exchange.getRequest()).willReturn(request); @@ -111,42 +111,42 @@ public class WebFluxTagsTests { } @Test - public void outcomeTagIsUnknownWhenResponseStatusIsNull() { + void outcomeTagIsUnknownWhenResponseStatusIsNull() { this.exchange.getResponse().setStatusCode(null); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("UNKNOWN"); } @Test - public void outcomeTagIsInformationalWhenResponseIs1xx() { + void outcomeTagIsInformationalWhenResponseIs1xx() { this.exchange.getResponse().setStatusCode(HttpStatus.CONTINUE); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("INFORMATIONAL"); } @Test - public void outcomeTagIsSuccessWhenResponseIs2xx() { + void outcomeTagIsSuccessWhenResponseIs2xx() { this.exchange.getResponse().setStatusCode(HttpStatus.OK); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("SUCCESS"); } @Test - public void outcomeTagIsRedirectionWhenResponseIs3xx() { + void outcomeTagIsRedirectionWhenResponseIs3xx() { this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("REDIRECTION"); } @Test - public void outcomeTagIsClientErrorWhenResponseIs4xx() { + void outcomeTagIsClientErrorWhenResponseIs4xx() { this.exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("CLIENT_ERROR"); } @Test - public void outcomeTagIsServerErrorWhenResponseIs5xx() { + void outcomeTagIsServerErrorWhenResponseIs5xx() { this.exchange.getResponse().setStatusCode(HttpStatus.BAD_GATEWAY); Tag tag = WebFluxTags.outcome(this.exchange); assertThat(tag.getValue()).isEqualTo("SERVER_ERROR"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java index c185ef716d8..8e59bbbb026 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptorTests.java @@ -65,7 +65,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @ExtendWith(SpringExtension.class) @WebAppConfiguration -public class LongTaskTimingHandlerInterceptorTests { +class LongTaskTimingHandlerInterceptorTests { @Autowired private SimpleMeterRegistry registry; @@ -84,7 +84,7 @@ public class LongTaskTimingHandlerInterceptorTests { } @Test - public void asyncRequestThatThrowsUncheckedException() throws Exception { + void asyncRequestThatThrowsUncheckedException() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/completableFutureException")) .andExpect(request().asyncStarted()).andReturn(); assertThat(this.registry.get("my.long.request.exception").longTaskTimer().activeTasks()).isEqualTo(1); @@ -95,7 +95,7 @@ public class LongTaskTimingHandlerInterceptorTests { } @Test - public void asyncCallableRequest() throws Exception { + void asyncCallableRequest() throws Exception { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java index c74649e8463..68b28fb2cc7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterAutoTimedTests.java @@ -54,7 +54,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @ExtendWith(SpringExtension.class) @WebAppConfiguration -public class WebMvcMetricsFilterAutoTimedTests { +class WebMvcMetricsFilterAutoTimedTests { @Autowired private MeterRegistry registry; @@ -73,7 +73,7 @@ public class WebMvcMetricsFilterAutoTimedTests { } @Test - public void metricsCanBeAutoTimed() throws Exception { + void metricsCanBeAutoTimed() throws Exception { this.mvc.perform(get("/api/10")).andExpect(status().isOk()); Timer timer = this.registry.get("http.server.requests").tags("status", "200").timer(); assertThat(timer.count()).isEqualTo(1L); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java index 1724f25060d..cf7776aeaab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilterTests.java @@ -96,7 +96,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @ExtendWith(SpringExtension.class) @WebAppConfiguration -public class WebMvcMetricsFilterTests { +class WebMvcMetricsFilterTests { @Autowired private SimpleMeterRegistry registry; @@ -127,39 +127,39 @@ public class WebMvcMetricsFilterTests { } @Test - public void timedMethod() throws Exception { + void timedMethod() throws Exception { this.mvc.perform(get("/api/c1/10")).andExpect(status().isOk()); assertThat(this.registry.get("http.server.requests") .tags("status", "200", "uri", "/api/c1/{id}", "public", "true").timer().count()).isEqualTo(1); } @Test - public void subclassedTimedMethod() throws Exception { + void subclassedTimedMethod() throws Exception { this.mvc.perform(get("/api/c1/metaTimed/10")).andExpect(status().isOk()); assertThat(this.registry.get("http.server.requests").tags("status", "200", "uri", "/api/c1/metaTimed/{id}") .timer().count()).isEqualTo(1L); } @Test - public void untimedMethod() throws Exception { + void untimedMethod() throws Exception { this.mvc.perform(get("/api/c1/untimed/10")).andExpect(status().isOk()); assertThat(this.registry.find("http.server.requests").tags("uri", "/api/c1/untimed/10").timer()).isNull(); } @Test - public void timedControllerClass() throws Exception { + void timedControllerClass() throws Exception { this.mvc.perform(get("/api/c2/10")).andExpect(status().isOk()); assertThat(this.registry.get("http.server.requests").tags("status", "200").timer().count()).isEqualTo(1L); } @Test - public void badClientRequest() throws Exception { + void badClientRequest() throws Exception { this.mvc.perform(get("/api/c1/oops")).andExpect(status().is4xxClientError()); assertThat(this.registry.get("http.server.requests").tags("status", "400").timer().count()).isEqualTo(1L); } @Test - public void redirectRequest() throws Exception { + void redirectRequest() throws Exception { this.mvc.perform(get("/api/redirect").header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "302")) .andExpect(status().is3xxRedirection()); assertThat(this.registry.get("http.server.requests").tags("uri", "REDIRECTION").tags("status", "302").timer()) @@ -167,7 +167,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void notFoundRequest() throws Exception { + void notFoundRequest() throws Exception { this.mvc.perform(get("/api/not/found").header(RedirectAndNotFoundFilter.TEST_MISBEHAVE_HEADER, "404")) .andExpect(status().is4xxClientError()); assertThat(this.registry.get("http.server.requests").tags("uri", "NOT_FOUND").tags("status", "404").timer()) @@ -175,7 +175,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void unhandledError() { + void unhandledError() { assertThatCode(() -> this.mvc.perform(get("/api/c1/unhandledError/10")).andExpect(status().isOk())) .hasRootCauseInstanceOf(RuntimeException.class); assertThat(this.registry.get("http.server.requests").tags("exception", "RuntimeException").timer().count()) @@ -183,7 +183,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void streamingError() throws Exception { + void streamingError() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/streamingError")).andExpect(request().asyncStarted()) .andReturn(); assertThatCode(() -> this.mvc.perform(asyncDispatch(result)).andExpect(status().isOk())); @@ -192,7 +192,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void anonymousError() { + void anonymousError() { try { this.mvc.perform(get("/api/c1/anonymousError/10")); } @@ -203,7 +203,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void asyncCallableRequest() throws Exception { + void asyncCallableRequest() throws Exception { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { @@ -228,7 +228,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void asyncRequestThatThrowsUncheckedException() throws Exception { + void asyncRequestThatThrowsUncheckedException() throws Exception { MvcResult result = this.mvc.perform(get("/api/c1/completableFutureException")) .andExpect(request().asyncStarted()).andReturn(); assertThatExceptionOfType(NestedServletException.class) @@ -239,7 +239,7 @@ public class WebMvcMetricsFilterTests { } @Test - public void asyncCompletableFutureRequest() throws Exception { + void asyncCompletableFutureRequest() throws Exception { AtomicReference result = new AtomicReference<>(); Thread backgroundRequest = new Thread(() -> { try { @@ -261,13 +261,13 @@ public class WebMvcMetricsFilterTests { } @Test - public void endpointThrowsError() throws Exception { + void endpointThrowsError() throws Exception { this.mvc.perform(get("/api/c1/error/10")).andExpect(status().is4xxClientError()); assertThat(this.registry.get("http.server.requests").tags("status", "422").timer().count()).isEqualTo(1L); } @Test - public void regexBasedRequestMapping() throws Exception { + void regexBasedRequestMapping() throws Exception { this.mvc.perform(get("/api/c1/regex/.abc")).andExpect(status().isOk()); assertThat( this.registry.get("http.server.requests").tags("uri", "/api/c1/regex/{id:\\.[a-z]+}").timer().count()) @@ -275,14 +275,14 @@ public class WebMvcMetricsFilterTests { } @Test - public void recordQuantiles() throws Exception { + void recordQuantiles() throws Exception { this.mvc.perform(get("/api/c1/percentiles/10")).andExpect(status().isOk()); assertThat(this.prometheusRegistry.scrape()).contains("quantile=\"0.5\""); assertThat(this.prometheusRegistry.scrape()).contains("quantile=\"0.95\""); } @Test - public void recordHistogram() throws Exception { + void recordHistogram() throws Exception { this.mvc.perform(get("/api/c1/histogram/10")).andExpect(status().isOk()); assertThat(this.prometheusRegistry.scrape()).contains("le=\"0.001\""); assertThat(this.prometheusRegistry.scrape()).contains("le=\"30.0\""); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java index 7353fce9bb0..27164399872 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsIntegrationTests.java @@ -58,7 +58,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @ExtendWith(SpringExtension.class) @WebAppConfiguration @TestPropertySource(properties = "security.ignored=/**") -public class WebMvcMetricsIntegrationTests { +class WebMvcMetricsIntegrationTests { @Autowired private WebApplicationContext context; @@ -77,14 +77,14 @@ public class WebMvcMetricsIntegrationTests { } @Test - public void handledExceptionIsRecordedInMetricTag() throws Exception { + void handledExceptionIsRecordedInMetricTag() throws Exception { this.mvc.perform(get("/api/handledError")).andExpect(status().is5xxServerError()); assertThat(this.registry.get("http.server.requests").tags("exception", "Exception1", "status", "500").timer() .count()).isEqualTo(1L); } @Test - public void rethrownExceptionIsRecordedInMetricTag() { + void rethrownExceptionIsRecordedInMetricTag() { assertThatCode(() -> this.mvc.perform(get("/api/rethrownError")).andExpect(status().is5xxServerError())); assertThat(this.registry.get("http.server.requests").tags("exception", "Exception2", "status", "500").timer() .count()).isEqualTo(1L); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java index 669d53e3982..6b3537ffaa7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoHealthIndicatorTests.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; * * @author Christian Dupuis */ -public class MongoHealthIndicatorTests { +class MongoHealthIndicatorTests { private AnnotationConfigApplicationContext context; @@ -48,7 +48,7 @@ public class MongoHealthIndicatorTests { } @Test - public void mongoIsUp() { + void mongoIsUp() { Document commandResult = mock(Document.class); given(commandResult.getString("version")).willReturn("2.6.4"); MongoTemplate mongoTemplate = mock(MongoTemplate.class); @@ -62,7 +62,7 @@ public class MongoHealthIndicatorTests { } @Test - public void mongoIsDown() { + void mongoIsDown() { MongoTemplate mongoTemplate = mock(MongoTemplate.class); given(mongoTemplate.executeCommand("{ buildInfo: 1 }")).willThrow(new MongoException("Connection failed")); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java index 761ff40fba0..582dc58507d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java @@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock; * * @author Yulin Qin */ -public class MongoReactiveHealthIndicatorTests { +class MongoReactiveHealthIndicatorTests { @Test - public void testMongoIsUp() { + void testMongoIsUp() { Document buildInfo = mock(Document.class); given(buildInfo.getString("version")).willReturn("2.6.4"); ReactiveMongoTemplate reactiveMongoTemplate = mock(ReactiveMongoTemplate.class); @@ -54,7 +54,7 @@ public class MongoReactiveHealthIndicatorTests { } @Test - public void testMongoIsDown() { + void testMongoIsDown() { ReactiveMongoTemplate reactiveMongoTemplate = mock(ReactiveMongoTemplate.class); given(reactiveMongoTemplate.executeCommand("{ buildInfo: 1 }")) .willThrow(new MongoException("Connection failed")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java index 46c9c74dd20..9fd25b1a805 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicatorTests.java @@ -22,7 +22,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Assert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.neo4j.ogm.exception.CypherException; @@ -44,7 +43,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Michael Simons */ -public class Neo4jHealthIndicatorTests { +class Neo4jHealthIndicatorTests { private Session session; @@ -59,7 +58,7 @@ public class Neo4jHealthIndicatorTests { } @Test - public void neo4jUp() { + void neo4jUp() { Result result = mock(Result.class); given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())).willReturn(result); int nodeCount = 500; @@ -72,11 +71,11 @@ public class Neo4jHealthIndicatorTests { assertThat(health.getStatus()).isEqualTo(Status.UP); Map details = health.getDetails(); int nodeCountFromDetails = (int) details.get("nodes"); - Assert.assertEquals(nodeCount, nodeCountFromDetails); + assertThat(nodeCountFromDetails).isEqualTo(nodeCount); } @Test - public void neo4jDown() { + void neo4jDown() { CypherException cypherException = new CypherException("Neo.ClientError.Statement.SyntaxError", "Error executing Cypher"); given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())).willThrow(cypherException); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java index bd887a27a69..78c47a063ab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisHealthIndicatorTests.java @@ -44,10 +44,10 @@ import static org.mockito.Mockito.verify; * @author Richard Santana * @author Stephane Nicoll */ -public class RedisHealthIndicatorTests { +class RedisHealthIndicatorTests { @Test - public void redisIsUp() { + void redisIsUp() { Properties info = new Properties(); info.put("redis_version", "2.8.9"); RedisConnection redisConnection = mock(RedisConnection.class); @@ -59,7 +59,7 @@ public class RedisHealthIndicatorTests { } @Test - public void redisIsDown() { + void redisIsDown() { RedisConnection redisConnection = mock(RedisConnection.class); given(redisConnection.info()).willThrow(new RedisConnectionFailureException("Connection failed")); RedisHealthIndicator healthIndicator = createHealthIndicator(redisConnection); @@ -75,7 +75,7 @@ public class RedisHealthIndicatorTests { } @Test - public void redisClusterIsUp() { + void redisClusterIsUp() { Properties clusterProperties = new Properties(); clusterProperties.setProperty("cluster_size", "4"); clusterProperties.setProperty("cluster_slots_ok", "4"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java index 305c9a092e8..6fcce879c30 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java @@ -43,10 +43,10 @@ import static org.mockito.Mockito.verify; * @author Nikolay Rybak * @author Artsiom Yudovin */ -public class RedisReactiveHealthIndicatorTests { +class RedisReactiveHealthIndicatorTests { @Test - public void redisIsUp() { + void redisIsUp() { Properties info = new Properties(); info.put("redis_version", "2.8.9"); ReactiveRedisConnection redisConnection = mock(ReactiveRedisConnection.class); @@ -64,7 +64,7 @@ public class RedisReactiveHealthIndicatorTests { } @Test - public void redisCommandIsDown() { + void redisCommandIsDown() { ReactiveServerCommands commands = mock(ReactiveServerCommands.class); given(commands.info()).willReturn(Mono.error(new RedisConnectionFailureException("Connection failed"))); ReactiveRedisConnection redisConnection = mock(ReactiveRedisConnection.class); @@ -77,7 +77,7 @@ public class RedisReactiveHealthIndicatorTests { } @Test - public void redisConnectionIsDown() { + void redisConnectionIsDown() { ReactiveRedisConnectionFactory redisConnectionFactory = mock(ReactiveRedisConnectionFactory.class); given(redisConnectionFactory.getReactiveConnection()) .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java index d08ce24675d..0baa43dbb05 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java @@ -47,13 +47,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ScheduledTasksEndpointTests { +class ScheduledTasksEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(BaseConfiguration.class); @Test - public void cronScheduledMethodIsReported() { + void cronScheduledMethodIsReported() { run(CronScheduledMethod.class, (tasks) -> { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getFixedRate()).isEmpty(); @@ -66,7 +66,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void cronTriggerIsReported() { + void cronTriggerIsReported() { run(CronTriggerTask.class, (tasks) -> { assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getFixedDelay()).isEmpty(); @@ -79,7 +79,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void fixedDelayScheduledMethodIsReported() { + void fixedDelayScheduledMethodIsReported() { run(FixedDelayScheduledMethod.class, (tasks) -> { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedRate()).isEmpty(); @@ -94,7 +94,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void fixedDelayTriggerIsReported() { + void fixedDelayTriggerIsReported() { run(FixedDelayTriggerTask.class, (tasks) -> { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedRate()).isEmpty(); @@ -108,7 +108,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void fixedRateScheduledMethodIsReported() { + void fixedRateScheduledMethodIsReported() { run(FixedRateScheduledMethod.class, (tasks) -> { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedDelay()).isEmpty(); @@ -123,7 +123,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void fixedRateTriggerIsReported() { + void fixedRateTriggerIsReported() { run(FixedRateTriggerTask.class, (tasks) -> { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedDelay()).isEmpty(); @@ -137,7 +137,7 @@ public class ScheduledTasksEndpointTests { } @Test - public void taskWithCustomTriggerIsReported() { + void taskWithCustomTriggerIsReported() { run(CustomTriggerTask.class, (tasks) -> { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedDelay()).isEmpty(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java index f1d2ebede30..3e33ce5cbcc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java @@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify; /** * Tests for {@link AuthenticationAuditListener}. */ -public class AuthenticationAuditListenerTests { +class AuthenticationAuditListenerTests { private final AuthenticationAuditListener listener = new AuthenticationAuditListener(); @@ -54,14 +54,14 @@ public class AuthenticationAuditListenerTests { } @Test - public void testAuthenticationSuccess() { + void testAuthenticationSuccess() { AuditApplicationEvent event = handleAuthenticationEvent( new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("user", "password"))); assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SUCCESS); } @Test - public void testOtherAuthenticationSuccess() { + void testOtherAuthenticationSuccess() { this.listener.onApplicationEvent(new InteractiveAuthenticationSuccessEvent( new UsernamePasswordAuthenticationToken("user", "password"), getClass())); // No need to audit this one (it shadows a regular AuthenticationSuccessEvent) @@ -69,14 +69,14 @@ public class AuthenticationAuditListenerTests { } @Test - public void testAuthenticationFailed() { + void testAuthenticationFailed() { AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent( new UsernamePasswordAuthenticationToken("user", "password"), new BadCredentialsException("Bad user"))); assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE); } @Test - public void testAuthenticationSwitch() { + void testAuthenticationSwitch() { AuditApplicationEvent event = handleAuthenticationEvent( new AuthenticationSwitchUserEvent(new UsernamePasswordAuthenticationToken("user", "password"), new User("user", "password", AuthorityUtils.commaSeparatedStringToAuthorityList("USER")))); @@ -84,14 +84,14 @@ public class AuthenticationAuditListenerTests { } @Test - public void testAuthenticationSwitchBackToAnonymous() { + void testAuthenticationSwitchBackToAnonymous() { AuditApplicationEvent event = handleAuthenticationEvent( new AuthenticationSwitchUserEvent(new UsernamePasswordAuthenticationToken("user", "password"), null)); assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); } @Test - public void testDetailsAreIncludedInAuditEvent() { + void testDetailsAreIncludedInAuditEvent() { Object details = new Object(); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", "password"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java index 2aee13e0072..4eadffbf24e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthorizationAuditListenerTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.verify; /** * Tests for {@link AuthorizationAuditListener}. */ -public class AuthorizationAuditListenerTests { +class AuthorizationAuditListenerTests { private final AuthorizationAuditListener listener = new AuthorizationAuditListener(); @@ -51,7 +51,7 @@ public class AuthorizationAuditListenerTests { } @Test - public void testAuthenticationCredentialsNotFound() { + void testAuthenticationCredentialsNotFound() { AuditApplicationEvent event = handleAuthorizationEvent( new AuthenticationCredentialsNotFoundEvent(this, Collections.singletonList(new SecurityConfig("USER")), new AuthenticationCredentialsNotFoundException("Bad user"))); @@ -59,7 +59,7 @@ public class AuthorizationAuditListenerTests { } @Test - public void testAuthorizationFailure() { + void testAuthorizationFailure() { AuditApplicationEvent event = handleAuthorizationEvent(new AuthorizationFailureEvent(this, Collections.singletonList(new SecurityConfig("USER")), new UsernamePasswordAuthenticationToken("user", "password"), new AccessDeniedException("Bad user"))); @@ -67,7 +67,7 @@ public class AuthorizationAuditListenerTests { } @Test - public void testDetailsAreIncludedInAuditEvent() { + void testDetailsAreIncludedInAuditEvent() { Object details = new Object(); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", "password"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java index bbf12c3996e..32a48b4abf2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.actuate.session; import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.session.SessionsEndpoint.SessionDescriptor; import org.springframework.session.FindByIndexNameSessionRepository; @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; * * @author Vedran Pavic */ -public class SessionsEndpointTests { +class SessionsEndpointTests { private static final Session session = new MapSession(); @@ -46,7 +46,7 @@ public class SessionsEndpointTests { private final SessionsEndpoint endpoint = new SessionsEndpoint(this.repository); @Test - public void sessionsForUsername() { + void sessionsForUsername() { given(this.repository.findByPrincipalName("user")) .willReturn(Collections.singletonMap(session.getId(), session)); List result = this.endpoint.sessionsForUsername("user").getSessions(); @@ -60,7 +60,7 @@ public class SessionsEndpointTests { } @Test - public void getSession() { + void getSession() { given(this.repository.findById(session.getId())).willReturn(session); SessionDescriptor result = this.endpoint.getSession(session.getId()); assertThat(result.getId()).isEqualTo(session.getId()); @@ -72,13 +72,13 @@ public class SessionsEndpointTests { } @Test - public void getSessionWithIdNotFound() { + void getSessionWithIdNotFound() { given(this.repository.findById("not-found")).willReturn(null); assertThat(this.endpoint.getSession("not-found")).isNull(); } @Test - public void deleteSession() { + void deleteSession() { this.endpoint.deleteSession(session.getId()); verify(this.repository).deleteById(session.getId()); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java index 0324e3dfca5..cfc466e7b66 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java @@ -19,10 +19,8 @@ package org.springframework.boot.actuate.session; import java.util.Collections; import net.minidev.json.JSONArray; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.actuate.endpoint.web.test.WebEndpointRunners; +import org.springframework.boot.actuate.endpoint.web.test.WebEndpointTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.session.FindByIndexNameSessionRepository; @@ -39,8 +37,7 @@ import static org.mockito.Mockito.mock; * * @author Vedran Pavic */ -@RunWith(WebEndpointRunners.class) -public class SessionsEndpointWebIntegrationTests { +class SessionsEndpointWebIntegrationTests { private static final Session session = new MapSession(); @@ -48,31 +45,29 @@ public class SessionsEndpointWebIntegrationTests { private static final FindByIndexNameSessionRepository repository = mock( FindByIndexNameSessionRepository.class); - private static WebTestClient client; - - @Test - public void sessionsForUsernameWithoutUsernameParam() { + @WebEndpointTest + void sessionsForUsernameWithoutUsernameParam(WebTestClient client) { client.get().uri((builder) -> builder.path("/actuator/sessions").build()).exchange().expectStatus() .isBadRequest(); } - @Test - public void sessionsForUsernameNoResults() { + @WebEndpointTest + void sessionsForUsernameNoResults(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.emptyMap()); client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("sessions").isEmpty(); } - @Test - public void sessionsForUsernameFound() { + @WebEndpointTest + void sessionsForUsernameFound(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.singletonMap(session.getId(), session)); client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) .exchange().expectStatus().isOk().expectBody().jsonPath("sessions.[*].id") .isEqualTo(new JSONArray().appendElement(session.getId())); } - @Test - public void sessionForIdNotFound() { + @WebEndpointTest + void sessionForIdNotFound(WebTestClient client) { client.get().uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()).exchange() .expectStatus().isNotFound(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java index c9dfac1236f..4858eec3a07 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/solr/SolrHealthIndicatorTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class SolrHealthIndicatorTests { +class SolrHealthIndicatorTests { private AnnotationConfigApplicationContext context; @@ -51,7 +51,7 @@ public class SolrHealthIndicatorTests { } @Test - public void solrIsUp() throws Exception { + void solrIsUp() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(0)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); @@ -61,7 +61,7 @@ public class SolrHealthIndicatorTests { } @Test - public void solrIsUpAndRequestFailed() throws Exception { + void solrIsUpAndRequestFailed() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(400)); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); @@ -71,7 +71,7 @@ public class SolrHealthIndicatorTests { } @Test - public void solrIsDown() throws Exception { + void solrIsDown() throws Exception { SolrClient solrClient = mock(SolrClient.class); given(solrClient.request(any(CoreAdminRequest.class), isNull())) .willThrow(new IOException("Connection failed")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java index 7b95e57f1c7..0ec408534ac 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java @@ -37,7 +37,7 @@ import static org.mockito.BDDMockito.given; * @author Mattias Severson * @author Stephane Nicoll */ -public class DiskSpaceHealthIndicatorTests { +class DiskSpaceHealthIndicatorTests { private static final DataSize THRESHOLD = DataSize.ofKilobytes(1); @@ -57,7 +57,7 @@ public class DiskSpaceHealthIndicatorTests { } @Test - public void diskSpaceIsUp() { + void diskSpaceIsUp() { long freeSpace = THRESHOLD.toBytes() + 10; given(this.fileMock.getUsableSpace()).willReturn(freeSpace); given(this.fileMock.getTotalSpace()).willReturn(TOTAL_SPACE.toBytes()); @@ -69,7 +69,7 @@ public class DiskSpaceHealthIndicatorTests { } @Test - public void diskSpaceIsDown() { + void diskSpaceIsDown() { long freeSpace = THRESHOLD.toBytes() - 10; given(this.fileMock.getUsableSpace()).willReturn(freeSpace); given(this.fileMock.getTotalSpace()).willReturn(TOTAL_SPACE.toBytes()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java index 6418fd385a2..f3b213f2ad1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracerTests.java @@ -41,52 +41,52 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class HttpExchangeTracerTests { +class HttpExchangeTracerTests { @Test - public void methodIsIncluded() { + void methodIsIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getMethod()).isEqualTo("GET"); } @Test - public void uriIsIncluded() { + void uriIsIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getUri()).isEqualTo(URI.create("https://api.example.com")); } @Test - public void remoteAddressIsNotIncludedByDefault() { + void remoteAddressIsNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getRemoteAddress()).isNull(); } @Test - public void remoteAddressCanBeIncluded() { + void remoteAddressCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REMOTE_ADDRESS)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test - public void requestHeadersAreNotIncludedByDefault() { + void requestHeadersAreNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.noneOf(Include.class)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getHeaders()).isEmpty(); } @Test - public void requestHeadersCanBeIncluded() { + void requestHeadersCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest(createRequest()); Request request = trace.getRequest(); assertThat(request.getHeaders()).containsOnlyKeys(HttpHeaders.ACCEPT); } @Test - public void requestHeadersCanBeCustomized() { + void requestHeadersCanBeCustomized() { MultiValueMap headers = new LinkedMultiValueMap<>(); headers.add("to-remove", "test"); headers.add("test", "value"); @@ -98,7 +98,7 @@ public class HttpExchangeTracerTests { } @Test - public void authorizationHeaderIsNotIncludedByDefault() { + void authorizationHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); Request request = trace.getRequest(); @@ -106,7 +106,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseAuthorizationHeaderIsNotIncludedByDefault() { + void mixedCaseAuthorizationHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( createRequest(Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); Request request = trace.getRequest(); @@ -114,7 +114,7 @@ public class HttpExchangeTracerTests { } @Test - public void authorizationHeaderCanBeIncluded() { + void authorizationHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) .receivedRequest( createRequest(Collections.singletonMap(HttpHeaders.AUTHORIZATION, Arrays.asList("secret")))); @@ -123,7 +123,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseAuthorizationHeaderCanBeIncluded() { + void mixedCaseAuthorizationHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER)) .receivedRequest(createRequest( Collections.singletonMap(mixedCase(HttpHeaders.AUTHORIZATION), Arrays.asList("secret")))); @@ -132,7 +132,7 @@ public class HttpExchangeTracerTests { } @Test - public void cookieHeaderIsNotIncludedByDefault() { + void cookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("test=test")))); Request request = trace.getRequest(); @@ -140,7 +140,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseCookieHeaderIsNotIncludedByDefault() { + void mixedCaseCookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS)).receivedRequest( createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); Request request = trace.getRequest(); @@ -148,7 +148,7 @@ public class HttpExchangeTracerTests { } @Test - public void cookieHeaderCanBeIncluded() { + void cookieHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) .receivedRequest(createRequest(Collections.singletonMap(HttpHeaders.COOKIE, Arrays.asList("value")))); Request request = trace.getRequest(); @@ -156,7 +156,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseCookieHeaderCanBeIncluded() { + void mixedCaseCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpExchangeTracer(EnumSet.of(Include.REQUEST_HEADERS, Include.COOKIE_HEADERS)) .receivedRequest( createRequest(Collections.singletonMap(mixedCase(HttpHeaders.COOKIE), Arrays.asList("value")))); @@ -165,21 +165,21 @@ public class HttpExchangeTracerTests { } @Test - public void statusIsIncluded() { + void statusIsIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getResponse().getStatus()).isEqualTo(204); } @Test - public void responseHeadersAreNotIncludedByDefault() { + void responseHeadersAreNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getResponse().getHeaders()).isEmpty(); } @Test - public void responseHeadersCanBeIncluded() { + void responseHeadersCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, createResponse(), null, null); @@ -187,7 +187,7 @@ public class HttpExchangeTracerTests { } @Test - public void setCookieHeaderIsNotIncludedByDefault() { + void setCookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, createResponse(Collections.singletonMap(HttpHeaders.SET_COOKIE, Arrays.asList("test=test"))), null, @@ -196,7 +196,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseSetCookieHeaderIsNotIncludedByDefault() { + void mixedCaseSetCookieHeaderIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS)).sendingResponse(trace, createResponse(Collections.singletonMap(mixedCase(HttpHeaders.SET_COOKIE), Arrays.asList("test=test"))), @@ -205,7 +205,7 @@ public class HttpExchangeTracerTests { } @Test - public void setCookieHeaderCanBeIncluded() { + void setCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)).sendingResponse(trace, createResponse(Collections.singletonMap(HttpHeaders.SET_COOKIE, Arrays.asList("test=test"))), null, @@ -214,7 +214,7 @@ public class HttpExchangeTracerTests { } @Test - public void mixedCaseSetCookieHeaderCanBeIncluded() { + void mixedCaseSetCookieHeaderCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS)).sendingResponse(trace, createResponse(Collections.singletonMap(mixedCase(HttpHeaders.SET_COOKIE), Arrays.asList("test=test"))), @@ -223,7 +223,7 @@ public class HttpExchangeTracerTests { } @Test - public void principalIsNotIncludedByDefault() { + void principalIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), this::createPrincipal, null); @@ -231,7 +231,7 @@ public class HttpExchangeTracerTests { } @Test - public void principalCanBeIncluded() { + void principalCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.PRINCIPAL)).sendingResponse(trace, createResponse(), this::createPrincipal, null); @@ -240,7 +240,7 @@ public class HttpExchangeTracerTests { } @Test - public void sessionIdIsNotIncludedByDefault() { + void sessionIdIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, () -> "sessionId"); @@ -248,7 +248,7 @@ public class HttpExchangeTracerTests { } @Test - public void sessionIdCanBeIncluded() { + void sessionIdCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.SESSION_ID)).sendingResponse(trace, createResponse(), null, () -> "sessionId"); @@ -257,14 +257,14 @@ public class HttpExchangeTracerTests { } @Test - public void timeTakenIsNotIncludedByDefault() { + void timeTakenIsNotIncludedByDefault() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getTimeTaken()).isNull(); } @Test - public void timeTakenCanBeIncluded() { + void timeTakenCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); new HttpExchangeTracer(EnumSet.of(Include.TIME_TAKEN)).sendingResponse(trace, createResponse(), null, null); assertThat(trace.getTimeTaken()).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpTraceEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpTraceEndpointTests.java index a5490e08fa7..dc347b8ea46 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpTraceEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/HttpTraceEndpointTests.java @@ -30,10 +30,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class HttpTraceEndpointTests { +class HttpTraceEndpointTests { @Test - public void trace() { + void trace() { HttpTraceRepository repository = new InMemoryHttpTraceRepository(); repository.add(new HttpTrace(createRequest("GET"))); List traces = new HttpTraceEndpoint(repository).traces().getTraces(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/InMemoryHttpTraceRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/InMemoryHttpTraceRepositoryTests.java index c5febf9c26b..e9e3df49a6a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/InMemoryHttpTraceRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/InMemoryHttpTraceRepositoryTests.java @@ -30,12 +30,12 @@ import static org.mockito.Mockito.mock; * @author Dave Syer * @author Andy Wilkinson */ -public class InMemoryHttpTraceRepositoryTests { +class InMemoryHttpTraceRepositoryTests { private final InMemoryHttpTraceRepository repository = new InMemoryHttpTraceRepository(); @Test - public void capacityLimited() { + void capacityLimited() { this.repository.setCapacity(2); this.repository.add(new HttpTrace(createRequest("GET"))); this.repository.add(new HttpTrace(createRequest("POST"))); @@ -47,7 +47,7 @@ public class InMemoryHttpTraceRepositoryTests { } @Test - public void reverseFalse() { + void reverseFalse() { this.repository.setReverse(false); this.repository.setCapacity(2); this.repository.add(new HttpTrace(createRequest("GET"))); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java index 34372d67330..ff829225899 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterIntegrationTests.java @@ -49,13 +49,13 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r * * @author Andy Wilkinson */ -public class HttpTraceWebFilterIntegrationTests { +class HttpTraceWebFilterIntegrationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withUserConfiguration(Config.class); @Test - public void traceForNotFoundResponseHas404Status() { + void traceForNotFoundResponseHas404Status() { this.contextRunner.run((context) -> { WebTestClient.bindToApplicationContext(context).build().get().uri("/").exchange().expectStatus() .isNotFound(); @@ -66,7 +66,7 @@ public class HttpTraceWebFilterIntegrationTests { } @Test - public void traceForMonoErrorWithRuntimeExceptionHas500Status() { + void traceForMonoErrorWithRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { WebTestClient.bindToApplicationContext(context).build().get().uri("/mono-error").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @@ -77,7 +77,7 @@ public class HttpTraceWebFilterIntegrationTests { } @Test - public void traceForThrownRuntimeExceptionHas500Status() { + void traceForThrownRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { WebTestClient.bindToApplicationContext(context).build().get().uri("/thrown").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java index e9ac5628d91..0fa0c8e2ef8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class HttpTraceWebFilterTests { +class HttpTraceWebFilterTests { private final InMemoryHttpTraceRepository repository = new InMemoryHttpTraceRepository(); @@ -53,14 +53,14 @@ public class HttpTraceWebFilterTests { EnumSet.allOf(Include.class)); @Test - public void filterTracesExchange() { + void filterTracesExchange() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> Mono.empty()).block(Duration.ofSeconds(30)); assertThat(this.repository.findAll()).hasSize(1); } @Test - public void filterCapturesSessionIdWhenSessionIsUsed() { + void filterCapturesSessionIdWhenSessionIsUsed() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> { exchange.getSession().block(Duration.ofSeconds(30)).getAttributes().put("a", "alpha"); return Mono.empty(); @@ -72,7 +72,7 @@ public class HttpTraceWebFilterTests { } @Test - public void filterDoesNotCaptureIdOfUnusedSession() { + void filterDoesNotCaptureIdOfUnusedSession() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), (exchange) -> { exchange.getSession().block(Duration.ofSeconds(30)); return Mono.empty(); @@ -83,7 +83,7 @@ public class HttpTraceWebFilterTests { } @Test - public void filterCapturesPrincipal() { + void filterCapturesPrincipal() { Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); executeFilter(new ServerWebExchangeDecorator( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java index 7cb35829195..48fdcbc42c8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java @@ -52,7 +52,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Madhura Bhave */ -public class HttpTraceFilterTests { +class HttpTraceFilterTests { private final InMemoryHttpTraceRepository repository = new InMemoryHttpTraceRepository(); @@ -61,13 +61,13 @@ public class HttpTraceFilterTests { private final HttpTraceFilter filter = new HttpTraceFilter(this.repository, this.tracer); @Test - public void filterTracesExchange() throws ServletException, IOException { + void filterTracesExchange() throws ServletException, IOException { this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(1); } @Test - public void filterCapturesSessionId() throws ServletException, IOException { + void filterCapturesSessionId() throws ServletException, IOException { this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { @@ -85,7 +85,7 @@ public class HttpTraceFilterTests { } @Test - public void filterCapturesPrincipal() throws ServletException, IOException { + void filterCapturesPrincipal() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest(); Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); @@ -99,7 +99,7 @@ public class HttpTraceFilterTests { } @Test - public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { + void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { assertThatIOException().isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { @@ -116,7 +116,7 @@ public class HttpTraceFilterTests { } @Test - public void filterRejectsInvalidRequests() throws ServletException, IOException { + void filterRejectsInvalidRequests() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName(""); this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java index 0012247499c..1ef72f6394e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java @@ -70,10 +70,10 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r * @author Andy Wilkinson * @author Stephane Nicoll */ -public class MappingsEndpointTests { +class MappingsEndpointTests { @Test - public void servletWebMappings() { + void servletWebMappings() { Supplier contextSupplier = prepareContextSupplier(); new WebApplicationContextRunner(contextSupplier) .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class).run((context) -> { @@ -95,7 +95,7 @@ public class MappingsEndpointTests { } @Test - public void servletWebMappingsWithAdditionalDispatcherServlets() { + void servletWebMappingsWithAdditionalDispatcherServlets() { Supplier contextSupplier = prepareContextSupplier(); new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class, CustomDispatcherServletConfiguration.class).run((context) -> { @@ -129,7 +129,7 @@ public class MappingsEndpointTests { } @Test - public void reactiveWebMappings() { + void reactiveWebMappings() { new ReactiveWebApplicationContextRunner() .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class).run((context) -> { ContextMappings contextMappings = contextMappings(context); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java index d38841cd9e1..a8571669c27 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequestTests.java @@ -19,8 +19,8 @@ import java.net.InetSocketAddress; import java.net.URI; import java.util.Collections; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpRequest; @@ -36,13 +36,13 @@ import static org.mockito.Mockito.mock; * * @author Dmytro Nosan */ -public class ServerWebExchangeTraceableRequestTests { +class ServerWebExchangeTraceableRequestTests { private ServerWebExchange exchange; private ServerHttpRequest request; - @Before + @BeforeEach public void setUp() { this.exchange = mock(ServerWebExchange.class); this.request = mock(ServerHttpRequest.class); @@ -50,7 +50,7 @@ public class ServerWebExchangeTraceableRequestTests { } @Test - public void getMethod() { + void getMethod() { String method = "POST"; given(this.request.getMethodValue()).willReturn(method); ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); @@ -58,7 +58,7 @@ public class ServerWebExchangeTraceableRequestTests { } @Test - public void getUri() { + void getUri() { URI uri = URI.create("http://localhost:8080/"); given(this.request.getURI()).willReturn(uri); ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); @@ -66,7 +66,7 @@ public class ServerWebExchangeTraceableRequestTests { } @Test - public void getHeaders() { + void getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("name", "value"); given(this.request.getHeaders()).willReturn(httpHeaders); @@ -75,7 +75,7 @@ public class ServerWebExchangeTraceableRequestTests { } @Test - public void getUnresolvedRemoteAddress() { + void getUnresolvedRemoteAddress() { InetSocketAddress socketAddress = InetSocketAddress.createUnresolved("unresolved.example.com", 8080); given(this.request.getRemoteAddress()).willReturn(socketAddress); ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); @@ -83,7 +83,7 @@ public class ServerWebExchangeTraceableRequestTests { } @Test - public void getRemoteAddress() { + void getRemoteAddress() { InetSocketAddress socketAddress = new InetSocketAddress(0); given(this.request.getRemoteAddress()).willReturn(socketAddress); ServerWebExchangeTraceableRequest traceableRequest = new ServerWebExchangeTraceableRequest(this.exchange); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletRequestTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletRequestTests.java index c997dacda9e..91f00230e2d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletRequestTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/trace/servlet/TraceableHttpServletRequestTests.java @@ -27,7 +27,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class TraceableHttpServletRequestTests { +class TraceableHttpServletRequestTests { private MockHttpServletRequest request; @@ -37,24 +37,24 @@ public class TraceableHttpServletRequestTests { } @Test - public void getUriWithoutQueryStringShouldReturnUri() { + void getUriWithoutQueryStringShouldReturnUri() { validate("http://localhost/script"); } @Test - public void getUriShouldReturnUriWithQueryString() { + void getUriShouldReturnUriWithQueryString() { this.request.setQueryString("a=b"); validate("http://localhost/script?a=b"); } @Test - public void getUriWithSpecialCharactersInQueryStringShouldEncode() { + void getUriWithSpecialCharactersInQueryStringShouldEncode() { this.request.setQueryString("a=${b}"); validate("http://localhost/script?a=$%7Bb%7D"); } @Test - public void getUriWithSpecialCharactersEncodedShouldNotDoubleEncode() { + void getUriWithSpecialCharactersEncodedShouldNotDoubleEncode() { this.request.setQueryString("a=$%7Bb%7D"); validate("http://localhost/script?a=$%7Bb%7D"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/pom.xml b/spring-boot-project/spring-boot-autoconfigure/pom.xml index d90d189ab19..9cad0b8cc45 100755 --- a/spring-boot-project/spring-boot-autoconfigure/pom.xml +++ b/spring-boot-project/spring-boot-autoconfigure/pom.xml @@ -937,6 +937,11 @@ cassandra test + + org.testcontainers + elasticsearch + test + org.testcontainers junit-jupiter diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java deleted file mode 100644 index 880ef6eb177..00000000000 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AdhocTestSuite.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.autoconfigure; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfigurationTests; -import org.springframework.boot.autoconfigure.jmx.JmxAutoConfigurationTests; -import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorControllerDirectMockMvcTests; - -/** - * A test suite for probing weird ordering problems in the tests. - * - * @author Dave Syer - */ -@RunWith(Suite.class) -@SuiteClasses({ BasicErrorControllerDirectMockMvcTests.class, JmxAutoConfigurationTests.class, - IntegrationAutoConfigurationTests.class }) -@Ignore -public class AdhocTestSuite { - -} diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java index f322cadad75..4c237416f79 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Stephane Nicoll */ -public class AutoConfigurationExcludeFilterTests { +class AutoConfigurationExcludeFilterTests { private static final Class FILTERED = ExampleFilteredAutoConfiguration.class; @@ -52,7 +52,7 @@ public class AutoConfigurationExcludeFilterTests { } @Test - public void filterExcludeAutoConfiguration() { + void filterExcludeAutoConfiguration() { this.context = new AnnotationConfigApplicationContext(Config.class); assertThat(this.context.getBeansOfType(String.class)).hasSize(1); assertThat(this.context.getBean(String.class)).isEqualTo("test"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java index 16f490201f0..69e7ff697db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java @@ -33,31 +33,31 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AutoConfigurationImportSelectorIntegrationTests { +class AutoConfigurationImportSelectorIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void singleSelectorWithNoImports() { + void singleSelectorWithNoImports() { this.contextRunner.withUserConfiguration(NoConfig.class) .run((context) -> assertThat(getImportedConfigBeans(context)).isEmpty()); } @Test - public void singleSelector() { + void singleSelector() { this.contextRunner.withUserConfiguration(SingleConfig.class) .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); } @Test - public void multipleSelectorsShouldMergeAndSortCorrectly() { + void multipleSelectorsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(Config.class, AnotherConfig.class) .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD")); } @Test - public void multipleSelectorsWithRedundantImportsShouldMergeAndSortCorrectly() { + void multipleSelectorsWithRedundantImportsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(SingleConfig.class, Config.class, AnotherConfig.class) .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index ab4e0cbc2ec..9df609c3ec3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Stephane Nicoll * @author Madhura Bhave */ -public class AutoConfigurationImportSelectorTests { +class AutoConfigurationImportSelectorTests { private final TestAutoConfigurationImportSelector importSelector = new TestAutoConfigurationImportSelector(); @@ -69,7 +69,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void importsAreSelectedWhenUsingEnableAutoConfiguration() { + void importsAreSelectedWhenUsingEnableAutoConfiguration() { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSameSizeAs( SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getClass().getClassLoader())); @@ -77,7 +77,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void classExclusionsAreApplied() { + void classExclusionsAreApplied() { String[] imports = selectImports(EnableAutoConfigurationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -85,7 +85,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void classExclusionsAreAppliedWhenUsingSpringBootApplication() { + void classExclusionsAreAppliedWhenUsingSpringBootApplication() { String[] imports = selectImports(SpringBootApplicationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -93,7 +93,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void classNamesExclusionsAreApplied() { + void classNamesExclusionsAreApplied() { String[] imports = selectImports(EnableAutoConfigurationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -101,7 +101,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void classNamesExclusionsAreAppliedWhenUsingSpringBootApplication() { + void classNamesExclusionsAreAppliedWhenUsingSpringBootApplication() { String[] imports = selectImports(SpringBootApplicationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) @@ -109,7 +109,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void propertyExclusionsAreApplied() { + void propertyExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude", FreeMarkerAutoConfiguration.class.getName()); String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); @@ -118,21 +118,21 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void severalPropertyExclusionsAreApplied() { + void severalPropertyExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude", FreeMarkerAutoConfiguration.class.getName() + "," + MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); } @Test - public void severalPropertyExclusionsAreAppliedWithExtraSpaces() { + void severalPropertyExclusionsAreAppliedWithExtraSpaces() { this.environment.setProperty("spring.autoconfigure.exclude", FreeMarkerAutoConfiguration.class.getName() + " , " + MustacheAutoConfiguration.class.getName() + " "); testSeveralPropertyExclusionsAreApplied(); } @Test - public void severalPropertyYamlExclusionsAreApplied() { + void severalPropertyYamlExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude[0]", FreeMarkerAutoConfiguration.class.getName()); this.environment.setProperty("spring.autoconfigure.exclude[1]", MustacheAutoConfiguration.class.getName()); testSeveralPropertyExclusionsAreApplied(); @@ -146,7 +146,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void combinedExclusionsAreApplied() { + void combinedExclusionsAreApplied() { this.environment.setProperty("spring.autoconfigure.exclude", ThymeleafAutoConfiguration.class.getName()); String[] imports = selectImports(EnableAutoConfigurationWithClassAndClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 3); @@ -156,26 +156,26 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void nonAutoConfigurationClassExclusionsShouldThrowException() { + void nonAutoConfigurationClassExclusionsShouldThrowException() { assertThatIllegalStateException() .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); } @Test - public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { + void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { assertThatIllegalStateException() .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); } @Test - public void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() { + void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() { this.environment.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure." + "AutoConfigurationImportSelectorTests.TestConfiguration"); assertThatIllegalStateException().isThrownBy(() -> selectImports(BasicEnableAutoConfiguration.class)); } @Test - public void nameAndPropertyExclusionsWhenNotPresentOnClasspathShouldNotThrowException() { + void nameAndPropertyExclusionsWhenNotPresentOnClasspathShouldNotThrowException() { this.environment.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure.DoesNotExist2"); selectImports(EnableAutoConfigurationWithAbsentClassNameExclude.class); @@ -185,7 +185,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void filterShouldFilterImports() { + void filterShouldFilterImports() { String[] defaultImports = selectImports(BasicEnableAutoConfiguration.class); this.filters.add(new TestAutoConfigurationImportFilter(defaultImports, 1)); this.filters.add(new TestAutoConfigurationImportFilter(defaultImports, 3, 4)); @@ -195,7 +195,7 @@ public class AutoConfigurationImportSelectorTests { } @Test - public void filterShouldSupportAware() { + void filterShouldSupportAware() { TestAutoConfigurationImportFilter filter = new TestAutoConfigurationImportFilter(new String[] {}); this.filters.add(filter); selectImports(BasicEnableAutoConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java index e2ec8ed55eb..adb83a99bf1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoaderTests.java @@ -27,65 +27,65 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AutoConfigurationMetadataLoaderTests { +class AutoConfigurationMetadataLoaderTests { @Test - public void loadShouldLoadProperties() { + void loadShouldLoadProperties() { assertThat(load()).isNotNull(); } @Test - public void wasProcessedWhenProcessedShouldReturnTrue() { + void wasProcessedWhenProcessedShouldReturnTrue() { assertThat(load().wasProcessed("test")).isTrue(); } @Test - public void wasProcessedWhenNotProcessedShouldReturnFalse() { + void wasProcessedWhenNotProcessedShouldReturnFalse() { assertThat(load().wasProcessed("testx")).isFalse(); } @Test - public void getIntegerShouldReturnValue() { + void getIntegerShouldReturnValue() { assertThat(load().getInteger("test", "int")).isEqualTo(123); } @Test - public void getIntegerWhenMissingShouldReturnNull() { + void getIntegerWhenMissingShouldReturnNull() { assertThat(load().getInteger("test", "intx")).isNull(); } @Test - public void getIntegerWithDefaultWhenMissingShouldReturnDefault() { + void getIntegerWithDefaultWhenMissingShouldReturnDefault() { assertThat(load().getInteger("test", "intx", 345)).isEqualTo(345); } @Test - public void getSetShouldReturnValue() { + void getSetShouldReturnValue() { assertThat(load().getSet("test", "set")).containsExactly("a", "b", "c"); } @Test - public void getSetWhenMissingShouldReturnNull() { + void getSetWhenMissingShouldReturnNull() { assertThat(load().getSet("test", "setx")).isNull(); } @Test - public void getSetWithDefaultWhenMissingShouldReturnDefault() { + void getSetWithDefaultWhenMissingShouldReturnDefault() { assertThat(load().getSet("test", "setx", Collections.singleton("x"))).containsExactly("x"); } @Test - public void getShouldReturnValue() { + void getShouldReturnValue() { assertThat(load().get("test", "string")).isEqualTo("abc"); } @Test - public void getWhenMissingShouldReturnNull() { + void getWhenMissingShouldReturnNull() { assertThat(load().get("test", "stringx")).isNull(); } @Test - public void getWithDefaultWhenMissingShouldReturnDefault() { + void getWithDefaultWhenMissingShouldReturnDefault() { assertThat(load().get("test", "stringx", "xyz")).isEqualTo("xyz"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index 8c0b08ca6b6..433698ca482 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -40,21 +40,21 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; public class AutoConfigurationPackagesTests { @Test - public void setAndGet() { + void setAndGet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithRegistrar.class); assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) .containsExactly(getClass().getPackage().getName()); } @Test - public void getWithoutSet() { + void getWithoutSet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); assertThatIllegalStateException().isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); } @Test - public void detectsMultipleAutoConfigurationPackages() { + void detectsMultipleAutoConfigurationPackages() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FirstConfiguration.class, SecondConfiguration.class); List packages = AutoConfigurationPackages.get(context.getBeanFactory()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java index 8e2bdda9e7b..34dc5e775fe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AutoConfigurationReproTests { +class AutoConfigurationReproTests { private ConfigurableApplicationContext context; @@ -45,7 +45,7 @@ public class AutoConfigurationReproTests { } @Test - public void doesNotEarlyInitializeFactoryBeans() { + void doesNotEarlyInitializeFactoryBeans() { SpringApplication application = new SpringApplication(EarlyInitConfig.class, PropertySourcesPlaceholderConfigurer.class, ServletWebServerFactoryAutoConfiguration.class); this.context = application.run("--server.port=0"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index 3aa34df0ec6..42c3a89d806 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class AutoConfigurationSorterTests { +class AutoConfigurationSorterTests { private static final String DEFAULT = OrderUnspecified.class.getName(); @@ -83,62 +83,62 @@ public class AutoConfigurationSorterTests { } @Test - public void byOrderAnnotation() { + void byOrderAnnotation() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST, DEFAULT)); assertThat(actual).containsExactly(HIGHEST, DEFAULT, LOWEST); } @Test - public void byAutoConfigureAfter() { + void byAutoConfigureAfter() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C)); assertThat(actual).containsExactly(C, B, A); } @Test - public void byAutoConfigureBefore() { + void byAutoConfigureBefore() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(X, Y, Z)); assertThat(actual).containsExactly(Z, Y, X); } @Test - public void byAutoConfigureAfterDoubles() { + void byAutoConfigureAfterDoubles() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, E)); assertThat(actual).containsExactly(C, E, B, A); } @Test - public void byAutoConfigureMixedBeforeAndAfter() { + void byAutoConfigureMixedBeforeAndAfter() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, W, X)); assertThat(actual).containsExactly(C, W, B, A, X); } @Test - public void byAutoConfigureMixedBeforeAndAfterWithClassNames() { + void byAutoConfigureMixedBeforeAndAfterWithClassNames() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); assertThat(actual).containsExactly(C, W2, B, A2, X); } @Test - public void byAutoConfigureMixedBeforeAndAfterWithDifferentInputOrder() { + void byAutoConfigureMixedBeforeAndAfterWithDifferentInputOrder() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(W, X, A, B, C)); assertThat(actual).containsExactly(C, W, B, A, X); } @Test - public void byAutoConfigureAfterWithMissing() { + void byAutoConfigureAfterWithMissing() { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B)); assertThat(actual).containsExactly(B, A); } @Test - public void byAutoConfigureAfterWithCycle() { + void byAutoConfigureAfterWithCycle() { this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) .withMessageContaining("AutoConfigure cycle detected"); } @Test - public void usesAnnotationPropertiesWhenPossible() throws Exception { + void usesAnnotationPropertiesWhenPossible() throws Exception { MetadataReaderFactory readerFactory = new SkipCycleMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A2, B, C, W2, X); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); @@ -147,7 +147,7 @@ public class AutoConfigurationSorterTests { } @Test - public void useAnnotationWithNoDirectLink() throws Exception { + void useAnnotationWithNoDirectLink() throws Exception { MetadataReaderFactory readerFactory = new SkipCycleMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, E); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); @@ -156,7 +156,7 @@ public class AutoConfigurationSorterTests { } @Test - public void useAnnotationWithNoDirectLinkAndCycle() throws Exception { + void useAnnotationWithNoDirectLinkAndCycle() throws Exception { MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(); this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java index 1df5f76eb85..e6c8095c3b2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationsTests.java @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AutoConfigurationsTests { +class AutoConfigurationsTests { @Test - public void ofShouldCreateOrderedConfigurations() { + void ofShouldCreateOrderedConfigurations() { Configurations configurations = AutoConfigurations.of(AutoConfigureA.class, AutoConfigureB.class); assertThat(Configurations.getClasses(configurations)).containsExactly(AutoConfigureB.class, AutoConfigureA.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java index f8cd55ad67f..38012675b66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java @@ -48,7 +48,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Phillip Webb * @author Andy Wilkinson */ -public class ImportAutoConfigurationImportSelectorTests { +class ImportAutoConfigurationImportSelectorTests { private final ImportAutoConfigurationImportSelector importSelector = new TestImportAutoConfigurationImportSelector(); @@ -66,28 +66,28 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void importsAreSelected() throws Exception { + void importsAreSelected() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test - public void importsAreSelectedUsingClassesAttribute() throws Exception { + void importsAreSelectedUsingClassesAttribute() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarkerUsingClassesAttribute.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsExactly(FreeMarkerAutoConfiguration.class.getName()); } @Test - public void propertyExclusionsAreNotApplied() throws Exception { + void propertyExclusionsAreNotApplied() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportFreeMarker.class); this.importSelector.selectImports(annotationMetadata); verifyZeroInteractions(this.environment); } @Test - public void multipleImportsAreFound() throws Exception { + void multipleImportsAreFound() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImports.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName(), @@ -95,35 +95,35 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() throws IOException { + void selfAnnotatingAnnotationDoesNotCauseStackOverflow() throws IOException { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotation.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(ThymeleafAutoConfiguration.class.getName()); } @Test - public void exclusionsAreApplied() throws Exception { + void exclusionsAreApplied() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImportsWithExclusion.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test - public void exclusionsWithoutImport() throws Exception { + void exclusionsWithoutImport() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ExclusionWithoutImport.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).containsOnly(FreeMarkerAutoConfiguration.class.getName()); } @Test - public void exclusionsAliasesAreApplied() throws Exception { + void exclusionsAliasesAreApplied() throws Exception { AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotationExclude.class); String[] imports = this.importSelector.selectImports(annotationMetadata); assertThat(imports).isEmpty(); } @Test - public void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { + void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector @@ -133,7 +133,7 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { + void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { Set set1 = this.importSelector .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector @@ -142,7 +142,7 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { + void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { Set set1 = this.importSelector .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); Set set2 = this.importSelector @@ -151,7 +151,7 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { + void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector @@ -161,7 +161,7 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { + void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { Set set1 = this.importSelector .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector @@ -170,7 +170,7 @@ public class ImportAutoConfigurationImportSelectorTests { } @Test - public void determineImportsShouldNotSetPackageImport() throws Exception { + void determineImportsShouldNotSetPackageImport() throws Exception { Class packageImportClass = ClassUtils.resolveClassName( "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImport", null); Set selectedImports = this.importSelector diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java index c0659a7c589..88600c7a106 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationTests.java @@ -34,33 +34,33 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ImportAutoConfigurationTests { +class ImportAutoConfigurationTests { @Test - public void multipleAnnotationsShouldMergeCorrectly() { + void multipleAnnotationsShouldMergeCorrectly() { assertThat(getImportedConfigBeans(Config.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); assertThat(getImportedConfigBeans(AnotherConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); } @Test - public void classesAsAnAlias() { + void classesAsAnAlias() { assertThat(getImportedConfigBeans(AnotherConfigUsingClasses.class)).containsExactly("ConfigA", "ConfigB", "ConfigC", "ConfigD"); } @Test - public void excluding() { + void excluding() { assertThat(getImportedConfigBeans(ExcludingConfig.class)).containsExactly("ConfigA", "ConfigB", "ConfigD"); } @Test - public void excludeAppliedGlobally() { + void excludeAppliedGlobally() { assertThat(getImportedConfigBeans(ExcludeDConfig.class, ImportADConfig.class)).containsExactly("ConfigA"); } @Test - public void excludeWithRedundancy() { + void excludeWithRedundancy() { assertThat(getImportedConfigBeans(ExcludeADConfig.class, ExcludeDConfig.class, ImportADConfig.class)).isEmpty(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java index c68bb4edaac..8da3f7e22e5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java @@ -38,10 +38,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class SharedMetadataReaderFactoryContextInitializerTests { +class SharedMetadataReaderFactoryContextInitializerTests { @Test - public void checkOrderOfInitializer() { + void checkOrderOfInitializer() { SpringApplication application = new SpringApplication(TestConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java index c5f763636c1..e6f2945c6ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.autoconfigure; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotatedElementUtils; @@ -29,17 +29,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SpringBootApplicationTests { +class SpringBootApplicationTests { @Test - public void proxyBeanMethodsIsEnabledByDefault() { + void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test - public void proxyBeanMethodsCanBeDisabled() { + void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java index a1d414173a6..96de272f6d8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest -public class SpringJUnitTests { +class SpringJUnitTests { @Autowired private ApplicationContext context; @@ -43,12 +43,12 @@ public class SpringJUnitTests { private String foo = "bar"; @Test - public void testContextCreated() { + void testContextCreated() { assertThat(this.context).isNotNull(); } @Test - public void testContextInitialized() { + void testContextInitialized() { assertThat(this.foo).isEqualTo("bucket"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index acc1319c529..600fa096093 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -43,7 +43,7 @@ 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; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link SpringApplicationAdminJmxAutoConfiguration}. @@ -51,7 +51,7 @@ import static org.junit.Assert.fail; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class SpringApplicationAdminJmxAutoConfigurationTests { +class SpringApplicationAdminJmxAutoConfigurationTests { private static final String ENABLE_ADMIN_PROP = "spring.application.admin.enabled=true"; @@ -64,13 +64,13 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { SpringApplicationAdminJmxAutoConfiguration.class)); @Test - public void notRegisteredByDefault() { + void notRegisteredByDefault() { this.contextRunner.run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); } @Test - public void registeredWithProperty() { + void registeredWithProperty() { this.contextRunner.withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { ObjectName objectName = createDefaultObjectName(); ObjectInstance objectInstance = this.server.getObjectInstance(objectName); @@ -79,7 +79,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } @Test - public void registerWithCustomJmxName() { + void registerWithCustomJmxName() { String customJmxName = "org.acme:name=FooBar"; this.contextRunner.withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { @@ -95,7 +95,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } @Test - public void registerWithSimpleWebApp() throws Exception { + void registerWithSimpleWebApp() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) @@ -110,7 +110,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { } @Test - public void onlyRegisteredOnceWhenThereIsAChildContext() { + void onlyRegisteredOnceWhenThereIsAChildContext() { SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder().web(WebApplicationType.NONE) .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); SpringApplicationBuilder childBuilder = parentBuilder diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index 551b7378aad..59e160060db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -80,13 +80,13 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Gary Russell */ -public class RabbitAutoConfigurationTests { +class RabbitAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test - public void testDefaultRabbitConfiguration() { + void testDefaultRabbitConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitMessagingTemplate messagingTemplate = context.getBean(RabbitMessagingTemplate.class); @@ -105,7 +105,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testDefaultRabbitTemplateConfiguration() { + void testDefaultRabbitTemplateConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitTemplate defaultRabbitTemplate = new RabbitTemplate(); @@ -115,7 +115,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testDefaultConnectionFactoryConfiguration() { + void testDefaultConnectionFactoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { RabbitProperties properties = new RabbitProperties(); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); @@ -125,7 +125,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryWithOverrides() { + void testConnectionFactoryWithOverrides() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice", "spring.rabbitmq.password:secret", @@ -142,7 +142,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryWithCustomConnectionNameStrategy() { + void testConnectionFactoryWithCustomConnectionNameStrategy() { this.contextRunner.withUserConfiguration(ConnectionNameStrategyConfiguration.class).run((context) -> { CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); Address[] addresses = (Address[]) ReflectionTestUtils.getField(connectionFactory, "addresses"); @@ -159,7 +159,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryEmptyVirtualHost() { + void testConnectionFactoryEmptyVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> { CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); @@ -168,7 +168,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryVirtualHostNoLeadingSlash() { + void testConnectionFactoryVirtualHostNoLeadingSlash() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> { CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); @@ -177,7 +177,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryVirtualHostMultiLeadingSlashes() { + void testConnectionFactoryVirtualHostMultiLeadingSlashes() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:///foo").run((context) -> { CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); @@ -186,7 +186,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryDefaultVirtualHost() { + void testConnectionFactoryDefaultVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> { CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); @@ -195,7 +195,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryPublisherSettings() { + void testConnectionFactoryPublisherSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.publisher-confirms=true", "spring.rabbitmq.publisher-returns=true") .run((context) -> { @@ -208,7 +208,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateMessageConverters() { + void testRabbitTemplateMessageConverters() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class).run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(rabbitTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); @@ -217,7 +217,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateRetry() { + void testRabbitTemplateRetry() { this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( "spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.maxAttempts:4", "spring.rabbitmq.template.retry.initialInterval:2000", "spring.rabbitmq.template.retry.multiplier:1.5", @@ -241,7 +241,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateRetryWithCustomizer() { + void testRabbitTemplateRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.initialInterval:2000") @@ -259,7 +259,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateExchangeAndRoutingKey() { + void testRabbitTemplateExchangeAndRoutingKey() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", "spring.rabbitmq.template.routing-key:my-routing-key") @@ -271,7 +271,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateDefaultReceiveQueue() { + void testRabbitTemplateDefaultReceiveQueue() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); @@ -280,7 +280,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateMandatory() { + void testRabbitTemplateMandatory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.template.mandatory:true").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); @@ -289,7 +289,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateMandatoryDisabledEvenIfPublisherReturnsIsSet() { + void testRabbitTemplateMandatoryDisabledEvenIfPublisherReturnsIsSet() { this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( "spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true").run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); @@ -298,7 +298,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryBackOff() { + void testConnectionFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration2.class).run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); @@ -309,7 +309,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testConnectionFactoryCacheSettings() { + void testConnectionFactoryCacheSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.cache.channel.size=23", "spring.rabbitmq.cache.channel.checkoutTimeout=1000", @@ -324,7 +324,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitTemplateBackOff() { + void testRabbitTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration3.class).run((context) -> { RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); assertThat(rabbitTemplate.getMessageConverter()).isEqualTo(context.getBean("testMessageConverter")); @@ -332,7 +332,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitMessagingTemplateBackOff() { + void testRabbitMessagingTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration4.class).run((context) -> { RabbitMessagingTemplate messagingTemplate = context.getBean(RabbitMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestination()).isEqualTo("fooBar"); @@ -340,7 +340,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testStaticQueues() { + 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") @@ -350,7 +350,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testEnableRabbitCreateDefaultContainerFactory() { + void testEnableRabbitCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class).run((context) -> { RabbitListenerContainerFactory rabbitListenerContainerFactory = context .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); @@ -359,7 +359,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitListenerContainerFactoryBackOff() { + void testRabbitListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class).run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); @@ -370,7 +370,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { + void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", @@ -400,7 +400,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testDirectRabbitListenerContainerFactoryWithCustomSettings() { + void testDirectRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:direct", @@ -426,7 +426,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testSimpleRabbitListenerContainerFactoryRetryWithCustomizer() { + void testSimpleRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", "spring.rabbitmq.listener.simple.retry.maxAttempts:4") @@ -439,7 +439,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testDirectRabbitListenerContainerFactoryRetryWithCustomizer() { + void testDirectRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:direct", "spring.rabbitmq.listener.direct.retry.enabled:true", @@ -463,7 +463,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testRabbitListenerContainerFactoryConfigurersAreAvailable() { + void testRabbitListenerContainerFactoryConfigurersAreAvailable() { this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( "spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.direct.consumers-per-queue:5", @@ -474,7 +474,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testSimpleRabbitListenerContainerFactoryConfigurerUsesConfig() { + void testSimpleRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:direct", "spring.rabbitmq.listener.simple.concurrency:5", @@ -492,7 +492,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void testDirectRabbitListenerContainerFactoryConfigurerUsesConfig() { + void testDirectRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.listener.type:simple", "spring.rabbitmq.listener.direct.consumers-per-queue:5", @@ -539,7 +539,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableRabbitAutomatically() { + void enableRabbitAutomatically() { this.contextRunner.withUserConfiguration(NoEnableRabbitConfiguration.class).run((context) -> { assertThat(context).hasBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); assertThat(context).hasBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); @@ -547,7 +547,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void customizeRequestedHeartBeat() { + void customizeRequestedHeartBeat() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20").run((context) -> { com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); @@ -556,7 +556,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void noSslByDefault() { + void noSslByDefault() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); assertThat(rabbitConnectionFactory.getSocketFactory()).isNull(); @@ -565,7 +565,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSsl() { + void enableSsl() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); @@ -577,7 +577,7 @@ public class RabbitAutoConfigurationTests { @Test // Make sure that we at least attempt to load the store - public void enableSslWithNonExistingKeystoreShouldFail() { + void enableSslWithNonExistingKeystoreShouldFail() { this.contextRunner .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStorePassword=secret") @@ -590,7 +590,7 @@ public class RabbitAutoConfigurationTests { @Test // Make sure that we at least attempt to load the store - public void enableSslWithNonExistingTrustStoreShouldFail() { + void enableSslWithNonExistingTrustStoreShouldFail() { this.contextRunner .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStorePassword=secret") @@ -602,7 +602,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSslWithInvalidKeystoreTypeShouldFail() { + void enableSslWithInvalidKeystoreTypeShouldFail() { this.contextRunner .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStoreType=fooType") @@ -614,7 +614,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSslWithInvalidTrustStoreTypeShouldFail() { + void enableSslWithInvalidTrustStoreTypeShouldFail() { this.contextRunner .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStoreType=barType") @@ -626,7 +626,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSslWithKeystoreTypeAndTrustStoreTypeShouldWork() { + void enableSslWithKeystoreTypeAndTrustStoreTypeShouldWork() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", @@ -637,7 +637,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSslWithValidateServerCertificateFalse() throws Exception { + void enableSslWithValidateServerCertificateFalse() throws Exception { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.validateServerCertificate=false") @@ -649,7 +649,7 @@ public class RabbitAutoConfigurationTests { } @Test - public void enableSslWithValidateServerCertificateDefault() throws Exception { + void enableSslWithValidateServerCertificateDefault() throws Exception { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index f66bf6404a9..6f9e55e873f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -32,198 +32,198 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class RabbitPropertiesTests { +class RabbitPropertiesTests { private final RabbitProperties properties = new RabbitProperties(); @Test - public void hostDefaultsToLocalhost() { + void hostDefaultsToLocalhost() { assertThat(this.properties.getHost()).isEqualTo("localhost"); } @Test - public void customHost() { + void customHost() { this.properties.setHost("rabbit.example.com"); assertThat(this.properties.getHost()).isEqualTo("rabbit.example.com"); } @Test - public void hostIsDeterminedFromFirstAddress() { + void hostIsDeterminedFromFirstAddress() { this.properties.setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345"); assertThat(this.properties.determineHost()).isEqualTo("rabbit1.example.com"); } @Test - public void determineHostReturnsHostPropertyWhenNoAddresses() { + void determineHostReturnsHostPropertyWhenNoAddresses() { this.properties.setHost("rabbit.example.com"); assertThat(this.properties.determineHost()).isEqualTo("rabbit.example.com"); } @Test - public void portDefaultsTo5672() { + void portDefaultsTo5672() { assertThat(this.properties.getPort()).isEqualTo(5672); } @Test - public void customPort() { + void customPort() { this.properties.setPort(1234); assertThat(this.properties.getPort()).isEqualTo(1234); } @Test - public void determinePortReturnsPortOfFirstAddress() { + void determinePortReturnsPortOfFirstAddress() { this.properties.setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345"); assertThat(this.properties.determinePort()).isEqualTo(1234); } @Test - public void determinePortReturnsPortPropertyWhenNoAddresses() { + void determinePortReturnsPortPropertyWhenNoAddresses() { this.properties.setPort(1234); assertThat(this.properties.determinePort()).isEqualTo(1234); } @Test - public void determinePortReturnsDefaultAmqpPortWhenFirstAddressHasNoExplicitPort() { + void determinePortReturnsDefaultAmqpPortWhenFirstAddressHasNoExplicitPort() { this.properties.setPort(1234); this.properties.setAddresses("rabbit1.example.com,rabbit2.example.com:2345"); assertThat(this.properties.determinePort()).isEqualTo(5672); } @Test - public void virtualHostDefaultsToNull() { + void virtualHostDefaultsToNull() { assertThat(this.properties.getVirtualHost()).isNull(); } @Test - public void customVirtualHost() { + void customVirtualHost() { this.properties.setVirtualHost("alpha"); assertThat(this.properties.getVirtualHost()).isEqualTo("alpha"); } @Test - public void virtualHostRetainsALeadingSlash() { + void virtualHostRetainsALeadingSlash() { this.properties.setVirtualHost("/alpha"); assertThat(this.properties.getVirtualHost()).isEqualTo("/alpha"); } @Test - public void determineVirtualHostReturnsVirtualHostOfFirstAddress() { + void determineVirtualHostReturnsVirtualHostOfFirstAddress() { this.properties.setAddresses("rabbit1.example.com:1234/alpha,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @Test - public void determineVirtualHostReturnsPropertyWhenNoAddresses() { + void determineVirtualHostReturnsPropertyWhenNoAddresses() { this.properties.setVirtualHost("alpha"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @Test - public void determineVirtualHostReturnsPropertyWhenFirstAddressHasNoVirtualHost() { + void determineVirtualHostReturnsPropertyWhenFirstAddressHasNoVirtualHost() { this.properties.setVirtualHost("alpha"); this.properties.setAddresses("rabbit1.example.com:1234,rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineVirtualHost()).isEqualTo("alpha"); } @Test - public void determineVirtualHostIsSlashWhenAddressHasTrailingSlash() { + void determineVirtualHostIsSlashWhenAddressHasTrailingSlash() { this.properties.setAddresses("amqp://root:password@otherhost:1111/"); assertThat(this.properties.determineVirtualHost()).isEqualTo("/"); } @Test - public void emptyVirtualHostIsCoercedToASlash() { + void emptyVirtualHostIsCoercedToASlash() { this.properties.setVirtualHost(""); assertThat(this.properties.getVirtualHost()).isEqualTo("/"); } @Test - public void usernameDefaultsToGuest() { + void usernameDefaultsToGuest() { assertThat(this.properties.getUsername()).isEqualTo("guest"); } @Test - public void customUsername() { + void customUsername() { this.properties.setUsername("user"); assertThat(this.properties.getUsername()).isEqualTo("user"); } @Test - public void determineUsernameReturnsUsernameOfFirstAddress() { + void determineUsernameReturnsUsernameOfFirstAddress() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("user"); } @Test - public void determineUsernameReturnsPropertyWhenNoAddresses() { + void determineUsernameReturnsPropertyWhenNoAddresses() { this.properties.setUsername("alice"); assertThat(this.properties.determineUsername()).isEqualTo("alice"); } @Test - public void determineUsernameReturnsPropertyWhenFirstAddressHasNoUsername() { + void determineUsernameReturnsPropertyWhenFirstAddressHasNoUsername() { this.properties.setUsername("alice"); this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determineUsername()).isEqualTo("alice"); } @Test - public void passwordDefaultsToGuest() { + void passwordDefaultsToGuest() { assertThat(this.properties.getPassword()).isEqualTo("guest"); } @Test - public void customPassword() { + void customPassword() { this.properties.setPassword("secret"); assertThat(this.properties.getPassword()).isEqualTo("secret"); } @Test - public void determinePasswordReturnsPasswordOfFirstAddress() { + void determinePasswordReturnsPasswordOfFirstAddress() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha," + "rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("secret"); } @Test - public void determinePasswordReturnsPropertyWhenNoAddresses() { + void determinePasswordReturnsPropertyWhenNoAddresses() { this.properties.setPassword("secret"); assertThat(this.properties.determinePassword()).isEqualTo("secret"); } @Test - public void determinePasswordReturnsPropertyWhenFirstAddressHasNoPassword() { + void determinePasswordReturnsPropertyWhenFirstAddressHasNoPassword() { this.properties.setPassword("12345678"); this.properties.setAddresses("rabbit1.example.com:1234/alpha," + "user:secret@rabbit2.example.com:2345/bravo"); assertThat(this.properties.determinePassword()).isEqualTo("12345678"); } @Test - public void addressesDefaultsToNull() { + void addressesDefaultsToNull() { assertThat(this.properties.getAddresses()).isNull(); } @Test - public void customAddresses() { + void customAddresses() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); assertThat(this.properties.getAddresses()) .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); } @Test - public void determineAddressesReturnsAddressesWithJustHostAndPort() { + void determineAddressesReturnsAddressesWithJustHostAndPort() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); assertThat(this.properties.determineAddresses()).isEqualTo("rabbit1.example.com:1234,rabbit2.example.com:5672"); } @Test - public void determineAddressesUsesHostAndPortPropertiesWhenNoAddressesSet() { + void determineAddressesUsesHostAndPortPropertiesWhenNoAddressesSet() { this.properties.setHost("rabbit.example.com"); this.properties.setPort(1234); assertThat(this.properties.determineAddresses()).isEqualTo("rabbit.example.com:1234"); } @Test - public void simpleContainerUseConsistentDefaultValues() { + void simpleContainerUseConsistentDefaultValues() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); SimpleMessageListenerContainer container = factory.createListenerContainer(); RabbitProperties.SimpleContainer simple = this.properties.getListener().getSimple(); @@ -232,7 +232,7 @@ public class RabbitPropertiesTests { } @Test - public void directContainerUseConsistentDefaultValues() { + void directContainerUseConsistentDefaultValues() { DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory(); DirectMessageListenerContainer container = factory.createListenerContainer(); RabbitProperties.DirectContainer direct = this.properties.getListener().getDirect(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java index 1332b0e5b4b..91046d7b128 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eberhard Wolff * @author Stephane Nicoll */ -public class AopAutoConfigurationTests { +class AopAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); @Test - public void aopDisabled() { + void aopDisabled() { this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.aop.auto:false") .run((context) -> { TestAspect aspect = context.getBean(TestAspect.class); @@ -55,24 +55,24 @@ public class AopAutoConfigurationTests { } @Test - public void aopWithDefaultSettings() { + void aopWithDefaultSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run(proxyTargetClassEnabled()); } @Test - public void aopWithEnabledProxyTargetClass() { + void aopWithEnabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.aop.proxy-target-class:true").run(proxyTargetClassEnabled()); } @Test - public void aopWithDisabledProxyTargetClass() { + void aopWithDisabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.aop.proxy-target-class:false").run(proxyTargetClassDisabled()); } @Test - public void customConfigurationWithProxyTargetClassDefaultDoesNotDisableProxying() { + void customConfigurationWithProxyTargetClassDefaultDoesNotDisableProxying() { this.contextRunner.withUserConfiguration(CustomTestConfiguration.class).run(proxyTargetClassEnabled()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index d1ba34e130b..f093213c4af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -70,13 +70,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Vedran Pavic * @author Kazuki Shimizu */ -public class BatchAutoConfigurationTests { +class BatchAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test - public void testDefaultContext() { + void testDefaultContext() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); @@ -89,7 +89,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testNoDatabase() { + void testNoDatabase() { this.contextRunner.withUserConfiguration(TestCustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); JobExplorer explorer = context.getBean(JobExplorer.class); @@ -98,7 +98,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testNoBatchConfiguration() { + void testNoBatchConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { assertThat(context).doesNotHaveBean(JobLauncher.class); @@ -107,7 +107,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testDefinesAndLaunchesJob() { + void testDefinesAndLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); @@ -118,7 +118,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testDefinesAndLaunchesNamedJob() { + void testDefinesAndLaunchesNamedJob() { this.contextRunner .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, EmbeddedDataSourceConfiguration.class) @@ -131,7 +131,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testDefinesAndLaunchesLocalJob() { + void testDefinesAndLaunchesLocalJob() { this.contextRunner .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.batch.job.names:discreteLocalJob").run((context) -> { @@ -143,7 +143,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testDisableLaunchesJob() { + void testDisableLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.batch.job.enabled:false").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); @@ -152,7 +152,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testDisableSchemaLoader() { + void testDisableSchemaLoader() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.batch.initialize-schema:never") @@ -167,7 +167,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testUsingJpa() { + void testUsingJpa() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class).run((context) -> { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); @@ -183,7 +183,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testRenamePrefix() { + void testRenamePrefix() { this.contextRunner .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class) @@ -204,7 +204,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testCustomizeJpaTransactionManagerUsingProperties() { + void testCustomizeJpaTransactionManagerUsingProperties() { this.contextRunner .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class) @@ -220,7 +220,7 @@ public class BatchAutoConfigurationTests { } @Test - public void testCustomizeDataSourceTransactionManagerUsingProperties() { + void testCustomizeDataSourceTransactionManagerUsingProperties() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java index 237edeb1ee1..bb7786bc9d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java @@ -28,18 +28,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class JobExecutionExitCodeGeneratorTests { +class JobExecutionExitCodeGeneratorTests { private final JobExecutionExitCodeGenerator generator = new JobExecutionExitCodeGenerator(); @Test - public void testExitCodeForRunning() { + void testExitCodeForRunning() { this.generator.onApplicationEvent(new JobExecutionEvent(new JobExecution(0L))); assertThat(this.generator.getExitCode()).isEqualTo(1); } @Test - public void testExitCodeForCompleted() { + void testExitCodeForCompleted() { JobExecution execution = new JobExecution(0L); execution.setStatus(BatchStatus.COMPLETED); this.generator.onApplicationEvent(new JobExecutionEvent(execution)); @@ -47,7 +47,7 @@ public class JobExecutionExitCodeGeneratorTests { } @Test - public void testExitCodeForFailed() { + void testExitCodeForFailed() { JobExecution execution = new JobExecution(0L); execution.setStatus(BatchStatus.FAILED); this.generator.onApplicationEvent(new JobExecutionEvent(execution)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java index 9cf05705fd2..a4197686ffc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java @@ -56,7 +56,7 @@ import static org.assertj.core.api.Assertions.fail; * @author Jean-Pierre Bergamin * @author Mahmoud Ben Hassine */ -public class JobLauncherCommandLineRunnerTests { +class JobLauncherCommandLineRunnerTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -95,7 +95,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void basicExecution() throws Exception { + void basicExecution() throws Exception { this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters()); @@ -103,7 +103,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void incrementExistingExecution() throws Exception { + void incrementExistingExecution() throws Exception { this.job = this.jobs.get("job").start(this.step).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); @@ -111,7 +111,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void retryFailedExecution() throws Exception { + void retryFailedExecution() throws Exception { this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); @@ -120,7 +120,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void runDifferentInstances() throws Exception { + void runDifferentInstances() throws Exception { this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).build(); // start a job instance JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters(); @@ -133,7 +133,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void retryFailedExecutionOnNonRestartableJob() throws Exception { + void retryFailedExecutionOnNonRestartableJob() throws Exception { this.job = this.jobs.get("job").preventRestart() .start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()) .build(); @@ -150,7 +150,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { + void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) @@ -163,7 +163,7 @@ public class JobLauncherCommandLineRunnerTests { } @Test - public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() throws Exception { + void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() throws Exception { this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()) .incrementer(new RunIdIncrementer()).build(); JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java index bb4997f2e79..61a0923ba98 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizersTests.java @@ -33,15 +33,15 @@ import static org.mockito.Mockito.mock; /** * @author Stephane Nicoll */ -public class CacheManagerCustomizersTests { +class CacheManagerCustomizersTests { @Test - public void customizeWithNullCustomizersShouldDoNothing() { + void customizeWithNullCustomizersShouldDoNothing() { new CacheManagerCustomizers(null).customize(mock(CacheManager.class)); } @Test - public void customizeSimpleCacheManager() { + void customizeSimpleCacheManager() { CacheManagerCustomizers customizers = new CacheManagerCustomizers( Collections.singletonList(new CacheNamesCacheManagerCustomizer())); ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); @@ -50,7 +50,7 @@ public class CacheManagerCustomizersTests { } @Test - public void customizeShouldCheckGeneric() { + void customizeShouldCheckGeneric() { List> list = new ArrayList<>(); list.add(new TestCustomizer<>()); list.add(new TestConcurrentMapCacheManagerCustomizer()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index 70b52b35ef6..3ac1f9f0e1d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -35,13 +35,13 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CassandraAutoConfigurationTests { +class CassandraAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)); @Test - public void createClusterWithDefault() { + void createClusterWithDefault() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Cluster.class); assertThat(context.getBean(Cluster.class).getClusterName()).startsWith("cluster"); @@ -49,7 +49,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void createClusterWithOverrides() { + void createClusterWithOverrides() { this.contextRunner.withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> { assertThat(context).hasSingleBean(Cluster.class); assertThat(context.getBean(Cluster.class).getClusterName()).isEqualTo("testcluster"); @@ -57,7 +57,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void createCustomizeCluster() { + void createCustomizeCluster() { this.contextRunner.withUserConfiguration(MockCustomizerConfig.class).run((context) -> { assertThat(context).hasSingleBean(Cluster.class); assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class); @@ -65,7 +65,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void customizerOverridesAutoConfig() { + void customizerOverridesAutoConfig() { this.contextRunner.withUserConfiguration(SimpleCustomizerConfig.class) .withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> { assertThat(context).hasSingleBean(Cluster.class); @@ -74,7 +74,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void defaultPoolOptions() { + void defaultPoolOptions() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Cluster.class); PoolingOptions poolingOptions = context.getBean(Cluster.class).getConfiguration().getPoolingOptions(); @@ -87,7 +87,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void customizePoolOptions() { + void customizePoolOptions() { this.contextRunner.withPropertyValues("spring.data.cassandra.pool.idle-timeout=42", "spring.data.cassandra.pool.pool-timeout=52", "spring.data.cassandra.pool.heartbeat-interval=62", "spring.data.cassandra.pool.max-queue-size=72").run((context) -> { @@ -102,7 +102,7 @@ public class CassandraAutoConfigurationTests { } @Test - public void clusterFactoryIsCalledToCreateCluster() { + void clusterFactoryIsCalledToCreateCluster() { this.contextRunner.withUserConfiguration(ClusterFactoryConfig.class) .run((context) -> assertThat(context.getBean(TestClusterFactory.class).initializer).isNotNull()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java index d7ef8a5763a..b83453b846c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudServiceConnectorsAutoConfigurationTests.java @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class CloudServiceConnectorsAutoConfigurationTests { +class CloudServiceConnectorsAutoConfigurationTests { @Test - public void testOrder() { + void testOrder() { TestAutoConfigurationSorter sorter = new TestAutoConfigurationSorter(new CachingMetadataReaderFactory()); Collection classNames = new ArrayList<>(); classNames.add(MongoAutoConfiguration.class.getName()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java index 3580b6f95b5..39410492f76 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java @@ -30,18 +30,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Razib Shahriar */ -public class AbstractNestedConditionTests { +class AbstractNestedConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void validPhase() { + void validPhase() { this.contextRunner.withUserConfiguration(ValidConfig.class) .run((context) -> assertThat(context).hasBean("myBean")); } @Test - public void invalidMemberPhase() { + void invalidMemberPhase() { this.contextRunner.withUserConfiguration(InvalidConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) @@ -52,7 +52,7 @@ public class AbstractNestedConditionTests { } @Test - public void invalidNestedMemberPhase() { + void invalidNestedMemberPhase() { this.contextRunner.withUserConfiguration(DoubleNestedConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java index 85dd52f3e5f..a165daf68b0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java @@ -33,27 +33,27 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AllNestedConditions}. */ -public class AllNestedConditionsTests { +class AllNestedConditionsTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void neither() { + void neither() { this.contextRunner.withUserConfiguration(Config.class).run(match(false)); } @Test - public void propertyA() { + void propertyA() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a").run(match(false)); } @Test - public void propertyB() { + void propertyB() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b").run(match(false)); } @Test - public void both() { + void both() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a", "b:b").run(match(true)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java index 51efe6ea5b6..a64dbdf4bc0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java @@ -36,27 +36,27 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Dave Syer */ -public class AnyNestedConditionTests { +class AnyNestedConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void neither() { + void neither() { this.contextRunner.withUserConfiguration(Config.class).run(match(false)); } @Test - public void propertyA() { + void propertyA() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a").run(match(true)); } @Test - public void propertyB() { + void propertyB() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("b:b").run(match(true)); } @Test - public void both() { + void both() { this.contextRunner.withUserConfiguration(Config.class).withPropertyValues("a:a", "b:b").run(match(true)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java index 52b22fb5cce..e0af33381c1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class ConditionEvaluationReportAutoConfigurationImportListenerTests { +class ConditionEvaluationReportAutoConfigurationImportListenerTests { private ConditionEvaluationReportAutoConfigurationImportListener listener; @@ -51,7 +51,7 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { } @Test - public void shouldBeInSpringFactories() { + void shouldBeInSpringFactories() { List factories = SpringFactoriesLoader .loadFactories(AutoConfigurationImportListener.class, null); assertThat(factories) @@ -59,7 +59,7 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { } @Test - public void onAutoConfigurationImportEventShouldRecordCandidates() { + void onAutoConfigurationImportEventShouldRecordCandidates() { List candidateConfigurations = Collections.singletonList("Test"); Set exclusions = Collections.emptySet(); AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, @@ -70,7 +70,7 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { } @Test - public void onAutoConfigurationImportEventShouldRecordExclusions() { + void onAutoConfigurationImportEventShouldRecordExclusions() { List candidateConfigurations = Collections.emptyList(); Set exclusions = Collections.singleton("Test"); AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, candidateConfigurations, @@ -81,7 +81,7 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { } @Test - public void onAutoConfigurationImportEventShouldApplyExclusionsGlobally() { + void onAutoConfigurationImportEventShouldApplyExclusionsGlobally() { AutoConfigurationImportEvent event = new AutoConfigurationImportEvent(this, Arrays.asList("First", "Second"), Collections.emptySet()); this.listener.onAutoConfigurationImportEvent(event); @@ -94,7 +94,7 @@ public class ConditionEvaluationReportAutoConfigurationImportListenerTests { } @Test - public void onAutoConfigurationImportEventShouldApplyExclusionsGloballyWhenExclusionIsAlreadyApplied() { + void onAutoConfigurationImportEventShouldApplyExclusionsGloballyWhenExclusionIsAlreadyApplied() { AutoConfigurationImportEvent excludeEvent = new AutoConfigurationImportEvent(this, Collections.emptyList(), Collections.singleton("First")); this.listener.onAutoConfigurationImportEvent(excludeEvent); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index 46425c13a73..112f975b2ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -56,7 +56,7 @@ import static org.hamcrest.Matchers.nullValue; * @author Greg Turnquist * @author Phillip Webb */ -public class ConditionEvaluationReportTests { +class ConditionEvaluationReportTests { private DefaultListableBeanFactory beanFactory; @@ -85,13 +85,13 @@ public class ConditionEvaluationReportTests { } @Test - public void get() { + void get() { assertThat(this.report).isNotEqualTo(nullValue()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); } @Test - public void parent() { + void parent() { this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); @@ -104,7 +104,7 @@ public class ConditionEvaluationReportTests { } @Test - public void parentBottomUp() { + void parentBottomUp() { this.beanFactory = new DefaultListableBeanFactory(); // NB: overrides setup this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); @@ -116,7 +116,7 @@ public class ConditionEvaluationReportTests { } @Test - public void recordConditionEvaluations() { + void recordConditionEvaluations() { this.outcome1 = new ConditionOutcome(false, "m1"); this.outcome2 = new ConditionOutcome(false, "m2"); this.outcome3 = new ConditionOutcome(false, "m3"); @@ -141,13 +141,13 @@ public class ConditionEvaluationReportTests { } @Test - public void fullMatch() { + void fullMatch() { prepareMatches(true, true, true); assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isTrue(); } @Test - public void notFullMatch() { + void notFullMatch() { prepareMatches(true, false, true); assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()).isFalse(); } @@ -163,14 +163,14 @@ public class ConditionEvaluationReportTests { @Test @SuppressWarnings("resource") - public void springBootConditionPopulatesReport() { + void springBootConditionPopulatesReport() { ConditionEvaluationReport report = ConditionEvaluationReport .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource().size()).isNotEqualTo(0); } @Test - public void testDuplicateConditionAndOutcomes() { + void testDuplicateConditionAndOutcomes() { ConditionAndOutcome outcome1 = new ConditionAndOutcome(this.condition1, new ConditionOutcome(true, "Message 1")); ConditionAndOutcome outcome2 = new ConditionAndOutcome(this.condition2, @@ -188,7 +188,7 @@ public class ConditionEvaluationReportTests { } @Test - public void duplicateOutcomes() { + void duplicateOutcomes() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DuplicateConfig.class); ConditionEvaluationReport report = ConditionEvaluationReport.get(context.getBeanFactory()); String autoconfigKey = MultipartAutoConfiguration.class.getName(); @@ -206,7 +206,7 @@ public class ConditionEvaluationReportTests { } @Test - public void negativeOuterPositiveInnerBean() { + void negativeOuterPositiveInnerBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("test.present=true").applyTo(context); context.register(NegativeOuterConfig.class); @@ -221,7 +221,7 @@ public class ConditionEvaluationReportTests { } @Test - public void reportWhenSameShortNamePresentMoreThanOnceShouldUseFullyQualifiedName() { + void reportWhenSameShortNamePresentMoreThanOnceShouldUseFullyQualifiedName() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(WebMvcAutoConfiguration.class, org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration.class, @@ -236,7 +236,7 @@ public class ConditionEvaluationReportTests { } @Test - public void reportMessageWhenSameShortNamePresentMoreThanOnceShouldUseFullyQualifiedName() { + void reportMessageWhenSameShortNamePresentMoreThanOnceShouldUseFullyQualifiedName() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(WebMvcAutoConfiguration.class, org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java index ad7afdde95d..40d1cfce88f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java @@ -30,70 +30,70 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConditionMessageTests { +class ConditionMessageTests { @Test - public void isEmptyWhenEmptyShouldReturnTrue() { + void isEmptyWhenEmptyShouldReturnTrue() { ConditionMessage message = ConditionMessage.empty(); assertThat(message.isEmpty()).isTrue(); } @Test - public void isEmptyWhenNotEmptyShouldReturnFalse() { + void isEmptyWhenNotEmptyShouldReturnFalse() { ConditionMessage message = ConditionMessage.of("Test"); assertThat(message.isEmpty()).isFalse(); } @Test - public void toStringWhenEmptyShouldReturnEmptyString() { + void toStringWhenEmptyShouldReturnEmptyString() { ConditionMessage message = ConditionMessage.empty(); assertThat(message.toString()).isEqualTo(""); } @Test - public void toStringWhenHasMessageShouldReturnMessage() { + void toStringWhenHasMessageShouldReturnMessage() { ConditionMessage message = ConditionMessage.of("Test"); assertThat(message.toString()).isEqualTo("Test"); } @Test - public void appendWhenHasExistingMessageShouldAddSpace() { + void appendWhenHasExistingMessageShouldAddSpace() { ConditionMessage message = ConditionMessage.of("a").append("b"); assertThat(message.toString()).isEqualTo("a b"); } @Test - public void appendWhenAppendingNullShouldDoNothing() { + void appendWhenAppendingNullShouldDoNothing() { ConditionMessage message = ConditionMessage.of("a").append(null); assertThat(message.toString()).isEqualTo("a"); } @Test - public void appendWhenNoMessageShouldNotAddSpace() { + void appendWhenNoMessageShouldNotAddSpace() { ConditionMessage message = ConditionMessage.empty().append("b"); assertThat(message.toString()).isEqualTo("b"); } @Test - public void andConditionWhenUsingClassShouldIncludeCondition() { + void andConditionWhenUsingClassShouldIncludeCondition() { ConditionMessage message = ConditionMessage.empty().andCondition(Test.class).because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test - public void andConditionWhenUsingStringShouldIncludeCondition() { + void andConditionWhenUsingStringShouldIncludeCondition() { ConditionMessage message = ConditionMessage.empty().andCondition("@Test").because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test - public void andConditionWhenIncludingDetailsShouldIncludeCondition() { + void andConditionWhenIncludingDetailsShouldIncludeCondition() { ConditionMessage message = ConditionMessage.empty().andCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @Test - public void ofCollectionShouldCombine() { + void ofCollectionShouldCombine() { List messages = new ArrayList<>(); messages.add(ConditionMessage.of("a")); messages.add(ConditionMessage.of("b")); @@ -102,88 +102,88 @@ public class ConditionMessageTests { } @Test - public void ofCollectionWhenNullShouldReturnEmpty() { + void ofCollectionWhenNullShouldReturnEmpty() { ConditionMessage message = ConditionMessage.of((List) null); assertThat(message.isEmpty()).isTrue(); } @Test - public void forConditionShouldIncludeCondition() { + void forConditionShouldIncludeCondition() { ConditionMessage message = ConditionMessage.forCondition("@Test").because("OK"); assertThat(message.toString()).isEqualTo("@Test OK"); } @Test - public void forConditionShouldNotAddExtraSpaceWithEmptyCondition() { + void forConditionShouldNotAddExtraSpaceWithEmptyCondition() { ConditionMessage message = ConditionMessage.forCondition("").because("OK"); assertThat(message.toString()).isEqualTo("OK"); } @Test - public void forConditionWhenClassShouldIncludeCondition() { + void forConditionWhenClassShouldIncludeCondition() { ConditionMessage message = ConditionMessage.forCondition(Test.class, "(a=b)").because("OK"); assertThat(message.toString()).isEqualTo("@Test (a=b) OK"); } @Test - public void foundExactlyShouldConstructMessage() { + void foundExactlyShouldConstructMessage() { ConditionMessage message = ConditionMessage.forCondition(Test.class).foundExactly("abc"); assertThat(message.toString()).isEqualTo("@Test found abc"); } @Test - public void foundWhenSingleElementShouldUseSingular() { + void foundWhenSingleElementShouldUseSingular() { ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a"); assertThat(message.toString()).isEqualTo("@Test found bean a"); } @Test - public void foundNoneAtAllShouldConstructMessage() { + void foundNoneAtAllShouldConstructMessage() { ConditionMessage message = ConditionMessage.forCondition(Test.class).found("no beans").atAll(); assertThat(message.toString()).isEqualTo("@Test found no beans"); } @Test - public void foundWhenMultipleElementsShouldUsePlural() { + void foundWhenMultipleElementsShouldUsePlural() { ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans a, b, c"); } @Test - public void foundWhenQuoteStyleShouldQuote() { + void foundWhenQuoteStyleShouldQuote() { ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items(Style.QUOTE, "a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test found beans 'a', 'b', 'c'"); } @Test - public void didNotFindWhenSingleElementShouldUseSingular() { + void didNotFindWhenSingleElementShouldUseSingular() { ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a"); assertThat(message.toString()).isEqualTo("@Test did not find class a"); } @Test - public void didNotFindWhenMultipleElementsShouldUsePlural() { + void didNotFindWhenMultipleElementsShouldUsePlural() { ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a", "b", "c"); assertThat(message.toString()).isEqualTo("@Test did not find classes a, b, c"); } @Test - public void resultedInShouldConstructMessage() { + void resultedInShouldConstructMessage() { ConditionMessage message = ConditionMessage.forCondition(Test.class).resultedIn("Green"); assertThat(message.toString()).isEqualTo("@Test resulted in Green"); } @Test - public void notAvailableShouldConstructMessage() { + void notAvailableShouldConstructMessage() { ConditionMessage message = ConditionMessage.forCondition(Test.class).notAvailable("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is not available"); } @Test - public void availableShouldConstructMessage() { + void availableShouldConstructMessage() { ConditionMessage message = ConditionMessage.forCondition(Test.class).available("JMX"); assertThat(message.toString()).isEqualTo("@Test JMX is available"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index 9307ae4002f..acde1ec70c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -50,68 +50,68 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public class ConditionalOnBeanTests { +class ConditionalOnBeanTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void testNameOnBeanCondition() { + void testNameOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) .run(this::hasBarBean); } @Test - public void testNameAndTypeOnBeanCondition() { + void testNameAndTypeOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test - public void testNameOnBeanConditionReverseOrder() { + void testNameOnBeanConditionReverseOrder() { // Ideally this should be true this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test - public void testClassOnBeanCondition() { + void testClassOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassConfiguration.class) .run(this::hasBarBean); } @Test - public void testClassOnBeanClassNameCondition() { + void testClassOnBeanClassNameCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassNameConfiguration.class) .run(this::hasBarBean); } @Test - public void testOnBeanConditionWithXml() { + void testOnBeanConditionWithXml() { this.contextRunner.withUserConfiguration(XmlConfiguration.class, OnBeanNameConfiguration.class) .run(this::hasBarBean); } @Test - public void testOnBeanConditionWithCombinedXml() { + void testOnBeanConditionWithCombinedXml() { // Ideally this should be true this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test - public void testAnnotationOnBeanCondition() { + void testAnnotationOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) .run(this::hasBarBean); } @Test - public void testOnMissingBeanType() { + void testOnMissingBeanType() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanMissingClassConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test - public void withPropertyPlaceholderClassName() { + void withPropertyPlaceholderClassName() { this.contextRunner .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, WithPropertyPlaceholderClassName.class, OnBeanClassConfiguration.class) @@ -120,7 +120,7 @@ public class ConditionalOnBeanTests { } @Test - public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { + void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { this.contextRunner .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) .run((context) -> { @@ -135,7 +135,7 @@ public class ConditionalOnBeanTests { } @Test - public void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { + void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { this.contextRunner.withUserConfiguration(OriginalDefinition.class, OverridingDefinition.class, ConsumingConfiguration.class).run((context) -> { assertThat(context).hasBean("testBean"); @@ -145,7 +145,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfMissingBeanDoesNotMatch() { + void parameterizedContainerWhenValueIsOfMissingBeanDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) @@ -153,7 +153,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfExistingBeanMatches() { + void parameterizedContainerWhenValueIsOfExistingBeanMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) .run((context) -> assertThat(context) @@ -161,7 +161,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfMissingBeanRegistrationDoesNotMatch() { + void parameterizedContainerWhenValueIsOfMissingBeanRegistrationDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) @@ -169,7 +169,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfExistingBeanRegistrationMatches() { + void parameterizedContainerWhenValueIsOfExistingBeanRegistrationMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) @@ -178,7 +178,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenReturnTypeIsOfExistingBeanMatches() { + void parameterizedContainerWhenReturnTypeIsOfExistingBeanMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnTypeConfig.class) @@ -187,7 +187,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationMatches() { + void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnTypeConfig.class) @@ -196,7 +196,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanMatches() { + void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) @@ -205,7 +205,7 @@ public class ConditionalOnBeanTests { } @Test - public void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationMatches() { + void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java index 2b49d7c1f80..5a705d620b1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java @@ -35,18 +35,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public class ConditionalOnClassTests { +class ConditionalOnClassTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void testVanillaOnClassCondition() { + void testVanillaOnClassCondition() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, FooConfiguration.class) .run(this::hasBarBean); } @Test - public void testMissingOnClassCondition() { + void testMissingOnClassCondition() { this.contextRunner.withUserConfiguration(MissingConfiguration.class, FooConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean("bar"); assertThat(context).hasBean("foo"); @@ -55,18 +55,18 @@ public class ConditionalOnClassTests { } @Test - public void testOnClassConditionWithXml() { + void testOnClassConditionWithXml() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class) .run(this::hasBarBean); } @Test - public void testOnClassConditionWithCombinedXml() { + void testOnClassConditionWithCombinedXml() { this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class).run(this::hasBarBean); } @Test - public void onClassConditionOutputShouldNotContainConditionalOnMissingClassInMessage() { + void onClassConditionOutputShouldNotContainConditionalOnMissingClassInMessage() { this.contextRunner.withUserConfiguration(BasicConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java index dbff7efe2e8..6545aab8de5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java @@ -28,24 +28,24 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConditionalOnCloudPlatform @ConditionalOnCloudPlatform}. */ -public class ConditionalOnCloudPlatformTests { +class ConditionalOnCloudPlatformTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() { + void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { + void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); } @Test - public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { + void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class) .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index c6158e08423..f6d4cfbc723 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -37,30 +37,30 @@ import static org.mockito.Mockito.mock; * @author Dave Syer * @author Stephane Nicoll */ -public class ConditionalOnExpressionTests { +class ConditionalOnExpressionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void expressionIsTrue() { + void expressionIsTrue() { this.contextRunner.withUserConfiguration(BasicConfiguration.class) .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo")); } @Test - public void expressionEvaluatesToTrueRegistersBean() { + void expressionEvaluatesToTrueRegistersBean() { this.contextRunner.withUserConfiguration(MissingConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void expressionEvaluatesToFalseDoesNotRegisterBean() { + void expressionEvaluatesToFalseDoesNotRegisterBean() { this.contextRunner.withUserConfiguration(NullConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void expressionEvaluationWithNoBeanFactoryDoesNotMatch() { + void expressionEvaluationWithNoBeanFactoryDoesNotMatch() { OnExpressionCondition condition = new OnExpressionCondition(); MockEnvironment environment = new MockEnvironment(); ConditionContext conditionContext = mock(ConditionContext.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index 395aeb98573..3144d7556db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -22,12 +22,13 @@ import java.util.ServiceLoader; import java.util.function.Function; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.Range; import org.springframework.boot.system.JavaVersion; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.Assume; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; @@ -40,33 +41,33 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Oliver Gierke * @author Phillip Webb */ -public class ConditionalOnJavaTests { +class ConditionalOnJavaTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); private final OnJavaCondition condition = new OnJavaCondition(); @Test - public void doesNotMatchIfBetterVersionIsRequired() { - Assume.javaEight(); + @EnabledOnJre(JRE.JAVA_8) + void doesNotMatchIfBetterVersionIsRequired() { this.contextRunner.withUserConfiguration(Java9Required.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void doesNotMatchIfLowerIsRequired() { + void doesNotMatchIfLowerIsRequired() { this.contextRunner.withUserConfiguration(Java7Required.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void matchesIfVersionIsInRange() { + void matchesIfVersionIsInRange() { this.contextRunner.withUserConfiguration(Java8Required.class) .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test - public void boundsTests() { + void boundsTests() { testBounds(Range.EQUAL_OR_NEWER, JavaVersion.NINE, JavaVersion.EIGHT, true); testBounds(Range.EQUAL_OR_NEWER, JavaVersion.EIGHT, JavaVersion.EIGHT, true); testBounds(Range.EQUAL_OR_NEWER, JavaVersion.EIGHT, JavaVersion.NINE, false); @@ -76,28 +77,28 @@ public class ConditionalOnJavaTests { } @Test - public void equalOrNewerMessage() { + void equalOrNewerMessage() { ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, JavaVersion.NINE, JavaVersion.EIGHT); assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (1.8 or newer) found 1.9"); } @Test - public void olderThanMessage() { + void olderThanMessage() { ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, JavaVersion.NINE, JavaVersion.EIGHT); assertThat(outcome.getMessage()).isEqualTo("@ConditionalOnJava (older than 1.8) found 1.9"); } @Test - public void java8IsDetected() throws Exception { - Assume.javaEight(); + @EnabledOnJre(JRE.JAVA_8) + void java8IsDetected() throws Exception { assertThat(getJavaVersion()).isEqualTo("1.8"); } @Test - public void java8IsTheFallback() throws Exception { - Assume.javaEight(); + @EnabledOnJre(JRE.JAVA_8) + void java8IsTheFallback() throws Exception { assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)).isEqualTo("1.8"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index 794fa68076f..fe55b6c2416 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class ConditionalOnJndiTests { +class ConditionalOnJndiTests { private ClassLoader threadContextClassLoader; @@ -72,27 +72,27 @@ public class ConditionalOnJndiTests { } @Test - public void jndiNotAvailable() { + void jndiNotAvailable() { this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void jndiAvailable() { + void jndiAvailable() { setupJndi(); this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test - public void jndiLocationNotBound() { + void jndiLocationNotBound() { setupJndi(); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void jndiLocationBound() { + void jndiLocationBound() { setupJndi(); TestableInitialContextFactory.bind("java:/FooManager", new Object()); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) @@ -100,13 +100,13 @@ public class ConditionalOnJndiTests { } @Test - public void jndiLocationNotFound() { + void jndiLocationNotFound() { ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a")); assertThat(outcome.isMatch()).isFalse(); } @Test - public void jndiLocationFound() { + void jndiLocationFound() { this.condition.setFoundLocation("java:/b"); ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a", "java:/b")); assertThat(outcome.isMatch()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index 8a0be3def18..1f9c9bec48c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -64,7 +64,7 @@ public class ConditionalOnMissingBeanTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void testNameOnMissingBeanCondition() { + void testNameOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) .run((context) -> { assertThat(context).doesNotHaveBean("bar"); @@ -73,7 +73,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testNameOnMissingBeanConditionReverseOrder() { + void testNameOnMissingBeanConditionReverseOrder() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) .run((context) -> { // Ideally this would be doesNotHaveBean, but the ordering is a @@ -84,7 +84,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testNameAndTypeOnMissingBeanCondition() { + void testNameAndTypeOnMissingBeanCondition() { // Arguably this should be hasBean, but as things are implemented the conditions // specified in the different attributes of @ConditionalOnBean are combined with // logical OR (not AND) so if any of them match the condition is true. @@ -93,7 +93,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void hierarchyConsidered() { + void hierarchyConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) .run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(HierarchyConsidered.class) @@ -101,7 +101,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void hierarchyNotConsidered() { + void hierarchyNotConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) .run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(HierarchyNotConsidered.class) @@ -109,13 +109,13 @@ public class ConditionalOnMissingBeanTests { } @Test - public void impliedOnBeanMethod() { + void impliedOnBeanMethod() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class, ImpliedOnBeanMethod.class) .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); } @Test - public void testAnnotationOnMissingBeanCondition() { + void testAnnotationOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) .run((context) -> { assertThat(context).doesNotHaveBean("bar"); @@ -124,7 +124,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { + void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { // Rigorous test for SPR-11069 this.contextRunner .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, @@ -137,7 +137,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithFactoryBean() { + void testOnMissingBeanConditionWithFactoryBean() { this.contextRunner .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -145,7 +145,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithComponentScannedFactoryBean() { + void testOnMissingBeanConditionWithComponentScannedFactoryBean() { this.contextRunner .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -153,7 +153,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { + void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { this.contextRunner .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -161,7 +161,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { + void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { this.contextRunner .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -170,7 +170,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithConcreteFactoryBean() { + void testOnMissingBeanConditionWithConcreteFactoryBean() { this.contextRunner .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -178,7 +178,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { + void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { // We could not tell that the FactoryBean would ultimately create an ExampleBean this.contextRunner .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, @@ -187,7 +187,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithRegisteredFactoryBean() { + void testOnMissingBeanConditionWithRegisteredFactoryBean() { this.contextRunner .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -195,7 +195,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { + void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { this.contextRunner .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -203,7 +203,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { + void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { this.contextRunner .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -211,7 +211,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithFactoryBeanInXml() { + void testOnMissingBeanConditionWithFactoryBeanInXml() { this.contextRunner .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) @@ -219,7 +219,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithIgnoredSubclass() { + void testOnMissingBeanConditionWithIgnoredSubclass() { this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { assertThat(context).getBeans(ExampleBean.class).hasSize(2); @@ -228,7 +228,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void testOnMissingBeanConditionWithIgnoredSubclassByName() { + void testOnMissingBeanConditionWithIgnoredSubclassByName() { this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { assertThat(context).getBeans(ExampleBean.class).hasSize(2); @@ -237,7 +237,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void grandparentIsConsideredWhenUsingAncestorsStrategy() { + void grandparentIsConsideredWhenUsingAncestorsStrategy() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class) .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) .run((parent) -> new ApplicationContextRunner().withParent(parent) @@ -247,14 +247,14 @@ public class ConditionalOnMissingBeanTests { } @Test - public void currentContextIsIgnoredWhenUsingAncestorsStrategy() { + void currentContextIsIgnoredWhenUsingAncestorsStrategy() { this.contextRunner.run((parent) -> new ApplicationContextRunner().withParent(parent) .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); } @Test - public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { + void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { this.contextRunner.withUserConfiguration(ConcreteFactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean("bar"); @@ -263,7 +263,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfMissingBeanMatches() { + void parameterizedContainerWhenValueIsOfMissingBeanMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) @@ -272,14 +272,14 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfExistingBeanDoesNotMatch() { + void parameterizedContainerWhenValueIsOfExistingBeanDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test - public void parameterizedContainerWhenValueIsOfMissingBeanRegistrationMatches() { + void parameterizedContainerWhenValueIsOfMissingBeanRegistrationMatches() { this.contextRunner .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) @@ -288,7 +288,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenValueIsOfExistingBeanRegistrationDoesNotMatch() { + void parameterizedContainerWhenValueIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithValueConfig.class) @@ -296,7 +296,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenReturnTypeIsOfExistingBeanDoesNotMatch() { + void parameterizedContainerWhenReturnTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnTypeConfig.class) @@ -304,7 +304,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationDoesNotMatch() { + void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnTypeConfig.class) @@ -312,7 +312,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanDoesNotMatch() { + void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) @@ -320,7 +320,7 @@ public class ConditionalOnMissingBeanTests { } @Test - public void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationDoesNotMatch() { + void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, ParameterizedConditionWithReturnRegistrationTypeConfig.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java index 723c276b97a..5a5a1818d98 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.autoconfigure.condition; +import org.junit.After; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; @@ -42,7 +42,7 @@ public class ConditionalOnMissingBeanWithFilteredClasspathTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @AfterEach + @After public void closeContext() { this.context.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java index 21b8a789178..bfd39cf9079 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java @@ -29,12 +29,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class ConditionalOnMissingClassTests { +class ConditionalOnMissingClassTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void testVanillaOnClassCondition() { + void testVanillaOnClassCondition() { this.context.register(BasicConfiguration.class, FooConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); @@ -42,7 +42,7 @@ public class ConditionalOnMissingClassTests { } @Test - public void testMissingOnClassCondition() { + void testMissingOnClassCondition() { this.context.register(MissingConfiguration.class, FooConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java index 0baf4744b56..285f4576c32 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java @@ -37,23 +37,23 @@ import static org.assertj.core.api.Assertions.entry; * @author Dave Syer * @author Stephane Nicoll */ -public class ConditionalOnNotWebApplicationTests { +class ConditionalOnNotWebApplicationTests { @Test - public void testNotWebApplicationWithServletContext() { + void testNotWebApplicationWithServletContext() { new WebApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void testNotWebApplicationWithReactiveContext() { + void testNotWebApplicationWithReactiveContext() { new ReactiveWebApplicationContextRunner() .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test - public void testNotWebApplication() { + void testNotWebApplication() { new ApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index 27b4c19ab20..f9e2eaa5765 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Phillip Webb * @author Andy Wilkinson */ -public class ConditionalOnPropertyTests { +class ConditionalOnPropertyTests { private ConfigurableApplicationContext context; @@ -59,148 +59,148 @@ public class ConditionalOnPropertyTests { } @Test - public void allPropertiesAreDefined() { + void allPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void notAllPropertiesAreDefined() { + void notAllPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void propertyValueEqualsFalse() { + void propertyValueEqualsFalse() { load(MultiplePropertiesRequiredConfiguration.class, "property1=false", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void propertyValueEqualsFALSE() { + void propertyValueEqualsFALSE() { load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", "property2=value2"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void relaxedName() { + void relaxedName() { load(RelaxedPropertiesRequiredConfiguration.class, "spring.theRelaxedProperty=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void prefixWithoutPeriod() { + void prefixWithoutPeriod() { load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, "spring.property=value1"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test // Enabled by default - public void enabledIfNotConfiguredOtherwise() { + void enabledIfNotConfiguredOtherwise() { load(EnabledIfNotConfiguredOtherwiseConfig.class); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void enabledIfNotConfiguredOtherwiseWithConfig() { + void enabledIfNotConfiguredOtherwiseWithConfig() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:false"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void enabledIfNotConfiguredOtherwiseWithConfigDifferentCase() { + void enabledIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.my-property:FALSE"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test // Disabled by default - public void disableIfNotConfiguredOtherwise() { + void disableIfNotConfiguredOtherwise() { load(DisabledIfNotConfiguredOtherwiseConfig.class); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void disableIfNotConfiguredOtherwiseWithConfig() { + void disableIfNotConfiguredOtherwiseWithConfig() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:true"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void disableIfNotConfiguredOtherwiseWithConfigDifferentCase() { + void disableIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myproperty:TrUe"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void simpleValueIsSet() { + void simpleValueIsSet() { load(SimpleValueConfig.class, "simple.myProperty:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void caseInsensitive() { + void caseInsensitive() { load(SimpleValueConfig.class, "simple.myProperty:BaR"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void defaultValueIsSet() { + void defaultValueIsSet() { load(DefaultValueConfig.class, "simple.myProperty:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void defaultValueIsNotSet() { + void defaultValueIsNotSet() { load(DefaultValueConfig.class); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void defaultValueIsSetDifferentValue() { + void defaultValueIsSetDifferentValue() { load(DefaultValueConfig.class, "simple.myProperty:another"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void prefix() { + void prefix() { load(PrefixValueConfig.class, "simple.myProperty:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void relaxedEnabledByDefault() { + void relaxedEnabledByDefault() { load(PrefixValueConfig.class, "simple.myProperty:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void multiValuesAllSet() { + void multiValuesAllSet() { load(MultiValuesConfig.class, "simple.my-property:bar", "simple.my-another-property:bar"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void multiValuesOnlyOneSet() { + void multiValuesOnlyOneSet() { load(MultiValuesConfig.class, "simple.my-property:bar"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void usingValueAttribute() { + void usingValueAttribute() { load(ValueAttribute.class, "some.property"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void nameOrValueMustBeSpecified() { + void nameOrValueMustBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) .satisfies(causeMessageContaining( "The name or value attribute of @ConditionalOnProperty must be specified")); } @Test - public void nameAndValueMustNotBeSpecified() { + void nameAndValueMustNotBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) .satisfies(causeMessageContaining( "The name and value attributes of @ConditionalOnProperty are exclusive")); @@ -211,37 +211,37 @@ public class ConditionalOnPropertyTests { } @Test - public void metaAnnotationConditionMatchesWhenPropertyIsSet() { + void metaAnnotationConditionMatchesWhenPropertyIsSet() { load(MetaAnnotation.class, "my.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() { + void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() { load(MetaAnnotation.class); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyDirectPropertyIsSet() { + void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyDirectPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.other.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyMetaPropertyIsSet() { + void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyMetaPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void metaAndDirectAnnotationConditionDoesNotMatchWhenNeitherPropertyIsSet() { + void metaAndDirectAnnotationConditionDoesNotMatchWhenNeitherPropertyIsSet() { load(MetaAnnotationAndDirectAnnotation.class); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() { + void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() { load(MetaAnnotationAndDirectAnnotation.class, "my.feature.enabled=true", "my.other.feature.enabled=true"); assertThat(this.context.containsBean("foo")).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java index bc7d4e20d53..97143b68bac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java @@ -30,12 +30,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class ConditionalOnResourceTests { +class ConditionalOnResourceTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void testResourceExists() { + void testResourceExists() { this.context.register(BasicConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("foo")).isTrue(); @@ -43,7 +43,7 @@ public class ConditionalOnResourceTests { } @Test - public void testResourceExistsWithPlaceholder() { + void testResourceExistsWithPlaceholder() { TestPropertyValues.of("schema=schema.sql").applyTo(this.context); this.context.register(PlaceholderConfiguration.class); this.context.refresh(); @@ -52,7 +52,7 @@ public class ConditionalOnResourceTests { } @Test - public void testResourceNotExists() { + void testResourceNotExists() { this.context.register(MissingConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("foo")).isFalse(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index 64ec1f556e8..a6a78e4667f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class ConditionalOnSingleCandidateTests { +class ConditionalOnSingleCandidateTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -45,20 +45,20 @@ public class ConditionalOnSingleCandidateTests { } @Test - public void singleCandidateNoCandidate() { + void singleCandidateNoCandidate() { load(OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test - public void singleCandidateOneCandidate() { + void singleCandidateOneCandidate() { load(FooConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isTrue(); assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test - public void singleCandidateInAncestorsOneCandidateInCurrent() { + void singleCandidateInAncestorsOneCandidateInCurrent() { load(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.register(FooConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class); @@ -69,7 +69,7 @@ public class ConditionalOnSingleCandidateTests { } @Test - public void singleCandidateInAncestorsOneCandidateInParent() { + void singleCandidateInAncestorsOneCandidateInParent() { load(FooConfiguration.class); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.register(OnBeanSingleCandidateInAncestorsConfiguration.class); @@ -81,7 +81,7 @@ public class ConditionalOnSingleCandidateTests { } @Test - public void singleCandidateInAncestorsOneCandidateInGrandparent() { + void singleCandidateInAncestorsOneCandidateInGrandparent() { load(FooConfiguration.class); AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.setParent(this.context); @@ -97,40 +97,40 @@ public class ConditionalOnSingleCandidateTests { } @Test - public void singleCandidateMultipleCandidates() { + void singleCandidateMultipleCandidates() { load(FooConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test - public void singleCandidateMultipleCandidatesOnePrimary() { + void singleCandidateMultipleCandidatesOnePrimary() { load(FooPrimaryConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isTrue(); assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test - public void singleCandidateMultipleCandidatesMultiplePrimary() { + void singleCandidateMultipleCandidatesMultiplePrimary() { load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, OnBeanSingleCandidateConfiguration.class); assertThat(this.context.containsBean("baz")).isFalse(); } @Test - public void invalidAnnotationTwoTypes() { + void invalidAnnotationTwoTypes() { assertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.class)) .withCauseInstanceOf(IllegalArgumentException.class) .withMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); } @Test - public void invalidAnnotationNoType() { + void invalidAnnotationNoType() { assertThatIllegalStateException().isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.class)) .withCauseInstanceOf(IllegalArgumentException.class) .withMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); } @Test - public void singleCandidateMultipleCandidatesInContextHierarchy() { + void singleCandidateMultipleCandidatesInContextHierarchy() { load(FooPrimaryConfiguration.class, BarConfiguration.class); try (AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext()) { child.setParent(this.context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java index 8f148091e5e..7b90675bac9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.entry; * @author Dave Syer * @author Stephane Nicoll */ -public class ConditionalOnWebApplicationTests { +class ConditionalOnWebApplicationTests { private ConfigurableApplicationContext context; @@ -53,7 +53,7 @@ public class ConditionalOnWebApplicationTests { } @Test - public void testWebApplicationWithServletContext() { + void testWebApplicationWithServletContext() { AnnotationConfigServletWebApplicationContext ctx = new AnnotationConfigServletWebApplicationContext(); ctx.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); @@ -65,7 +65,7 @@ public class ConditionalOnWebApplicationTests { } @Test - public void testWebApplicationWithReactiveContext() { + void testWebApplicationWithReactiveContext() { AnnotationConfigReactiveWebApplicationContext context = new AnnotationConfigReactiveWebApplicationContext(); context.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); @@ -76,7 +76,7 @@ public class ConditionalOnWebApplicationTests { } @Test - public void testNonWebApplication() { + void testNonWebApplication() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AnyWebApplicationConfiguration.class, ServletWebApplicationConfiguration.class, ReactiveWebApplicationConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java index 903f960ad55..2fb26e96e9a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java @@ -32,31 +32,31 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link NoneNestedConditions}. */ -public class NoneNestedConditionsTests { +class NoneNestedConditionsTests { @Test - public void neither() { + void neither() { AnnotationConfigApplicationContext context = load(Config.class); assertThat(context.containsBean("myBean")).isTrue(); context.close(); } @Test - public void propertyA() { + void propertyA() { AnnotationConfigApplicationContext context = load(Config.class, "a:a"); assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test - public void propertyB() { + void propertyB() { AnnotationConfigApplicationContext context = load(Config.class, "b:b"); assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test - public void both() { + void both() { AnnotationConfigApplicationContext context = load(Config.class, "a:a", "b:b"); assertThat(context.containsBean("myBean")).isFalse(); context.close(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java index aa86b9d45cf..dbe159681fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OnClassConditionAutoConfigurationImportFilterTests { +class OnClassConditionAutoConfigurationImportFilterTests { private OnClassCondition filter = new OnClassCondition(); @@ -46,20 +46,20 @@ public class OnClassConditionAutoConfigurationImportFilterTests { } @Test - public void shouldBeRegistered() { + void shouldBeRegistered() { assertThat(SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, null)) .hasAtLeastOneElementOfType(OnClassCondition.class); } @Test - public void matchShouldMatchClasses() { + void matchShouldMatchClasses() { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; boolean[] result = this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); assertThat(result).containsExactly(true, false); } @Test - public void matchShouldRecordOutcome() { + void matchShouldRecordOutcome() { String[] autoConfigurationClasses = new String[] { "test.match", "test.nomatch" }; this.filter.match(autoConfigurationClasses, getAutoConfigurationMetadata()); ConditionEvaluationReport report = ConditionEvaluationReport.get(this.beanFactory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java index 1db5949021f..b483749930f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java @@ -30,36 +30,36 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class OnPropertyListConditionTests { +class OnPropertyListConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfig.class); @Test - public void propertyNotDefined() { + void propertyNotDefined() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void propertyDefinedAsCommaSeparated() { + void propertyDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.test.my-list=value1") .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void propertyDefinedAsList() { + void propertyDefinedAsList() { this.contextRunner.withPropertyValues("spring.test.my-list[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void propertyDefinedAsCommaSeparatedRelaxed() { + void propertyDefinedAsCommaSeparatedRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList=value1") .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void propertyDefinedAsListRelaxed() { + void propertyDefinedAsListRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java index 1fd0a264fb6..0788587d1ba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ResourceConditionTests { +class ResourceConditionTests { private ConfigurableApplicationContext context; @@ -45,19 +45,19 @@ public class ResourceConditionTests { } @Test - public void defaultResourceAndNoExplicitKey() { + void defaultResourceAndNoExplicitKey() { load(DefaultLocationConfiguration.class); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void unknownDefaultLocationAndNoExplicitKey() { + void unknownDefaultLocationAndNoExplicitKey() { load(UnknownDefaultLocationConfiguration.class); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void unknownDefaultLocationAndExplicitKeyToResource() { + void unknownDefaultLocationAndExplicitKeyToResource() { load(UnknownDefaultLocationConfiguration.class, "spring.foo.test.config=logging.properties"); assertThat(this.context.containsBean("foo")).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index d7bbaa7de6a..f0fdb4d270c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -33,16 +33,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Phillip Webb */ @SuppressWarnings("resource") -public class SpringBootConditionTests { +class SpringBootConditionTests { @Test - public void sensibleClassException() { + void sensibleClassException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); } @Test - public void sensibleMethodException() { + void sensibleMethodException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java index b4702c978ff..7c72e1bd692 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConfigurationPropertiesAutoConfigurationTests { +class ConfigurationPropertiesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -45,13 +45,13 @@ public class ConfigurationPropertiesAutoConfigurationTests { } @Test - public void processAnnotatedBean() { + void processAnnotatedBean() { load(new Class[] { AutoConfig.class, SampleBean.class }, "foo.name:test"); assertThat(this.context.getBean(SampleBean.class).getName()).isEqualTo("test"); } @Test - public void processAnnotatedBeanNoAutoConfig() { + void processAnnotatedBeanNoAutoConfig() { load(new Class[] { SampleBean.class }, "foo.name:test"); assertThat(this.context.getBean(SampleBean.class).getName()).isEqualTo("default"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java index 3735076dc74..a1f4e607093 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationIntegrationTests.java @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest("spring.messages.basename:test/messages") @ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext -public class MessageSourceAutoConfigurationIntegrationTests { +class MessageSourceAutoConfigurationIntegrationTests { @Autowired private ApplicationContext context; @Test - public void testMessageSourceFromPropertySourceAnnotation() { + void testMessageSourceFromPropertySourceAnnotation() { assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java index 595ffc015d2..8a605a6010c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationProfileTests.java @@ -39,13 +39,13 @@ import static org.assertj.core.api.Assertions.assertThat; @ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @ActiveProfiles("switch-messages") @DirtiesContext -public class MessageSourceAutoConfigurationProfileTests { +class MessageSourceAutoConfigurationProfileTests { @Autowired private ApplicationContext context; @Test - public void testMessageSourceFromPropertySourceAnnotation() { + void testMessageSourceFromPropertySourceAnnotation() { assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index a27e7e022fe..8579f73ece0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -42,19 +42,19 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Kedar Joshi */ -public class MessageSourceAutoConfigurationTests { +class MessageSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); @Test - public void testDefaultMessageSource() { + void testDefaultMessageSource() { this.contextRunner.run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) .isEqualTo("Foo message")); } @Test - public void propertiesBundleWithSlashIsDetected() { + void propertiesBundleWithSlashIsDetected() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages").run((context) -> { assertThat(context).hasSingleBean(MessageSource.class); assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); @@ -62,7 +62,7 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void propertiesBundleWithDotIsDetected() { + void propertiesBundleWithDotIsDetected() { this.contextRunner.withPropertyValues("spring.messages.basename:test.messages").run((context) -> { assertThat(context).hasSingleBean(MessageSource.class); assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); @@ -70,21 +70,21 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void testEncodingWorks() { + void testEncodingWorks() { this.contextRunner.withPropertyValues("spring.messages.basename:test/swedish") .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) .isEqualTo("Some text with some swedish öäå!")); } @Test - public void testCacheDurationNoUnit() { + void testCacheDurationNoUnit() { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") .run(assertCache(10 * 1000)); } @Test - public void testCacheDurationWithUnit() { + void testCacheDurationWithUnit() { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") .run(assertCache(60 * 1000)); @@ -98,7 +98,7 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void testMultipleMessageSourceCreated() { + void testMultipleMessageSourceCreated() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages,test/messages2") .run((context) -> { assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); @@ -107,7 +107,7 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void testBadEncoding() { + void testBadEncoding() { // Bad encoding just means the messages are ignored this.contextRunner.withPropertyValues("spring.messages.encoding:rubbish") .run((context) -> assertThat(context.getMessage("foo", null, "blah", Locale.UK)).isEqualTo("blah")); @@ -115,20 +115,20 @@ public class MessageSourceAutoConfigurationTests { @Test @Disabled("Expected to fail per gh-1075") - public void testMessageSourceFromPropertySourceAnnotation() { + void testMessageSourceFromPropertySourceAnnotation() { this.contextRunner.withUserConfiguration(Config.class).run( (context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); } @Test - public void testFallbackDefault() { + void testFallbackDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") .run((context) -> assertThat(context.getBean(MessageSource.class)) .hasFieldOrPropertyWithValue("fallbackToSystemLocale", true)); } @Test - public void testFallbackTurnOff() { + void testFallbackTurnOff() { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.fallback-to-system-locale:false") @@ -137,14 +137,14 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void testFormatMessageDefault() { + void testFormatMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") .run((context) -> assertThat(context.getBean(MessageSource.class)) .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false)); } @Test - public void testFormatMessageOn() { + void testFormatMessageOn() { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.always-use-message-format:true") @@ -153,14 +153,14 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void testUseCodeAsDefaultMessageDefault() { + void testUseCodeAsDefaultMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") .run((context) -> assertThat(context.getBean(MessageSource.class)) .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false)); } @Test - public void testUseCodeAsDefaultMessageOn() { + void testUseCodeAsDefaultMessageOn() { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.use-code-as-default-message:true") @@ -169,13 +169,13 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void existingMessageSourceIsPreferred() { + void existingMessageSourceIsPreferred() { this.contextRunner.withUserConfiguration(CustomMessageSourceConfiguration.class) .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); } @Test - public void existingMessageSourceInParentIsIgnored() { + void existingMessageSourceInParentIsIgnored() { this.contextRunner.run((parent) -> this.contextRunner.withParent(parent) .withPropertyValues("spring.messages.basename:test/messages") .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) @@ -183,7 +183,7 @@ public class MessageSourceAutoConfigurationTests { } @Test - public void messageSourceWithNonStandardBeanNameIsIgnored() { + void messageSourceWithNonStandardBeanNameIsIgnored() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java index 63a55d70769..bc64bc198d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class PropertyPlaceholderAutoConfigurationTests { +class PropertyPlaceholderAutoConfigurationTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -46,7 +46,7 @@ public class PropertyPlaceholderAutoConfigurationTests { } @Test - public void propertyPlaceholders() { + void propertyPlaceholders() { this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class); TestPropertyValues.of("foo:two").applyTo(this.context); this.context.refresh(); @@ -54,7 +54,7 @@ public class PropertyPlaceholderAutoConfigurationTests { } @Test - public void propertyPlaceholdersOverride() { + void propertyPlaceholdersOverride() { this.context.register(PropertyPlaceholderAutoConfiguration.class, PlaceholderConfig.class, PlaceholdersOverride.class); TestPropertyValues.of("foo:two").applyTo(this.context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java index fcdac959b17..da7c1c844e0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java @@ -21,8 +21,8 @@ import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseBucket; import com.couchbase.client.java.cluster.ClusterInfo; import com.couchbase.client.java.env.CouchbaseEnvironment; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -38,23 +38,21 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class CouchbaseAutoConfigurationIntegrationTests { +@ExtendWith(LocalCouchbaseServer.class) +class CouchbaseAutoConfigurationIntegrationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class)); - @Rule - public final CouchbaseTestServer couchbase = new CouchbaseTestServer(); - @Test - public void defaultConfiguration() { + void defaultConfiguration() { this.contextRunner.withPropertyValues("spring.couchbase.bootstrapHosts=localhost") .run((context) -> assertThat(context).hasSingleBean(Cluster.class).hasSingleBean(ClusterInfo.class) .hasSingleBean(CouchbaseEnvironment.class).hasSingleBean(Bucket.class)); } @Test - public void customConfiguration() { + void customConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class) .withPropertyValues("spring.couchbase.bootstrapHosts=localhost").run((context) -> { assertThat(context.getBeansOfType(Cluster.class)).hasSize(2); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java index fcdaeeb3436..8859376f18d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java @@ -41,18 +41,18 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CouchbaseAutoConfigurationTests { +class CouchbaseAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, CouchbaseAutoConfiguration.class)); @Test - public void bootstrapHostsIsRequired() { + void bootstrapHostsIsRequired() { this.contextRunner.run(this::assertNoCouchbaseBeans); } @Test - public void bootstrapHostsNotRequiredIfCouchbaseConfigurerIsSet() { + void bootstrapHostsNotRequiredIfCouchbaseConfigurerIsSet() { this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class).run((context) -> { assertThat(context).hasSingleBean(CouchbaseTestConfigurer.class); // No beans are going to be created @@ -61,7 +61,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void bootstrapHostsIgnoredIfCouchbaseConfigurerIsSet() { + void bootstrapHostsIgnoredIfCouchbaseConfigurerIsSet() { this.contextRunner.withUserConfiguration(CouchbaseTestConfigurer.class) .withPropertyValues("spring.couchbase.bootstrapHosts=localhost").run((context) -> { assertThat(context).hasSingleBean(CouchbaseTestConfigurer.class); @@ -76,7 +76,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void customizeEnvEndpoints() { + void customizeEnvEndpoints() { testCouchbaseEnv((env) -> { assertThat(env.kvServiceConfig().minEndpoints()).isEqualTo(2); assertThat(env.kvServiceConfig().maxEndpoints()).isEqualTo(2); @@ -91,7 +91,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void customizeEnvEndpointsUsesNewInfrastructure() { + void customizeEnvEndpointsUsesNewInfrastructure() { testCouchbaseEnv((env) -> { assertThat(env.queryServiceConfig().minEndpoints()).isEqualTo(3); assertThat(env.queryServiceConfig().maxEndpoints()).isEqualTo(5); @@ -104,7 +104,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void customizeEnvEndpointsUsesNewInfrastructureWithOnlyMax() { + void customizeEnvEndpointsUsesNewInfrastructureWithOnlyMax() { testCouchbaseEnv((env) -> { assertThat(env.queryServiceConfig().minEndpoints()).isEqualTo(1); assertThat(env.queryServiceConfig().maxEndpoints()).isEqualTo(5); @@ -115,7 +115,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void customizeEnvTimeouts() { + void customizeEnvTimeouts() { testCouchbaseEnv((env) -> { assertThat(env.connectTimeout()).isEqualTo(100); assertThat(env.kvTimeout()).isEqualTo(200); @@ -128,7 +128,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void enableSslNoEnabledFlag() { + void enableSslNoEnabledFlag() { testCouchbaseEnv((env) -> { assertThat(env.sslEnabled()).isTrue(); assertThat(env.sslKeystoreFile()).isEqualTo("foo"); @@ -137,7 +137,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void disableSslEvenWithKeyStore() { + void disableSslEvenWithKeyStore() { testCouchbaseEnv((env) -> { assertThat(env.sslEnabled()).isFalse(); assertThat(env.sslKeystoreFile()).isNull(); @@ -157,7 +157,7 @@ public class CouchbaseAutoConfigurationTests { } @Test - public void customizeEnvWithCustomCouchbaseConfiguration() { + void customizeEnvWithCustomCouchbaseConfiguration() { this.contextRunner.withUserConfiguration(CustomCouchbaseConfiguration.class) .withPropertyValues("spring.couchbase.bootstrap-hosts=localhost", "spring.couchbase.env.timeouts.connect=100") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java deleted file mode 100644 index c9509ede890..00000000000 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseTestServer.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.autoconfigure.couchbase; - -import java.util.concurrent.TimeUnit; - -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.CouchbaseCluster; -import com.couchbase.client.java.env.CouchbaseEnvironment; -import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AssumptionViolatedException; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import org.springframework.beans.factory.BeanCreationException; - -/** - * {@link TestRule} for working with an optional Couchbase server. Expects a default - * {@link Bucket} with no password to be available on localhost. - * - * @author Stephane Nicoll - */ -public class CouchbaseTestServer implements TestRule { - - private static final Log logger = LogFactory.getLog(CouchbaseTestServer.class); - - private CouchbaseEnvironment environment; - - private Cluster cluster; - - @Override - public Statement apply(Statement base, Description description) { - try { - this.environment = DefaultCouchbaseEnvironment.create(); - this.cluster = CouchbaseCluster.create(this.environment, "localhost"); - testConnection(this.cluster); - return new CouchbaseStatement(base, this.environment, this.cluster); - } - catch (Exception ex) { - logger.info("No couchbase server available"); - return new SkipStatement(); - } - } - - private static void testConnection(Cluster cluster) { - Bucket bucket = cluster.openBucket(2, TimeUnit.SECONDS); - bucket.close(); - } - - /** - * @return the Couchbase environment if any - */ - public CouchbaseEnvironment getCouchbaseEnvironment() { - return this.environment; - } - - /** - * @return the cluster if any - */ - public Cluster getCluster() { - return this.cluster; - } - - private static class CouchbaseStatement extends Statement { - - private final Statement base; - - private final CouchbaseEnvironment environment; - - private final Cluster cluster; - - CouchbaseStatement(Statement base, CouchbaseEnvironment environment, Cluster cluster) { - this.base = base; - this.environment = environment; - this.cluster = cluster; - } - - @Override - public void evaluate() throws Throwable { - try { - this.base.evaluate(); - } - catch (BeanCreationException ex) { - if ("couchbaseClient".equals(ex.getBeanName())) { - throw new AssumptionViolatedException("Skipping test due to Couchbase error " + ex.getMessage(), - ex); - } - } - finally { - try { - this.cluster.disconnect(); - this.environment.shutdownAsync(); - } - catch (Exception ex) { - logger.warn("Exception while trying to cleanup couchbase resource", ex); - } - } - } - - } - - private static class SkipStatement extends Statement { - - @Override - public void evaluate() throws Throwable { - throw new AssumptionViolatedException("Skipping test due to Couchbase not being available"); - } - - } - -} diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/LocalCouchbaseServer.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/LocalCouchbaseServer.java new file mode 100644 index 00000000000..80103bb32cb --- /dev/null +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/LocalCouchbaseServer.java @@ -0,0 +1,72 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.autoconfigure.couchbase; + +import java.util.concurrent.TimeUnit; + +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; + +import org.springframework.beans.factory.BeanCreationException; + +/** + * {@link Extension} for working with an optional Couchbase server. Expects a default + * {@link Bucket} with no password to be available on localhost. + * + * @author Stephane Nicoll + * @author Andy Wilkinson + */ +class LocalCouchbaseServer implements ExecutionCondition, TestExecutionExceptionHandler { + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + try { + CouchbaseEnvironment environment = DefaultCouchbaseEnvironment.create(); + Cluster cluster = CouchbaseCluster.create(environment, "localhost"); + testConnection(cluster); + cluster.disconnect(); + environment.shutdownAsync(); + return ConditionEvaluationResult.enabled("Local Couchbase server available"); + } + catch (Exception ex) { + return ConditionEvaluationResult.disabled("Local Couchbase server not available"); + } + } + + private static void testConnection(Cluster cluster) { + Bucket bucket = cluster.openBucket(2, TimeUnit.SECONDS); + bucket.close(); + } + + @Override + public void handleTestExecutionException(ExtensionContext context, Throwable ex) throws Throwable { + if ((ex instanceof BeanCreationException) + && "couchbaseClient".equals(((BeanCreationException) ex).getBeanName())) { + return; + } + throw ex; + } + +} diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java index 1acd126a267..2ca1ddfcdfe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/OnBootstrapHostsConditionTests.java @@ -30,24 +30,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class OnBootstrapHostsConditionTests { +class OnBootstrapHostsConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfig.class); @Test - public void bootstrapHostsNotDefined() { + void bootstrapHostsNotDefined() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void bootstrapHostsDefinedAsCommaSeparated() { + void bootstrapHostsDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.couchbase.bootstrap-hosts=value1") .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void bootstrapHostsDefinedAsList() { + void bootstrapHostsDefinedAsList() { this.contextRunner.withPropertyValues("spring.couchbase.bootstrap-hosts[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index a9c525cd064..11ea0c82248 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class PersistenceExceptionTranslationAutoConfigurationTests { +class PersistenceExceptionTranslationAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -55,7 +55,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { } @Test - public void exceptionTranslationPostProcessorUsesCglibByDefault() { + void exceptionTranslationPostProcessorUsesCglibByDefault() { this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); @@ -64,7 +64,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { } @Test - public void exceptionTranslationPostProcessorCanBeConfiguredToUseJdkProxy() { + void exceptionTranslationPostProcessorCanBeConfiguredToUseJdkProxy() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.aop.proxy-target-class=false").applyTo(this.context); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); @@ -76,7 +76,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { } @Test - public void exceptionTranslationPostProcessorCanBeDisabled() { + void exceptionTranslationPostProcessorCanBeDisabled() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.dao.exceptiontranslation.enabled=false").applyTo(this.context); this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); @@ -97,7 +97,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { // } @Test - public void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() { + void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() { this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java index a9da8bc1ca1..38325c91496 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java @@ -28,80 +28,80 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ConditionalOnRepositoryTypeTests { +class ConditionalOnRepositoryTypeTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void imperativeRepositoryMatchesWithNoConfiguredType() { + void imperativeRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test - public void reactiveRepositoryMatchesWithNoConfiguredType() { + void reactiveRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test - public void imperativeRepositoryMatchesWithAutoConfiguredType() { + void imperativeRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:auto") .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test - public void reactiveRepositoryMatchesWithAutoConfiguredType() { + void reactiveRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:auto") .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test - public void imperativeRepositoryMatchesWithImperativeConfiguredType() { + void imperativeRepositoryMatchesWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:imperative") .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test - public void reactiveRepositoryMatchesWithReactiveConfiguredType() { + void reactiveRepositoryMatchesWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:reactive") .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test - public void imperativeRepositoryDoesNotMatchWithReactiveConfiguredType() { + void imperativeRepositoryDoesNotMatchWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:reactive") .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test - public void reactiveRepositoryDoesNotMatchWithImperativeConfiguredType() { + void reactiveRepositoryDoesNotMatchWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:imperative") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test - public void imperativeRepositoryDoesNotMatchWithNoneConfiguredType() { + void imperativeRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) .withPropertyValues("spring.data.test.repositories.type:none") .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test - public void reactiveRepositoryDoesNotMatchWithNoneConfiguredType() { + void reactiveRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:none") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test - public void failsFastWhenConfiguredTypeIsUnknown() { + void failsFastWhenConfiguredTypeIsUnknown() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) .withPropertyValues("spring.data.test.repositories.type:abcde") .run((context) -> assertThat(context).hasFailed()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index 950a351f384..69917bfbdd7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -23,13 +23,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.testcontainers.containers.CassandraContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration; import org.springframework.boot.autoconfigure.data.cassandra.city.City; import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.testsupport.testcontainers.SkippableContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.cassandra.config.CassandraSessionFactoryBean; import org.springframework.data.cassandra.config.SchemaAction; @@ -42,12 +41,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch * @author Stephane Nicoll */ -@Testcontainers -public class CassandraDataAutoConfigurationIntegrationTests { +@DisabledWithoutDockerTestcontainers +class CassandraDataAutoConfigurationIntegrationTests { @Container - public static SkippableContainer> cassandra = new SkippableContainer<>( - CassandraContainer::new); + static final CassandraContainer cassandra = new CassandraContainer<>(); private AnnotationConfigApplicationContext context; @@ -55,7 +53,7 @@ public class CassandraDataAutoConfigurationIntegrationTests { public void setUp() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.data.cassandra.port=" + cassandra.getContainer().getFirstMappedPort(), + .of("spring.data.cassandra.port=" + cassandra.getFirstMappedPort(), "spring.data.cassandra.read-timeout=24000", "spring.data.cassandra.connect-timeout=10000") .applyTo(this.context.getEnvironment()); } @@ -68,7 +66,7 @@ public class CassandraDataAutoConfigurationIntegrationTests { } @Test - public void hasDefaultSchemaActionSet() { + void hasDefaultSchemaActionSet() { String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); this.context.register(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); @@ -79,7 +77,7 @@ public class CassandraDataAutoConfigurationIntegrationTests { } @Test - public void hasRecreateSchemaActionSet() { + void hasRecreateSchemaActionSet() { createTestKeyspaceIfNotExists(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(this.context, cityPackage); @@ -92,9 +90,8 @@ public class CassandraDataAutoConfigurationIntegrationTests { } private void createTestKeyspaceIfNotExists() { - Cluster cluster = Cluster.builder().withoutJMXReporting() - .withPort(cassandra.getContainer().getFirstMappedPort()) - .addContactPoint(cassandra.getContainer().getContainerIpAddress()).build(); + Cluster cluster = Cluster.builder().withoutJMXReporting().withPort(cassandra.getFirstMappedPort()) + .addContactPoint(cassandra.getContainerIpAddress()).build(); try (Session session = cluster.connect()) { session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test" + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index 1e44f0e39ff..ef5f7bfd11b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -50,7 +50,7 @@ import static org.mockito.Mockito.mock; * @author Mark Paluch * @author Stephane Nicoll */ -public class CassandraDataAutoConfigurationTests { +class CassandraDataAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -62,14 +62,14 @@ public class CassandraDataAutoConfigurationTests { } @Test - public void templateExists() { + void templateExists() { load(TestExcludeConfiguration.class); assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length).isEqualTo(1); } @Test @SuppressWarnings("unchecked") - public void entityScanShouldSetInitialEntitySet() { + void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, @@ -78,7 +78,7 @@ public class CassandraDataAutoConfigurationTests { } @Test - public void userTypeResolverShouldBeSet() { + void userTypeResolverShouldBeSet() { load(); CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); assertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")) @@ -86,14 +86,14 @@ public class CassandraDataAutoConfigurationTests { } @Test - public void defaultConversions() { + void defaultConversions() { load(); CassandraTemplate template = this.context.getBean(CassandraTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(Person.class, String.class)).isFalse(); } @Test - public void customConversions() { + void customConversions() { load(CustomConversionConfig.class); CassandraTemplate template = this.context.getBean(CassandraTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(Person.class, String.class)).isTrue(); @@ -101,7 +101,7 @@ public class CassandraDataAutoConfigurationTests { } @Test - public void clusterDoesNotExist() { + void clusterDoesNotExist() { this.context = new AnnotationConfigApplicationContext(CassandraDataAutoConfiguration.class); assertThat(this.context.getBeansOfType(Session.class)).isEmpty(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java index 4783309a14f..6be09c34a86 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfigurationTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Mark Paluch */ -public class CassandraReactiveDataAutoConfigurationTests { +class CassandraReactiveDataAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -56,14 +56,14 @@ public class CassandraReactiveDataAutoConfigurationTests { } @Test - public void templateExists() { + void templateExists() { load("spring.data.cassandra.keyspaceName:boot_test"); assertThat(this.context.getBeanNamesForType(ReactiveCassandraTemplate.class)).hasSize(1); } @Test @SuppressWarnings("unchecked") - public void entityScanShouldSetInitialEntitySet() { + void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class, "spring.data.cassandra.keyspaceName:boot_test"); CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, @@ -72,7 +72,7 @@ public class CassandraReactiveDataAutoConfigurationTests { } @Test - public void userTypeResolverShouldBeSet() { + void userTypeResolverShouldBeSet() { load("spring.data.cassandra.keyspaceName:boot_test"); CassandraMappingContext mappingContext = this.context.getBean(CassandraMappingContext.class); assertThat(ReflectionTestUtils.getField(mappingContext, "userTypeResolver")) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java index bf65a0a44f7..1a840a1eeea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java @@ -53,7 +53,7 @@ import static org.mockito.Mockito.mock; * @author Mark Paluch * @author Andy Wilkinson */ -public class CassandraReactiveRepositoriesAutoConfigurationTests { +class CassandraReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class, @@ -61,7 +61,7 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { CassandraReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ReactiveCityRepository.class); assertThat(context).hasSingleBean(Cluster.class); @@ -70,7 +70,7 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, EmptyConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(Cluster.class); @@ -79,7 +79,7 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, CustomizedConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(ReactiveCityCassandraRepository.class); @@ -88,14 +88,14 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { } @Test - public void enablingImperativeRepositoriesDisablesReactiveRepositories() { + void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=imperative") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test - public void enablingNoRepositoriesDisablesReactiveRepositories() { + void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=none") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index 37f327a8291..77c95f0b0b5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -50,14 +50,14 @@ import static org.mockito.Mockito.mock; * @author Mark Paluch * @author Stephane Nicoll */ -public class CassandraRepositoriesAutoConfigurationTests { +class CassandraRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class, CassandraDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CityRepository.class); assertThat(context).hasSingleBean(Cluster.class); @@ -66,7 +66,7 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, EmptyConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(Cluster.class); @@ -75,7 +75,7 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(TestExcludeConfiguration.class, CustomizedConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(CityCassandraRepository.class); @@ -84,14 +84,14 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Test - public void enablingReactiveRepositoriesDisablesImperativeRepositories() { + void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=reactive") .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @Test - public void enablingNoRepositoriesDisablesImperativeRepositories() { + void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.cassandra.repositories.type=none") .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java index 207459c1246..3b80f51aa31 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java @@ -53,7 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CouchbaseDataAutoConfigurationTests { +class CouchbaseDataAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -65,26 +65,26 @@ public class CouchbaseDataAutoConfigurationTests { } @Test - public void disabledIfCouchbaseIsNotConfigured() { + void disabledIfCouchbaseIsNotConfigured() { load(null); assertThat(this.context.getBeansOfType(IndexManager.class)).isEmpty(); } @Test - public void customConfiguration() { + void customConfiguration() { load(CustomCouchbaseConfiguration.class); CouchbaseTemplate couchbaseTemplate = this.context.getBean(CouchbaseTemplate.class); assertThat(couchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT); } @Test - public void validatorIsPresent() { + void validatorIsPresent() { load(CouchbaseTestConfigurer.class); assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)).hasSize(1); } @Test - public void autoIndexIsDisabledByDefault() { + void autoIndexIsDisabledByDefault() { load(CouchbaseTestConfigurer.class); IndexManager indexManager = this.context.getBean(IndexManager.class); assertThat(indexManager.isIgnoreViews()).isTrue(); @@ -93,7 +93,7 @@ public class CouchbaseDataAutoConfigurationTests { } @Test - public void enableAutoIndex() { + void enableAutoIndex() { load(CouchbaseTestConfigurer.class, "spring.data.couchbase.auto-index=true"); IndexManager indexManager = this.context.getBean(IndexManager.class); assertThat(indexManager.isIgnoreViews()).isFalse(); @@ -102,7 +102,7 @@ public class CouchbaseDataAutoConfigurationTests { } @Test - public void changeConsistency() { + void changeConsistency() { load(CouchbaseTestConfigurer.class, "spring.data.couchbase.consistency=eventually-consistent"); SpringBootCouchbaseDataConfiguration configuration = this.context .getBean(SpringBootCouchbaseDataConfiguration.class); @@ -111,7 +111,7 @@ public class CouchbaseDataAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void entityScanShouldSetInitialEntitySet() { + void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.class); Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, @@ -120,7 +120,7 @@ public class CouchbaseDataAutoConfigurationTests { } @Test - public void customConversions() { + void customConversions() { load(CustomConversionsConfig.class); CouchbaseTemplate template = this.context.getBean(CouchbaseTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java index 6f96b241b62..c1c8a78aebc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; import org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration; -import org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfigurationTests; import org.springframework.boot.autoconfigure.couchbase.CouchbaseTestConfigurer; import org.springframework.boot.autoconfigure.data.couchbase.city.CityRepository; import org.springframework.boot.autoconfigure.data.couchbase.city.ReactiveCityRepository; @@ -46,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { +class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -56,7 +55,7 @@ public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { } @Test - public void shouldCreateInstancesForReactiveAndImperativeRepositories() { + void shouldCreateInstancesForReactiveAndImperativeRepositories() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class); @@ -66,7 +65,7 @@ public class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @TestAutoConfigurationPackage(CouchbaseAutoConfigurationTests.class) + @TestAutoConfigurationPackage(CouchbaseAutoConfiguration.class) @EnableCouchbaseRepositories(basePackageClasses = CityRepository.class) @EnableReactiveCouchbaseRepositories(basePackageClasses = ReactiveCityRepository.class) protected static class ImperativeAndReactiveConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java index e5a83cb3a7a..7d559de5e54 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java @@ -53,7 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Alex Derkach */ -public class CouchbaseReactiveDataAutoConfigurationTests { +class CouchbaseReactiveDataAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -65,27 +65,27 @@ public class CouchbaseReactiveDataAutoConfigurationTests { } @Test - public void disabledIfCouchbaseIsNotConfigured() { + void disabledIfCouchbaseIsNotConfigured() { load(null); assertThat(this.context.getBeansOfType(IndexManager.class)).isEmpty(); } @Test - public void customConfiguration() { + void customConfiguration() { load(CustomCouchbaseConfiguration.class); RxJavaCouchbaseTemplate rxJavaCouchbaseTemplate = this.context.getBean(RxJavaCouchbaseTemplate.class); assertThat(rxJavaCouchbaseTemplate.getDefaultConsistency()).isEqualTo(Consistency.STRONGLY_CONSISTENT); } @Test - public void validatorIsPresent() { + void validatorIsPresent() { load(CouchbaseTestConfigurer.class); assertThat(this.context.getBeansOfType(ValidatingCouchbaseEventListener.class)).hasSize(1); } @Test @SuppressWarnings("unchecked") - public void entityScanShouldSetInitialEntitySet() { + void entityScanShouldSetInitialEntitySet() { load(EntityScanConfig.class); CouchbaseMappingContext mappingContext = this.context.getBean(CouchbaseMappingContext.class); Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, @@ -94,7 +94,7 @@ public class CouchbaseReactiveDataAutoConfigurationTests { } @Test - public void customConversions() { + void customConversions() { load(CustomConversionsConfig.class); RxJavaCouchbaseTemplate template = this.context.getBean(RxJavaCouchbaseTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java index 6080ae7bd4d..c05eaeaecdc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Alex Derkach */ -public class CouchbaseReactiveRepositoriesAutoConfigurationTests { +class CouchbaseReactiveRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -53,37 +53,37 @@ public class CouchbaseReactiveRepositoriesAutoConfigurationTests { } @Test - public void couchbaseNotAvailable() { + void couchbaseNotAvailable() { load(null); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0); } @Test - public void defaultRepository() { + void defaultRepository() { load(DefaultConfiguration.class); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(1); } @Test - public void imperativeRepositories() { + void imperativeRepositories() { load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=imperative"); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0); } @Test - public void disabledRepositories() { + void disabledRepositories() { load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=none"); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0); } @Test - public void noRepositoryAvailable() { + void noRepositoryAvailable() { load(NoRepositoryConfiguration.class); assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { load(CustomizedConfiguration.class); assertThat(this.context.getBeansOfType(ReactiveCityCouchbaseRepository.class)).isEmpty(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java index cf8a2da1637..745b22205cf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CouchbaseRepositoriesAutoConfigurationTests { +class CouchbaseRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -51,31 +51,31 @@ public class CouchbaseRepositoriesAutoConfigurationTests { } @Test - public void couchbaseNotAvailable() { + void couchbaseNotAvailable() { load(null); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } @Test - public void defaultRepository() { + void defaultRepository() { load(DefaultConfiguration.class); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(1); } @Test - public void reactiveRepositories() { + void reactiveRepositories() { load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=reactive"); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } @Test - public void disabledRepositories() { + void disabledRepositories() { load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=none"); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } @Test - public void noRepositoryAvailable() { + void noRepositoryAvailable() { load(NoRepositoryConfiguration.class); assertThat(this.context.getBeansOfType(CityRepository.class)).hasSize(0); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java index f499fca35ab..da823f5bb8e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java @@ -21,13 +21,14 @@ import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.node.DiscoveryNode; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -41,23 +42,29 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -@Testcontainers -public class ElasticsearchAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class ElasticsearchAutoConfigurationTests { @Container public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private AnnotationConfigApplicationContext context; + @BeforeEach + public void setUp() { + System.setProperty("es.set.netty.runtime.available.processors", "false"); + } + @AfterEach public void close() { if (this.context != null) { this.context.close(); } + System.clearProperty("es.set.netty.runtime.available.processors"); } @Test - public void useExistingClient() { + void useExistingClient() { this.context = new AnnotationConfigApplicationContext(); this.context.register(CustomConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); @@ -67,11 +74,11 @@ public class ElasticsearchAutoConfigurationTests { } @Test - public void createTransportClient() { + void createTransportClient() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues - .of("spring.data.elasticsearch.cluster-nodes:localhost:" + elasticsearch.getMappedTransportPort(), - "spring.data.elasticsearch.cluster-name:docker-cluster") + .of("spring.data.elasticsearch.cluster-nodes:" + elasticsearch.getTcpHost().getHostString() + ":" + + elasticsearch.getTcpHost().getPort(), "spring.data.elasticsearch.cluster-name:docker-cluster") .applyTo(this.context); this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index 44a6d531fc4..6ab471011af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -16,14 +16,16 @@ package org.springframework.boot.autoconfigure.data.elasticsearch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; @@ -43,21 +45,32 @@ import static org.mockito.Mockito.mock; * @author Artur Konczak * @author Brian Clozel */ -@Testcontainers -public class ElasticsearchDataAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class ElasticsearchDataAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(ElasticsearchAutoConfiguration.class, RestClientAutoConfiguration.class, ReactiveRestClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)); + @BeforeEach + public void setUp() { + System.setProperty("es.set.netty.runtime.available.processors", "false"); + } + + @AfterEach + public void tearDown() { + System.clearProperty("es.set.netty.runtime.available.processors"); + } + @Test - public void defaultTransportBeansAreRegistered() { + void defaultTransportBeansAreRegistered() { this.contextRunner .withPropertyValues( - "spring.data.elasticsearch.cluster-nodes:localhost:" + elasticsearch.getMappedTransportPort(), + "spring.data.elasticsearch.cluster-nodes:" + elasticsearch.getTcpHost().getHostString() + ":" + + elasticsearch.getTcpHost().getPort(), "spring.data.elasticsearch.cluster-name:docker-cluster") .run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class) .hasSingleBean(SimpleElasticsearchMappingContext.class) @@ -65,12 +78,12 @@ public class ElasticsearchDataAutoConfigurationTests { } @Test - public void defaultTransportBeansNotRegisteredIfNoTransportClient() { + void defaultTransportBeansNotRegisteredIfNoTransportClient() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchTemplate.class)); } @Test - public void defaultRestBeansRegistered() { + void defaultRestBeansRegistered() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class) .hasSingleBean(ReactiveElasticsearchTemplate.class).hasSingleBean(ElasticsearchConverter.class) .hasSingleBean(SimpleElasticsearchMappingContext.class).hasSingleBean(EntityMapper.class) @@ -78,13 +91,13 @@ public class ElasticsearchDataAutoConfigurationTests { } @Test - public void customTransportTemplateShouldBeUsed() { + void customTransportTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomTransportTemplate.class).run((context) -> assertThat(context) .getBeanNames(ElasticsearchTemplate.class).hasSize(1).contains("elasticsearchTemplate")); } @Test - public void customRestTemplateShouldBeUsed() { + void customRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomRestTemplate.class).run((context) -> assertThat(context) .getBeanNames(ElasticsearchRestTemplate.class).hasSize(1).contains("elasticsearchTemplate")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index 988d1f60fd7..244800766c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -17,8 +17,8 @@ package org.springframework.boot.autoconfigure.data.elasticsearch; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; @@ -28,7 +28,7 @@ import org.springframework.boot.autoconfigure.data.elasticsearch.city.CityReposi import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage; import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @@ -42,32 +42,32 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Brian Clozel */ -@Testcontainers -public class ElasticsearchRepositoriesAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class ElasticsearchRepositoriesAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of(ElasticsearchAutoConfiguration.class, RestClientAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues("spring.elasticsearch.rest.uris=localhost:" + elasticsearch.getMappedHttpPort()); + .withPropertyValues("spring.elasticsearch.rest.uris=" + elasticsearch.getHttpHostAddress()); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(CityRepository.class).hasSingleBean(ElasticsearchRestTemplate.class)); } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestTemplate.class)); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java index d2c52057923..f6e365d119d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java @@ -17,6 +17,7 @@ package org.springframework.boot.autoconfigure.data.elasticsearch; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -27,7 +28,6 @@ import org.springframework.boot.autoconfigure.data.elasticsearch.city.City; import org.springframework.boot.autoconfigure.data.elasticsearch.city.ReactiveCityRepository; import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate; import org.springframework.data.elasticsearch.repository.config.EnableReactiveElasticsearchRepositories; @@ -45,28 +45,28 @@ import static org.assertj.core.api.Assertions.assertThat; public class ReactiveElasticsearchRepositoriesAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class, ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=localhost:" - + elasticsearch.getMappedHttpPort()); + .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=" + + elasticsearch.getContainerIpAddress() + ":" + elasticsearch.getFirstMappedPort()); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(ReactiveCityRepository.class).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java index 85695a16ce6..84bbb454b52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveRestClientAutoConfigurationTests.java @@ -23,12 +23,12 @@ import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.index.get.GetResult; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.client.ClientConfiguration; @@ -46,34 +46,35 @@ import static org.mockito.Mockito.mock; public class ReactiveRestClientAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveRestClientAutoConfiguration.class)); @Test - public void configureShouldCreateDefaultBeans() { + void configureShouldCreateDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ClientConfiguration.class) .hasSingleBean(ReactiveElasticsearchClient.class)); } @Test - public void configureWhenCustomClientShouldBackOff() { + void configureWhenCustomClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomClientConfiguration.class).run((context) -> assertThat(context) .hasSingleBean(ReactiveElasticsearchClient.class).hasBean("customClient")); } @Test - public void configureWhenCustomClientConfig() { + void configureWhenCustomClientConfig() { this.contextRunner.withUserConfiguration(CustomClientConfigConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) .hasSingleBean(ClientConfiguration.class).hasBean("customClientConfiguration")); } @Test - public void restClientCanQueryElasticsearchNode() { - this.contextRunner.withPropertyValues( - "spring.data.elasticsearch.client.reactive.endpoints=localhost:" + elasticsearch.getMappedPort()) + void restClientCanQueryElasticsearchNode() { + this.contextRunner + .withPropertyValues("spring.data.elasticsearch.client.reactive.endpoints=" + + elasticsearch.getContainerIpAddress() + ":" + elasticsearch.getFirstMappedPort()) .run((context) -> { ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); Map source = new HashMap<>(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java index e2585edb801..cc72a1cd5d8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java @@ -42,19 +42,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class JdbcRepositoriesAutoConfigurationTests { +class JdbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); @Test - public void backsOffWithNoDataSource() { + void backsOffWithNoDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(JdbcRepositoryConfigExtension.class)); } @Test - public void backsOffWithNoJdbcOperations() { + void backsOffWithNoJdbcOperations() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(DataSource.class); @@ -63,7 +63,7 @@ public class JdbcRepositoriesAutoConfigurationTests { } @Test - public void basicAutoConfiguration() { + void basicAutoConfiguration() { this.contextRunner .withConfiguration( AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) @@ -78,7 +78,7 @@ public class JdbcRepositoriesAutoConfigurationTests { } @Test - public void autoConfigurationWithNoRepositories() { + void autoConfigurationWithNoRepositories() { this.contextRunner.withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) .withUserConfiguration(EmbeddedDataSourceConfiguration.class, EmptyConfiguration.class) .run((context) -> { @@ -88,7 +88,7 @@ public class JdbcRepositoriesAutoConfigurationTests { } @Test - public void honoursUsersEnableJdbcRepositoriesConfiguration() { + void honoursUsersEnableJdbcRepositoriesConfiguration() { this.contextRunner .withConfiguration( AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index 2052ddc3c5e..b4659613baa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -52,7 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Oliver Gierke */ -public class JpaRepositoriesAutoConfigurationTests { +class JpaRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, @@ -60,7 +60,7 @@ public class JpaRepositoriesAutoConfigurationTests { .withUserConfiguration(EmbeddedDataSourceConfiguration.class); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CityRepository.class); assertThat(context).hasSingleBean(PlatformTransactionManager.class); @@ -70,7 +70,7 @@ public class JpaRepositoriesAutoConfigurationTests { } @Test - public void testOverrideRepositoryConfiguration() { + void testOverrideRepositoryConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CityJpaRepository.class); assertThat(context).hasSingleBean(PlatformTransactionManager.class); @@ -79,13 +79,13 @@ public class JpaRepositoriesAutoConfigurationTests { } @Test - public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { + void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test - public void whenBootstrappingModeIsLazyWithMultipleAsyncExecutorBootstrapExecutorIsConfigured() { + void whenBootstrappingModeIsLazyWithMultipleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) @@ -96,7 +96,7 @@ public class JpaRepositoriesAutoConfigurationTests { } @Test - public void whenBootstrappingModeIsLazyWithSingleAsyncExecutorBootstrapExecutorIsConfigured() { + void whenBootstrappingModeIsLazyWithSingleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(SingleAsyncTaskExecutorConfiguration.class) .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") .run((context) -> assertThat( @@ -105,7 +105,7 @@ public class JpaRepositoriesAutoConfigurationTests { } @Test - public void whenBootstrappingModeIsDeferredBootstrapExecutorIsConfigured() { + void whenBootstrappingModeIsDeferredBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) @@ -116,7 +116,7 @@ public class JpaRepositoriesAutoConfigurationTests { } @Test - public void whenBootstrappingModeIsDefaultBootstrapExecutorIsNotConfigured() { + void whenBootstrappingModeIsDefaultBootstrapExecutorIsNotConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index 15b825fd091..215803cc5f6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class JpaWebAutoConfigurationTests { +class JpaWebAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext context; @@ -51,7 +51,7 @@ public class JpaWebAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java index 1d4a43377bc..481eee8e9f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfigurationTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -public class LdapRepositoriesAutoConfigurationTests { +class LdapRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -50,19 +50,19 @@ public class LdapRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { load(TestConfiguration.class); assertThat(this.context.getBean(PersonRepository.class)).isNotNull(); } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { load(EmptyConfiguration.class); assertThat(this.context.getBeanNamesForType(PersonRepository.class)).isEmpty(); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { load(CustomizedConfiguration.class); assertThat(this.context.getBean(PersonLdapRepository.class)).isNotNull(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java index 5d58a0ed179..be56f776ff8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java @@ -31,7 +31,6 @@ import org.springframework.boot.autoconfigure.data.mongo.country.CountryReposito import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.MongoAutoConfigurationTests; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -51,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Oliver Gierke */ -public class MixedMongoRepositoriesAutoConfigurationTests { +class MixedMongoRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -61,7 +60,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(TestConfiguration.class, BaseConfiguration.class); @@ -70,7 +69,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Test - public void testMixedRepositoryConfiguration() { + void testMixedRepositoryConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(MixedConfiguration.class, BaseConfiguration.class); @@ -80,7 +79,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Test - public void testJpaRepositoryConfigurationWithMongoTemplate() { + void testJpaRepositoryConfigurationWithMongoTemplate() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(JpaConfiguration.class, BaseConfiguration.class); @@ -89,7 +88,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Test - public void testJpaRepositoryConfigurationWithMongoOverlap() { + void testJpaRepositoryConfigurationWithMongoOverlap() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); @@ -98,7 +97,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Test - public void testJpaRepositoryConfigurationWithMongoOverlapDisabled() { + void testJpaRepositoryConfigurationWithMongoOverlapDisabled() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.datasource.initialization-mode:never", "spring.data.mongodb.repositories.type:none") @@ -109,7 +108,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @TestAutoConfigurationPackage(MongoAutoConfigurationTests.class) + @TestAutoConfigurationPackage(MongoAutoConfiguration.class) // Not this package or its parent @EnableMongoRepositories(basePackageClasses = Country.class) protected static class TestConfiguration { @@ -117,7 +116,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @TestAutoConfigurationPackage(MongoAutoConfigurationTests.class) + @TestAutoConfigurationPackage(MongoAutoConfiguration.class) @EnableMongoRepositories(basePackageClasses = Country.class) @EntityScan(basePackageClasses = City.class) @EnableJpaRepositories(basePackageClasses = CityRepository.class) @@ -126,7 +125,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @TestAutoConfigurationPackage(MongoAutoConfigurationTests.class) + @TestAutoConfigurationPackage(MongoAutoConfiguration.class) @EntityScan(basePackageClasses = City.class) @EnableJpaRepositories(basePackageClasses = CityRepository.class) protected static class JpaConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index 81d14d73f99..2013256928d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -59,25 +59,25 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Josh Long * @author Oliver Gierke */ -public class MongoDataAutoConfigurationTests { +class MongoDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); @Test - public void templateExists() { + void templateExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } @Test - public void gridFsTemplateExists() { + void gridFsTemplateExists() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridFsDatabase:grid") .run((context) -> assertThat(context).hasSingleBean(GridFsTemplate.class)); } @Test - public void customConversions() { + void customConversions() { this.contextRunner.withUserConfiguration(CustomConversionsConfig.class).run((context) -> { MongoTemplate template = context.getBean(MongoTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) @@ -86,7 +86,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void usesAutoConfigurationPackageToPickUpDocumentTypes() { + void usesAutoConfigurationPackageToPickUpDocumentTypes() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(context, cityPackage); @@ -101,7 +101,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void defaultFieldNamingStrategy() { + void defaultFieldNamingStrategy() { this.contextRunner.run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils.getField(mappingContext, @@ -111,7 +111,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void customFieldNamingStrategy() { + void customFieldNamingStrategy() { this.contextRunner.withPropertyValues( "spring.data.mongodb.field-naming-strategy:" + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) .run((context) -> { @@ -124,7 +124,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void customAutoIndexCreation() { + void customAutoIndexCreation() { this.contextRunner.withPropertyValues("spring.data.mongodb.autoIndexCreation:false").run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); assertThat(mappingContext.isAutoIndexCreation()).isFalse(); @@ -132,7 +132,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void interfaceFieldNamingStrategy() { + void interfaceFieldNamingStrategy() { this.contextRunner .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); @@ -140,7 +140,7 @@ public class MongoDataAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void entityScanShouldSetInitialEntitySet() { + void entityScanShouldSetInitialEntitySet() { this.contextRunner.withUserConfiguration(EntityScanConfig.class).run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); Set> initialEntitySet = (Set>) ReflectionTestUtils.getField(mappingContext, @@ -151,7 +151,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void registersDefaultSimpleTypesWithMappingContext() { + void registersDefaultSimpleTypesWithMappingContext() { this.contextRunner.run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); BasicMongoPersistentEntity entity = mappingContext.getPersistentEntity(Sample.class); @@ -162,14 +162,14 @@ public class MongoDataAutoConfigurationTests { } @Test - public void backsOffIfMongoClientBeanIsNotPresent() { + void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoDataAutoConfiguration.class)); } @Test - public void createsMongoDbFactoryForPreferredMongoClient() { + void createsMongoDbFactoryForPreferredMongoClient() { this.contextRunner.run((context) -> { MongoDbFactory dbFactory = context.getBean(MongoDbFactory.class); assertThat(dbFactory).isInstanceOf(SimpleMongoDbFactory.class); @@ -177,7 +177,7 @@ public class MongoDataAutoConfigurationTests { } @Test - public void createsMongoDbFactoryForFallbackMongoClient() { + void createsMongoDbFactoryForFallbackMongoClient() { this.contextRunner.withUserConfiguration(FallbackMongoClientConfiguration.class).run((context) -> { MongoDbFactory dbFactory = context.getBean(MongoDbFactory.class); assertThat(dbFactory).isInstanceOf(SimpleMongoClientDbFactory.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java index e9d26d4eff3..b44da144d0b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveAndBlockingRepositoriesAutoConfigurationTests.java @@ -26,7 +26,6 @@ import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; import org.springframework.boot.autoconfigure.data.mongo.city.CityRepository; import org.springframework.boot.autoconfigure.data.mongo.city.ReactiveCityRepository; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.MongoAutoConfigurationTests; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -46,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Mark Paluch */ -public class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { +class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -56,7 +55,7 @@ public class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { } @Test - public void shouldCreateInstancesForReactiveAndBlockingRepositories() { + void shouldCreateInstancesForReactiveAndBlockingRepositories() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.datasource.initialization-mode:never").applyTo(this.context); this.context.register(BlockingAndReactiveConfiguration.class, BaseConfiguration.class); @@ -66,7 +65,7 @@ public class MongoReactiveAndBlockingRepositoriesAutoConfigurationTests { } @Configuration(proxyBeanMethods = false) - @TestAutoConfigurationPackage(MongoAutoConfigurationTests.class) + @TestAutoConfigurationPackage(MongoAutoConfiguration.class) @EnableMongoRepositories(basePackageClasses = ReactiveCityRepository.class) @EnableReactiveMongoRepositories(basePackageClasses = ReactiveCityRepository.class) protected static class BlockingAndReactiveConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java index 5666200ea14..2d88d811504 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java @@ -33,24 +33,24 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch * @author Artsiom Yudovin */ -public class MongoReactiveDataAutoConfigurationTests { +class MongoReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); @Test - public void templateExists() { + void templateExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ReactiveMongoTemplate.class)); } @Test - public void gridFsTemplateExists() { + void gridFsTemplateExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ReactiveGridFsTemplate.class)); } @Test - public void backsOffIfMongoClientBeanIsNotPresent() { + void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner().withConfiguration(AutoConfigurations .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveDataAutoConfiguration.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java index 6d3698451a6..c607f84e97f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch * @author Andy Wilkinson */ -public class MongoReactiveRepositoriesAutoConfigurationTests { +class MongoReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -54,7 +54,7 @@ public class MongoReactiveRepositoriesAutoConfigurationTests { MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ReactiveCityRepository.class); assertThat(context).hasSingleBean(MongoClient.class); @@ -67,32 +67,32 @@ public class MongoReactiveRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); } @Test - public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { + void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test - public void enablingImperativeRepositoriesDisablesReactiveRepositories() { + void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=imperative") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test - public void enablingNoRepositoriesDisablesReactiveRepositories() { + void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=none") .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index 609447fa677..136a967f45c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -43,14 +43,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Oliver Gierke */ -public class MongoRepositoriesAutoConfigurationTests { +class MongoRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CityRepository.class); assertThat(context).hasSingleBean(MongoClient.class); @@ -63,32 +63,32 @@ public class MongoRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); } @Test - public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { + void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test - public void enablingReactiveRepositoriesDisablesImperativeRepositories() { + void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=reactive") .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test - public void enablingNoRepositoriesDisablesImperativeRepositories() { + void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.data.mongodb.repositories.type=none") .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java index 955b3bbe94f..765abe77034 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/MixedNeo4jRepositoriesAutoConfigurationTests.java @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vince Bickers * @author Stephane Nicoll */ -public class MixedNeo4jRepositoriesAutoConfigurationTests { +class MixedNeo4jRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -61,33 +61,33 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { load(TestConfiguration.class); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); } @Test - public void testMixedRepositoryConfiguration() { + void testMixedRepositoryConfiguration() { load(MixedConfiguration.class); assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test - public void testJpaRepositoryConfigurationWithNeo4jTemplate() { + void testJpaRepositoryConfigurationWithNeo4jTemplate() { load(JpaConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test @Disabled - public void testJpaRepositoryConfigurationWithNeo4jOverlap() { + void testJpaRepositoryConfigurationWithNeo4jOverlap() { load(OverlapConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test - public void testJpaRepositoryConfigurationWithNeo4jOverlapDisabled() { + void testJpaRepositoryConfigurationWithNeo4jOverlapDisabled() { load(OverlapConfiguration.class, "spring.data.neo4j.repositories.enabled:false"); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java index 459deea99ba..3cd35194859 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java @@ -63,7 +63,7 @@ import static org.mockito.Mockito.verify; * @author Kazuki Shimizu * @author Michael Simons */ -public class Neo4jDataAutoConfigurationTests { +class Neo4jDataAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withClassLoader(new FilteredClassLoader(EmbeddedDriver.class)) @@ -71,7 +71,7 @@ public class Neo4jDataAutoConfigurationTests { AutoConfigurations.of(Neo4jDataAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test - public void defaultConfiguration() { + void defaultConfiguration() { this.contextRunner.withPropertyValues("spring.data.neo4j.uri=http://localhost:8989").run((context) -> { assertThat(context).hasSingleBean(org.neo4j.ogm.config.Configuration.class); assertThat(context).hasSingleBean(SessionFactory.class); @@ -82,7 +82,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void customNeo4jTransactionManagerUsingProperties() { + void customNeo4jTransactionManagerUsingProperties() { this.contextRunner.withPropertyValues("spring.transaction.default-timeout=30", "spring.transaction.rollback-on-commit-failure:true").run((context) -> { Neo4jTransactionManager transactionManager = context.getBean(Neo4jTransactionManager.class); @@ -92,7 +92,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void customSessionFactory() { + void customSessionFactory() { this.contextRunner.withUserConfiguration(CustomSessionFactory.class).run((context) -> { assertThat(context).doesNotHaveBean(org.neo4j.ogm.config.Configuration.class); assertThat(context).hasSingleBean(SessionFactory.class); @@ -100,7 +100,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void customConfiguration() { + void customConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context.getBean(org.neo4j.ogm.config.Configuration.class)) .isSameAs(context.getBean("myConfiguration")); @@ -110,7 +110,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void usesAutoConfigurationPackageToPickUpDomainTypes() { + void usesAutoConfigurationPackageToPickUpDomainTypes() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setClassLoader(new FilteredClassLoader(EmbeddedDriver.class)); String cityPackage = City.class.getPackage().getName(); @@ -126,13 +126,13 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void openSessionInViewInterceptorCanBeDisabled() { + void openSessionInViewInterceptorCanBeDisabled() { this.contextRunner.withPropertyValues("spring.data.neo4j.open-in-view:false") .run((context) -> assertThat(context).doesNotHaveBean(OpenSessionInViewInterceptor.class)); } @Test - public void shouldBeAbleToUseNativeTypesWithBolt() { + void shouldBeAbleToUseNativeTypesWithBolt() { this.contextRunner .withPropertyValues("spring.data.neo4j.uri=bolt://localhost:7687", "spring.data.neo4j.use-native-types:true") @@ -143,7 +143,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void shouldFailWhenNativeTypesAreNotAvailable() { + void shouldFailWhenNativeTypesAreNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.neo4j.ogm.drivers.bolt.types")) .withPropertyValues("spring.data.neo4j.uri=bolt://localhost:7687", "spring.data.neo4j.use-native-types:true") @@ -157,7 +157,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void shouldFailWhenNativeTypesAreNotSupported() { + void shouldFailWhenNativeTypesAreNotSupported() { this.contextRunner .withPropertyValues("spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.use-native-types:true") @@ -171,7 +171,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void eventListenersAreAutoRegistered() { + void eventListenersAreAutoRegistered() { this.contextRunner.withUserConfiguration(EventListenerConfiguration.class).run((context) -> { Session session = context.getBean(SessionFactory.class).openSession(); session.notifyListeners(new PersistenceEvent(null, Event.TYPE.PRE_SAVE)); @@ -181,7 +181,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void providesARequestScopedBookmarkManagerIfNecessaryAndPossible() { + void providesARequestScopedBookmarkManagerIfNecessaryAndPossible() { this.contextRunner.withUserConfiguration(BookmarkManagementEnabledConfiguration.class).run((context) -> { BeanDefinition bookmarkManagerBean = context.getBeanFactory() .getBeanDefinition("scopedTarget.bookmarkManager"); @@ -190,7 +190,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void providesASingletonScopedBookmarkManagerIfNecessaryAndPossible() { + void providesASingletonScopedBookmarkManagerIfNecessaryAndPossible() { new ApplicationContextRunner().withClassLoader(new FilteredClassLoader(EmbeddedDriver.class)) .withUserConfiguration(TestConfiguration.class, BookmarkManagementEnabledConfiguration.class) .withConfiguration( @@ -202,7 +202,7 @@ public class Neo4jDataAutoConfigurationTests { } @Test - public void doesNotProvideABookmarkManagerIfNotPossible() { + void doesNotProvideABookmarkManagerIfNotPossible() { this.contextRunner.withClassLoader(new FilteredClassLoader(Caffeine.class, EmbeddedDriver.class)) .withUserConfiguration(BookmarkManagementEnabledConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(BookmarkManager.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java index f3b5d1a555b..3cfac8d0abd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jPropertiesTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Michael Simons */ -public class Neo4jPropertiesTests { +class Neo4jPropertiesTests { private AnnotationConfigApplicationContext context; @@ -49,49 +49,49 @@ public class Neo4jPropertiesTests { } @Test - public void defaultUseEmbeddedInMemoryIfAvailable() { + void defaultUseEmbeddedInMemoryIfAvailable() { Neo4jProperties properties = load(true); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, null); } @Test - public void defaultUseBoltDriverIfEmbeddedDriverIsNotAvailable() { + void defaultUseBoltDriverIfEmbeddedDriverIsNotAvailable() { Neo4jProperties properties = load(false); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI); } @Test - public void httpUriUseHttpDriver() { + void httpUriUseHttpDriver() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://localhost:7474"); } @Test - public void httpsUriUseHttpDriver() { + void httpsUriUseHttpDriver() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://localhost:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://localhost:7474"); } @Test - public void boltUriUseBoltDriver() { + void boltUriUseBoltDriver() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=bolt://localhost:7687"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, "bolt://localhost:7687"); } @Test - public void fileUriUseEmbeddedServer() { + void fileUriUseEmbeddedServer() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file://var/tmp/graph.db"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file://var/tmp/graph.db"); } @Test - public void credentialsAreSet() { + void credentialsAreSet() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://localhost:7474", "spring.data.neo4j.username=user", "spring.data.neo4j.password=secret"); Configuration configuration = properties.createConfiguration(); @@ -100,7 +100,7 @@ public class Neo4jPropertiesTests { } @Test - public void credentialsAreSetFromUri() { + void credentialsAreSetFromUri() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=https://user:secret@my-server:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "https://my-server:7474"); @@ -108,42 +108,42 @@ public class Neo4jPropertiesTests { } @Test - public void autoIndexNoneByDefault() { + void autoIndexNoneByDefault() { Neo4jProperties properties = load(true); Configuration configuration = properties.createConfiguration(); assertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.NONE); } @Test - public void autoIndexCanBeConfigured() { + void autoIndexCanBeConfigured() { Neo4jProperties properties = load(true, "spring.data.neo4j.auto-index=validate"); Configuration configuration = properties.createConfiguration(); assertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.VALIDATE); } @Test - public void embeddedModeDisabledUseBoltUri() { + void embeddedModeDisabledUseBoltUri() { Neo4jProperties properties = load(true, "spring.data.neo4j.embedded.enabled=false"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.BOLT_DRIVER, Neo4jProperties.DEFAULT_BOLT_URI); } @Test - public void embeddedModeWithRelativeLocation() { + void embeddedModeWithRelativeLocation() { Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file:relative/path/to/my.db"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file:relative/path/to/my.db"); } @Test - public void nativeTypesAreSetToFalseByDefault() { + void nativeTypesAreSetToFalseByDefault() { Neo4jProperties properties = load(true); Configuration configuration = properties.createConfiguration(); assertThat(configuration.getUseNativeTypes()).isFalse(); } @Test - public void nativeTypesCanBeConfigured() { + void nativeTypesCanBeConfigured() { Neo4jProperties properties = load(true, "spring.data.neo4j.use-native-types=true"); Configuration configuration = properties.createConfiguration(); assertThat(configuration.getUseNativeTypes()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java index 13fa35e70e9..630f53ce486 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Vince Bickers * @author Stephane Nicoll */ -public class Neo4jRepositoriesAutoConfigurationTests { +class Neo4jRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -55,7 +55,7 @@ public class Neo4jRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { prepareApplicationContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); Neo4jMappingContext mappingContext = this.context.getBean(Neo4jMappingContext.class); @@ -63,19 +63,19 @@ public class Neo4jRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { prepareApplicationContext(EmptyConfiguration.class); assertThat(this.context.getBean(SessionFactory.class)).isNotNull(); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { prepareApplicationContext(CustomizedConfiguration.class); assertThat(this.context.getBean(CityNeo4jRepository.class)).isNotNull(); } @Test - public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { + void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { prepareApplicationContext(SortOfInvalidCustomConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(CityRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 1cb7c4e523c..1aaf4008aa5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -52,13 +52,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Alen Turkovic */ -public class RedisAutoConfigurationTests { +class RedisAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test - public void testDefaultRedisConfiguration() { + void testDefaultRedisConfiguration() { this.contextRunner.run((context) -> { assertThat(context.getBean("redisTemplate", RedisOperations.class)).isNotNull(); assertThat(context.getBean(StringRedisTemplate.class)).isNotNull(); @@ -66,7 +66,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testOverrideRedisConfiguration() { + void testOverrideRedisConfiguration() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.database:1", "spring.redis.lettuce.shutdown-timeout:500").run((context) -> { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); @@ -79,7 +79,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testCustomizeRedisConfiguration() { + void testCustomizeRedisConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.isUseSsl()).isTrue(); @@ -87,7 +87,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisUrlConfiguration() { + void testRedisUrlConfiguration() { this.contextRunner .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") .run((context) -> { @@ -100,7 +100,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testOverrideUrlRedisConfiguration() { + void testOverrideUrlRedisConfiguration() { this.contextRunner .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") @@ -114,7 +114,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testPasswordInUrlWithColon() { + void testPasswordInUrlWithColon() { this.contextRunner.withPropertyValues("spring.redis.url:redis://:pass:word@example:33").run((context) -> { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); @@ -124,7 +124,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testPasswordInUrlStartsWithColon() { + void testPasswordInUrlStartsWithColon() { this.contextRunner.withPropertyValues("spring.redis.url:redis://user::pass:word@example:33").run((context) -> { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("example"); @@ -134,7 +134,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithPool() { + void testRedisConfigurationWithPool() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.lettuce.pool.min-idle:1", "spring.redis.lettuce.pool.max-idle:4", "spring.redis.lettuce.pool.max-active:16", "spring.redis.lettuce.pool.max-wait:2000", "spring.redis.lettuce.pool.time-between-eviction-runs:30000", @@ -152,7 +152,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithTimeout() { + void testRedisConfigurationWithTimeout() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100").run((context) -> { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); @@ -161,7 +161,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithSentinel() { + void testRedisConfigurationWithSentinel() { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); this.contextRunner .withPropertyValues("spring.redis.sentinel.master:mymaster", @@ -171,7 +171,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithSentinelAndDatabase() { + void testRedisConfigurationWithSentinelAndDatabase() { this.contextRunner.withPropertyValues("spring.redis.database:1", "spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380").run((context) -> { LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); @@ -181,7 +181,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithSentinelAndPassword() { + void testRedisConfigurationWithSentinelAndPassword() { this.contextRunner.withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380").run((context) -> { LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); @@ -193,7 +193,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithCluster() { + void testRedisConfigurationWithCluster() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); this.contextRunner.withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { @@ -208,7 +208,7 @@ public class RedisAutoConfigurationTests { } @Test - public void testRedisConfigurationWithClusterAndPassword() { + void testRedisConfigurationWithClusterAndPassword() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); this.contextRunner .withPropertyValues("spring.redis.password=password", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java index d84e5282d70..ba473870099 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java @@ -31,13 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class RedisReactiveAutoConfigurationTests { +class RedisReactiveAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test - public void testDefaultRedisConfiguration() { + void testDefaultRedisConfiguration() { this.contextRunner.run((context) -> { Map beans = context.getBeansOfType(ReactiveRedisTemplate.class); assertThat(beans).containsOnlyKeys("reactiveRedisTemplate", "reactiveStringRedisTemplate"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java index 63edce3cf1c..d120736c5d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java @@ -20,7 +20,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -29,6 +28,7 @@ import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage; import org.springframework.boot.autoconfigure.data.redis.city.City; import org.springframework.boot.autoconfigure.data.redis.city.CityRepository; import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.boot.testsupport.testcontainers.RedisContainer; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; @@ -41,8 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -@Testcontainers -public class RedisRepositoriesAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class RedisRepositoriesAutoConfigurationTests { @Container public static RedisContainer redis = new RedisContainer(); @@ -51,7 +51,7 @@ public class RedisRepositoriesAutoConfigurationTests { @BeforeEach public void setUp() { - TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()).applyTo(this.context.getEnvironment()); + TestPropertyValues.of("spring.redis.port=" + redis.getFirstMappedPort()).applyTo(this.context.getEnvironment()); } @AfterEach @@ -60,7 +60,7 @@ public class RedisRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { this.context.register(TestConfiguration.class, RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); @@ -68,7 +68,7 @@ public class RedisRepositoriesAutoConfigurationTests { } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { this.context.register(EmptyConfiguration.class, RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); @@ -76,7 +76,7 @@ public class RedisRepositoriesAutoConfigurationTests { } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.context.register(CustomizedConfiguration.class, RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java index 2ce3ac9b5df..c80c6a8d15f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java @@ -53,7 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class RepositoryRestMvcAutoConfigurationTests { +class RepositoryRestMvcAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext context; @@ -65,13 +65,13 @@ public class RepositoryRestMvcAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { load(TestConfiguration.class); assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); } @Test - public void testWithCustomBasePath() { + void testWithCustomBasePath() { load(TestConfiguration.class, "spring.data.rest.base-path:foo"); assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); @@ -82,7 +82,7 @@ public class RepositoryRestMvcAutoConfigurationTests { } @Test - public void testWithCustomSettings() { + void testWithCustomSettings() { load(TestConfiguration.class, "spring.data.rest.default-page-size:42", "spring.data.rest.max-page-size:78", "spring.data.rest.page-param-name:_page", "spring.data.rest.limit-param-name:_limit", "spring.data.rest.sort-param-name:_sort", "spring.data.rest.detection-strategy=visibility", @@ -104,7 +104,7 @@ public class RepositoryRestMvcAutoConfigurationTests { } @Test - public void testWithCustomConfigurer() { + void testWithCustomConfigurer() { load(TestConfigurationWithConfigurer.class, "spring.data.rest.detection-strategy=visibility", "spring.data.rest.default-media-type:application/my-json"); assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); @@ -115,7 +115,7 @@ public class RepositoryRestMvcAutoConfigurationTests { } @Test - public void backOffWithCustomConfiguration() { + void backOffWithCustomConfiguration() { load(TestConfigurationWithRestMvcConfig.class, "spring.data.rest.base-path:foo"); assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)).isNotNull(); RepositoryRestConfiguration bean = this.context.getBean(RepositoryRestConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java index 9c76329c894..cabca98764e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Christoph Strobl * @author Oliver Gierke */ -public class SolrRepositoriesAutoConfigurationTests { +class SolrRepositoriesAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -52,26 +52,26 @@ public class SolrRepositoriesAutoConfigurationTests { } @Test - public void testDefaultRepositoryConfiguration() { + void testDefaultRepositoryConfiguration() { initContext(TestConfiguration.class); assertThat(this.context.getBean(CityRepository.class)).isNotNull(); assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test - public void testNoRepositoryConfiguration() { + void testNoRepositoryConfiguration() { initContext(EmptyConfiguration.class); assertThat(this.context.getBean(SolrClient.class)).isInstanceOf(HttpSolrClient.class); } @Test - public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { + void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { initContext(CustomizedConfiguration.class); assertThat(this.context.getBean(CitySolrRepository.class)).isNotNull(); } @Test - public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { + void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { initContext(SortOfInvalidCustomConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(CityRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index f7f68b051ba..2118e427ace 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -34,25 +34,25 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic * @author Stephane Nicoll */ -public class SpringDataWebAutoConfigurationTests { +class SpringDataWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); @Test - public void webSupportIsAutoConfiguredInWebApplicationContexts() { + void webSupportIsAutoConfiguredInWebApplicationContexts() { this.contextRunner .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); } @Test - public void autoConfigurationBacksOffInNonWebApplicationContexts() { + void autoConfigurationBacksOffInNonWebApplicationContexts() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); } @Test - public void customizePageable() { + void customizePageable() { this.contextRunner.withPropertyValues("spring.data.web.pageable.page-parameter=p", "spring.data.web.pageable.size-parameter=s", "spring.data.web.pageable.default-page-size=10", "spring.data.web.pageable.prefix=abc", "spring.data.web.pageable.qualifier-delimiter=__", @@ -71,7 +71,7 @@ public class SpringDataWebAutoConfigurationTests { } @Test - public void defaultPageable() { + void defaultPageable() { this.contextRunner.run((context) -> { SpringDataWebProperties.Pageable properties = new SpringDataWebProperties().getPageable(); PageableHandlerMethodArgumentResolver argumentResolver = context @@ -92,7 +92,7 @@ public class SpringDataWebAutoConfigurationTests { } @Test - public void customizeSort() { + void customizeSort() { this.contextRunner.withPropertyValues("spring.data.web.sort.sort-parameter=s").run((context) -> { SortHandlerMethodArgumentResolver argumentResolver = context .getBean(SortHandlerMethodArgumentResolver.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index bd8065cf02c..a23e4188c52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -47,18 +47,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class NoSuchBeanDefinitionFailureAnalyzerTests { +class NoSuchBeanDefinitionFailureAnalyzerTests { private final NoSuchBeanDefinitionFailureAnalyzer analyzer = new NoSuchBeanDefinitionFailureAnalyzer(); @Test - public void failureAnalysisForMultipleBeans() { + void failureAnalysisForMultipleBeans() { FailureAnalysis analysis = analyzeFailure(new NoUniqueBeanDefinitionException(String.class, 2, "Test")); assertThat(analysis).isNull(); } @Test - public void failureAnalysisForNoMatchType() { + void failureAnalysisForNoMatchType() { FailureAnalysis analysis = analyzeFailure(createFailure(StringHandler.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertThat(analysis.getDescription()) @@ -68,7 +68,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForMissingPropertyExactType() { + void failureAnalysisForMissingPropertyExactType() { FailureAnalysis analysis = analyzeFailure(createFailure(StringPropertyTypeConfiguration.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", @@ -77,7 +77,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForMissingPropertySubType() { + void failureAnalysisForMissingPropertySubType() { FailureAnalysis analysis = analyzeFailure(createFailure(IntegerPropertyTypeConfiguration.class)); assertThat(analysis).isNotNull(); assertDescriptionConstructorMissingType(analysis, NumberHandler.class, 0, Number.class); @@ -87,7 +87,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForMissingClassOnAutoConfigurationType() { + void failureAnalysisForMissingClassOnAutoConfigurationType() { FailureAnalysis analysis = analyzeFailure(createFailure(MissingClassOnAutoConfigurationConfiguration.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertClassDisabled(analysis, "did not find required class 'com.example.FooBar'", "string", @@ -96,7 +96,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForExcludedAutoConfigurationType() { + void failureAnalysisForExcludedAutoConfigurationType() { FatalBeanException failure = createFailure(StringHandler.class); addExclusions(this.analyzer, TestPropertyAutoConfiguration.class); FailureAnalysis analysis = analyzeFailure(failure); @@ -108,7 +108,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForSeveralConditionsType() { + void failureAnalysisForSeveralConditionsType() { FailureAnalysis analysis = analyzeFailure(createFailure(SeveralAutoConfigurationTypeConfiguration.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", @@ -119,7 +119,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForNoMatchName() { + void failureAnalysisForNoMatchName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNameHandler.class)); assertThat(analysis.getDescription()) .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", @@ -129,7 +129,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForMissingBeanName() { + void failureAnalysisForMissingBeanName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringMissingBeanNameConfiguration.class)); assertThat(analysis.getDescription()) .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", @@ -141,7 +141,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForNullBeanByType() { + void failureAnalysisForNullBeanByType() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNullBeanConfiguration.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertUserDefinedBean(analysis, "as the bean value is null", TestNullBeanConfiguration.class, "string"); @@ -149,7 +149,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForUnmatchedQualifier() { + void failureAnalysisForUnmatchedQualifier() { FailureAnalysis analysis = analyzeFailure(createFailure(QualifiedBeanConfiguration.class)); assertThat(analysis.getDescription()) .containsPattern("@org.springframework.beans.factory.annotation.Qualifier\\(value=\"*alpha\"*\\)"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index fde2d791450..6ac233b271e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class EntityScanPackagesTests { +class EntityScanPackagesTests { private AnnotationConfigApplicationContext context; @@ -48,7 +48,7 @@ public class EntityScanPackagesTests { } @Test - public void getWhenNoneRegisteredShouldReturnNone() { + void getWhenNoneRegisteredShouldReturnNone() { this.context = new AnnotationConfigApplicationContext(); this.context.refresh(); EntityScanPackages packages = EntityScanPackages.get(this.context); @@ -57,7 +57,7 @@ public class EntityScanPackagesTests { } @Test - public void getShouldReturnRegisterPackages() { + void getShouldReturnRegisterPackages() { this.context = new AnnotationConfigApplicationContext(); EntityScanPackages.register(this.context, "a", "b"); EntityScanPackages.register(this.context, "b", "c"); @@ -67,14 +67,14 @@ public class EntityScanPackagesTests { } @Test - public void registerFromArrayWhenRegistryIsNullShouldThrowException() { + void registerFromArrayWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> EntityScanPackages.register(null)) .withMessageContaining("Registry must not be null"); } @Test - public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { + void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) @@ -82,14 +82,14 @@ public class EntityScanPackagesTests { } @Test - public void registerFromCollectionWhenRegistryIsNullShouldThrowException() { + void registerFromCollectionWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) .withMessageContaining("Registry must not be null"); } @Test - public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { + void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) @@ -97,14 +97,14 @@ public class EntityScanPackagesTests { } @Test - public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackages() { + void entityScanAnnotationWhenHasValueAttributeShouldSetupPackages() { this.context = new AnnotationConfigApplicationContext(EntityScanValueConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("a"); } @Test - public void entityScanAnnotationWhenHasValueAttributeShouldSetupPackagesAsm() { + void entityScanAnnotationWhenHasValueAttributeShouldSetupPackagesAsm() { this.context = new AnnotationConfigApplicationContext(); this.context.registerBeanDefinition("entityScanValueConfig", new RootBeanDefinition(EntityScanValueConfig.class.getName())); @@ -114,35 +114,35 @@ public class EntityScanPackagesTests { } @Test - public void entityScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() { + void entityScanAnnotationWhenHasBasePackagesAttributeShouldSetupPackages() { this.context = new AnnotationConfigApplicationContext(EntityScanBasePackagesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly("b"); } @Test - public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { + void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { assertThatExceptionOfType(AnnotationConfigurationException.class) .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( EntityScanValueAndBasePackagesConfig.class)); } @Test - public void entityScanAnnotationWhenHasBasePackageClassesAttributeShouldSetupPackages() { + void entityScanAnnotationWhenHasBasePackageClassesAttributeShouldSetupPackages() { this.context = new AnnotationConfigApplicationContext(EntityScanBasePackageClassesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test - public void entityScanAnnotationWhenNoAttributesShouldSetupPackages() { + void entityScanAnnotationWhenNoAttributesShouldSetupPackages() { this.context = new AnnotationConfigApplicationContext(EntityScanNoAttributesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); assertThat(packages.getPackageNames()).containsExactly(getClass().getPackage().getName()); } @Test - public void entityScanAnnotationWhenLoadingFromMultipleConfigsShouldCombinePackages() { + void entityScanAnnotationWhenLoadingFromMultipleConfigsShouldCombinePackages() { this.context = new AnnotationConfigApplicationContext(EntityScanValueConfig.class, EntityScanBasePackagesConfig.class); EntityScanPackages packages = EntityScanPackages.get(this.context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index 98c97559082..1110a73a845 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -40,16 +40,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class EntityScannerTests { +class EntityScannerTests { @Test - public void createWhenContextIsNullShouldThrowException() { + void createWhenContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EntityScanner(null)) .withMessageContaining("Context must not be null"); } @Test - public void scanShouldScanFromSinglePackage() throws Exception { + void scanShouldScanFromSinglePackage() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); Set> scanned = scanner.scan(Entity.class); @@ -58,7 +58,7 @@ public class EntityScannerTests { } @Test - public void scanShouldScanFromMultiplePackages() throws Exception { + void scanShouldScanFromMultiplePackages() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanAConfig.class, ScanBConfig.class); EntityScanner scanner = new EntityScanner(context); @@ -68,7 +68,7 @@ public class EntityScannerTests { } @Test - public void scanShouldFilterOnAnnotation() throws Exception { + void scanShouldFilterOnAnnotation() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); EntityScanner scanner = new EntityScanner(context); assertThat(scanner.scan(Entity.class)).containsOnly(EntityA.class, EntityB.class, EntityC.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java index 28d114088d6..b039fb93b63 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java @@ -28,14 +28,14 @@ import io.searchbox.client.http.JestHttpClient; import io.searchbox.core.Get; import io.searchbox.core.Index; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -50,29 +50,29 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson */ @Deprecated -@Testcontainers -public class JestAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class JestAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, JestAutoConfiguration.class)); @Test - public void jestClientOnLocalhostByDefault() { + void jestClientOnLocalhostByDefault() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JestClient.class)); } @Test - public void customJestClient() { + void customJestClient() { this.contextRunner.withUserConfiguration(CustomJestClient.class) .withPropertyValues("spring.elasticsearch.jest.uris[0]=http://localhost:9200") .run((context) -> assertThat(context).hasSingleBean(JestClient.class)); } @Test - public void customGson() { + void customGson() { this.contextRunner.withUserConfiguration(CustomGson.class) .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200").run((context) -> { JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); @@ -81,7 +81,7 @@ public class JestAutoConfigurationTests { } @Test - public void customizerOverridesAutoConfig() { + void customizerOverridesAutoConfig() { this.contextRunner.withUserConfiguration(BuilderCustomizer.class) .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200").run((context) -> { JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); @@ -90,7 +90,7 @@ public class JestAutoConfigurationTests { } @Test - public void proxyHostWithoutPort() { + void proxyHostWithoutPort() { this.contextRunner .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200", "spring.elasticsearch.jest.proxy.host=proxy.example.com") @@ -99,9 +99,9 @@ public class JestAutoConfigurationTests { } @Test - public void jestCanCommunicateWithElasticsearchInstance() { + void jestCanCommunicateWithElasticsearchInstance() { this.contextRunner - .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" + elasticsearch.getMappedPort()) + .withPropertyValues("spring.elasticsearch.jest.uris=http://" + elasticsearch.getHttpHostAddress()) .run((context) -> { JestClient client = context.getBean(JestClient.class); Map source = new HashMap<>(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java index e5c2b1dc77d..6399e75b222 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/rest/RestClientAutoConfigurationTests.java @@ -27,12 +27,12 @@ import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.junit.jupiter.api.Test; +import org.testcontainers.elasticsearch.ElasticsearchContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.testsupport.testcontainers.ElasticsearchContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.util.ReflectionTestUtils; @@ -45,29 +45,29 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -@Testcontainers -public class RestClientAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class RestClientAutoConfigurationTests { @Container - public static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); + static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(); private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RestClientAutoConfiguration.class)); @Test - public void configureShouldCreateBothRestClientVariants() { + void configureShouldCreateBothRestClientVariants() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RestClient.class) .hasSingleBean(RestHighLevelClient.class)); } @Test - public void configureWhenCustomClientShouldBackOff() { + void configureWhenCustomClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(RestClient.class).hasBean("customRestClient")); } @Test - public void configureWhenBuilderCustomizerShouldApply() { + void configureWhenBuilderCustomizerShouldApply() { this.contextRunner.withUserConfiguration(BuilderCustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(RestClient.class); RestClient restClient = context.getBean(RestClient.class); @@ -76,7 +76,7 @@ public class RestClientAutoConfigurationTests { } @Test - public void configureWithNoTimeoutsApplyDefaults() { + void configureWithNoTimeoutsApplyDefaults() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(RestClient.class); RestClient restClient = context.getBean(RestClient.class); @@ -86,7 +86,7 @@ public class RestClientAutoConfigurationTests { } @Test - public void configureWithCustomTimeouts() { + void configureWithCustomTimeouts() { this.contextRunner.withPropertyValues("spring.elasticsearch.rest.connection-timeout=15s", "spring.elasticsearch.rest.read-timeout=1m").run((context) -> { assertThat(context).hasSingleBean(RestClient.class); @@ -103,9 +103,10 @@ public class RestClientAutoConfigurationTests { } @Test - public void restClientCanQueryElasticsearchNode() { - this.contextRunner.withPropertyValues("spring.elasticsearch.rest.uris=http://localhost:" - + RestClientAutoConfigurationTests.elasticsearch.getMappedPort()).run((context) -> { + void restClientCanQueryElasticsearchNode() { + this.contextRunner + .withPropertyValues("spring.elasticsearch.rest.uris=http://" + elasticsearch.getHttpHostAddress()) + .run((context) -> { RestHighLevelClient client = context.getBean(RestHighLevelClient.class); Map source = new HashMap<>(); source.put("a", "alpha"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index 8692d614313..56f50c0acf1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -72,19 +72,19 @@ import static org.mockito.Mockito.mock; * @author Dominic Gunn */ @SuppressWarnings("deprecation") -public class FlywayAutoConfigurationTests { +class FlywayAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test - public void backsOffWithNoDataSourceBeanAndNoFlywayUrl() { + void backsOffWithNoDataSourceBeanAndNoFlywayUrl() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); } @Test - public void createsDataSourceWithNoDataSourceBeanAndFlywayUrl() { + void createsDataSourceWithNoDataSourceBeanAndFlywayUrl() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -93,7 +93,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void createDataSourceWithUrl() { + void createDataSourceWithUrl() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -102,7 +102,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void createDataSourceWithUser() { + void createDataSourceWithUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), "spring.flyway.user:sa") @@ -113,7 +113,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void flywayDataSource() { + void flywayDataSource() { this.contextRunner .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { @@ -124,7 +124,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void flywayDataSourceWithoutDataSourceAutoConfiguration() { + void flywayDataSourceWithoutDataSourceAutoConfiguration() { this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getDataSource()).isEqualTo(context.getBean("flywayDataSource")); @@ -132,7 +132,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void schemaManagementProviderDetectsDataSource() { + void schemaManagementProviderDetectsDataSource() { this.contextRunner .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { @@ -147,7 +147,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void defaultFlyway() { + void defaultFlyway() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); @@ -156,7 +156,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void overrideLocations() { + void overrideLocations() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") .run((context) -> { @@ -168,7 +168,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void overrideLocationsList() { + void overrideLocationsList() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations[0]:classpath:db/changelog", "spring.flyway.locations[1]:classpath:db/migration") @@ -181,7 +181,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void overrideSchemas() { + void overrideSchemas() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.schemas:public").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -191,7 +191,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void changeLogDoesNotExist() { + void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:filesystem:no-such-dir").run((context) -> { assertThat(context).hasFailed(); @@ -200,7 +200,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void checkLocationsAllMissing() { + void checkLocationsAllMissing() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") .run((context) -> { @@ -211,28 +211,28 @@ public class FlywayAutoConfigurationTests { } @Test - public void checkLocationsAllExist() { + void checkLocationsAllExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void checkLocationsAllExistWithImplicitClasspathPrefix() { + void checkLocationsAllExistWithImplicitClasspathPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:db/changelog,db/migration") .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void checkLocationsAllExistWithFilesystemPrefix() { + void checkLocationsAllExistWithFilesystemPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void customFlywayMigrationStrategy() { + void customFlywayMigrationStrategy() { this.contextRunner .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) .run((context) -> { @@ -242,7 +242,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void customFlywayMigrationInitializer() { + void customFlywayMigrationInitializer() { this.contextRunner .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) .run((context) -> { @@ -253,14 +253,14 @@ public class FlywayAutoConfigurationTests { } @Test - public void customFlywayWithJpa() { + void customFlywayWithJpa() { this.contextRunner .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void overrideBaselineVersionString() { + void overrideBaselineVersionString() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.baseline-version=0").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -270,7 +270,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void overrideBaselineVersionNumber() { + void overrideBaselineVersionNumber() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.baseline-version=1").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -280,7 +280,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void useVendorDirectory() { + void useVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") .run((context) -> { @@ -292,7 +292,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void useOneLocationWithVendorDirectory() { + void useOneLocationWithVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}").run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -302,7 +302,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void callbacksAreConfiguredAndOrdered() { + void callbacksAreConfiguredAndOrdered() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CallbackConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -318,7 +318,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void legacyCallbacksAreConfiguredAndOrdered() { + void legacyCallbacksAreConfiguredAndOrdered() { this.contextRunner .withUserConfiguration(EmbeddedDataSourceConfiguration.class, LegacyCallbackConfiguration.class) .run((context) -> { @@ -334,7 +334,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void callbacksAndLegacyCallbacksCannotBeMixed() { + void callbacksAndLegacyCallbacksCannotBeMixed() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, LegacyCallbackConfiguration.class, CallbackConfiguration.class).run((context) -> { assertThat(context).hasFailed(); @@ -345,7 +345,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void configurationCustomizersAreConfiguredAndOrdered() { + void configurationCustomizersAreConfiguredAndOrdered() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, ConfigurationCustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); @@ -357,7 +357,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void batchIsCorrectlyMapped() { + void batchIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.batch=true").run((context) -> { assertThat(context).hasFailed(); @@ -368,7 +368,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void dryRunOutputIsCorrectlyMapped() { + void dryRunOutputIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql").run((context) -> { assertThat(context).hasFailed(); @@ -379,7 +379,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void errorOverridesIsCorrectlyMapped() { + void errorOverridesIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.errorOverrides=D12345").run((context) -> { assertThat(context).hasFailed(); @@ -390,7 +390,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void licenseKeyIsCorrectlyMapped() { + void licenseKeyIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.license-key=<>").run((context) -> { assertThat(context).hasFailed(); @@ -401,7 +401,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void oracleSqlplusIsCorrectlyMapped() { + void oracleSqlplusIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.oracle-sqlplus=true").run((context) -> { assertThat(context).hasFailed(); @@ -412,7 +412,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void streamIsCorrectlyMapped() { + void streamIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.stream=true").run((context) -> { assertThat(context).hasFailed(); @@ -423,7 +423,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void undoSqlMigrationPrefix() { + void undoSqlMigrationPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo").run((context) -> { assertThat(context).hasFailed(); @@ -434,7 +434,7 @@ public class FlywayAutoConfigurationTests { } @Test - public void customFlywayClassLoader() { + void customFlywayClassLoader() { this.contextRunner .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java index 60b4355c038..01cdfc1b497 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationScriptMissingFailureAnalyzerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.autoconfigure.flyway; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.diagnostics.FailureAnalysis; @@ -29,17 +29,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Anand Shastri */ -public class FlywayMigrationScriptMissingFailureAnalyzerTests { +class FlywayMigrationScriptMissingFailureAnalyzerTests { @Test - public void analysisForMissingScriptLocation() { + void analysisForMissingScriptLocation() { FailureAnalysis failureAnalysis = performAnalysis(); assertThat(failureAnalysis.getDescription()).contains("no migration scripts location is configured"); assertThat(failureAnalysis.getAction()).contains("Check your Flyway configuration"); } @Test - public void analysisForScriptLocationsNotFound() { + void analysisForScriptLocationsNotFound() { FailureAnalysis failureAnalysis = performAnalysis("classpath:db/migration"); assertThat(failureAnalysis.getDescription()) .contains("none of the following migration scripts locations could be found") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java index 7dc9dbaf2ea..83cf4753b66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java @@ -41,10 +41,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class FlywayPropertiesTests { +class FlywayPropertiesTests { @Test - public void defaultValuesAreConsistent() { + void defaultValuesAreConsistent() { FlywayProperties properties = new FlywayProperties(); Configuration configuration = new FluentConfiguration(); assertThat(properties.getLocations().stream().map(Location::new).toArray(Location[]::new)) @@ -87,7 +87,7 @@ public class FlywayPropertiesTests { } @Test - public void expectedPropertiesAreManaged() { + void expectedPropertiesAreManaged() { Map properties = indexProperties( PropertyAccessorFactory.forBeanPropertyAccess(new FlywayProperties())); Map configuration = indexProperties( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java index 7c06e332baf..baee19357fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java @@ -41,13 +41,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class FreeMarkerAutoConfigurationReactiveIntegrationTests { +class FreeMarkerAutoConfigurationReactiveIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test - public void defaultConfiguration() { + void defaultConfiguration() { this.contextRunner.run((context) -> { assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull(); assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull(); @@ -57,7 +57,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { } @Test - public void defaultViewResolution() { + void defaultViewResolution() { this.contextRunner.run((context) -> { MockServerWebExchange exchange = render(context, "home"); String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); @@ -67,7 +67,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { } @Test - public void customPrefix() { + void customPrefix() { this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/").run((context) -> { MockServerWebExchange exchange = render(context, "prefixed"); String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); @@ -76,7 +76,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { } @Test - public void customSuffix() { + void customSuffix() { this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker").run((context) -> { MockServerWebExchange exchange = render(context, "suffixed"); String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); @@ -85,7 +85,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { } @Test - public void customTemplateLoaderPath() { + void customTemplateLoaderPath() { this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/") .run((context) -> { MockServerWebExchange exchange = render(context, "custom"); @@ -96,7 +96,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { @SuppressWarnings("deprecation") @Test - public void customFreeMarkerSettings() { + void customFreeMarkerSettings() { this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") .run((context) -> assertThat( context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) @@ -104,19 +104,15 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { } @Test - public void renderTemplate() { + void renderTemplate() { this.contextRunner.withPropertyValues().run((context) -> { FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); - freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); + freemarker.getConfiguration().getTemplate("message.ftl").process(new DataModel(), writer); assertThat(writer.toString()).contains("Hello World"); }); } - public String getGreeting() { - return "Hello World"; - } - private MockServerWebExchange render(ApplicationContext context, String viewName) { FreeMarkerViewResolver resolver = context.getBean(FreeMarkerViewResolver.class); Mono view = resolver.resolveViewName(viewName, Locale.UK); @@ -125,4 +121,12 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests { return exchange; } + public static class DataModel { + + public String getGreeting() { + return "Hello World"; + } + + } + } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java index 6028e8ca5f2..d01be80b235 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java @@ -55,7 +55,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Kazuki Shimizu */ -public class FreeMarkerAutoConfigurationServletIntegrationTests { +class FreeMarkerAutoConfigurationServletIntegrationTests { private AnnotationConfigServletWebApplicationContext context; @@ -67,7 +67,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void defaultConfiguration() { + void defaultConfiguration() { load(); assertThat(this.context.getBean(FreeMarkerViewResolver.class)).isNotNull(); assertThat(this.context.getBean(FreeMarkerConfigurer.class)).isNotNull(); @@ -76,7 +76,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void defaultViewResolution() throws Exception { + void defaultViewResolution() throws Exception { load(); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); @@ -85,7 +85,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void customContentType() throws Exception { + void customContentType() throws Exception { load("spring.freemarker.contentType:application/json"); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); @@ -94,7 +94,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void customPrefix() throws Exception { + void customPrefix() throws Exception { load("spring.freemarker.prefix:prefix/"); MockHttpServletResponse response = render("prefixed"); String result = response.getContentAsString(); @@ -102,7 +102,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void customSuffix() throws Exception { + void customSuffix() throws Exception { load("spring.freemarker.suffix:.freemarker"); MockHttpServletResponse response = render("suffixed"); String result = response.getContentAsString(); @@ -110,7 +110,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void customTemplateLoaderPath() throws Exception { + void customTemplateLoaderPath() throws Exception { load("spring.freemarker.templateLoaderPath:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); @@ -118,13 +118,13 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } @Test - public void disableCache() { + void disableCache() { load("spring.freemarker.cache:false"); assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test - public void allowSessionOverride() { + void allowSessionOverride() { load("spring.freemarker.allow-session-override:true"); AbstractTemplateViewResolver viewResolver = this.context.getBean(FreeMarkerViewResolver.class); assertThat(viewResolver).hasFieldOrPropertyWithValue("allowSessionOverride", true); @@ -132,29 +132,29 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @SuppressWarnings("deprecation") @Test - public void customFreeMarkerSettings() { + void customFreeMarkerSettings() { load("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) .isEqualTo("yup,nope"); } @Test - public void renderTemplate() throws Exception { + void renderTemplate() throws Exception { load(); FreeMarkerConfigurer freemarker = this.context.getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); - freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); + freemarker.getConfiguration().getTemplate("message.ftl").process(new DataModel(), writer); assertThat(writer.toString()).contains("Hello World"); } @Test - public void registerResourceHandlingFilterDisabledByDefault() { + void registerResourceHandlingFilterDisabledByDefault() { load(); assertThat(this.context.getBeansOfType(FilterRegistrationBean.class)).isEmpty(); } @Test - public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { + void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { load("spring.resources.chain.enabled:true"); FilterRegistrationBean registration = this.context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class); @@ -164,7 +164,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void registerResourceHandlingFilterWithOtherRegistrationBean() { + void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 load(FilterRegistrationOtherConfiguration.class, "spring.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); @@ -177,7 +177,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void registerResourceHandlingFilterWithResourceRegistrationBean() { + void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 load(FilterRegistrationResourceConfiguration.class, "spring.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); @@ -199,10 +199,6 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { this.context.refresh(); } - public String getGreeting() { - return "Hello World"; - } - private MockHttpServletResponse render(String viewName) throws Exception { FreeMarkerViewResolver resolver = this.context.getBean(FreeMarkerViewResolver.class); View view = resolver.resolveViewName(viewName, Locale.UK); @@ -245,4 +241,12 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { } + public static class DataModel { + + public String getGreeting() { + return "Hello World"; + } + + } + } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 3fe7e72c953..993b6edbd2b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -45,21 +45,17 @@ public class FreeMarkerAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test - public void renderNonWebAppTemplate() { + void renderNonWebAppTemplate() { this.contextRunner.run((context) -> { freemarker.template.Configuration freemarker = context.getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); - freemarker.getTemplate("message.ftl").process(this, writer); + freemarker.getTemplate("message.ftl").process(new DataModel(), writer); assertThat(writer.toString()).contains("Hello World"); }); } - public String getGreeting() { - return "Hello World"; - } - @Test - public void nonExistentTemplateLocation(CapturedOutput capturedOutput) { + void nonExistentTemplateLocation(CapturedOutput capturedOutput) { this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,classpath:/also-does-not-exist") @@ -67,7 +63,7 @@ public class FreeMarkerAutoConfigurationTests { } @Test - public void emptyTemplateLocation(CapturedOutput capturedOutput) { + void emptyTemplateLocation(CapturedOutput capturedOutput) { File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory"); emptyDirectory.mkdirs(); this.contextRunner @@ -77,7 +73,7 @@ public class FreeMarkerAutoConfigurationTests { } @Test - public void nonExistentLocationAndEmptyLocation(CapturedOutput capturedOutput) { + void nonExistentLocationAndEmptyLocation(CapturedOutput capturedOutput) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" @@ -85,4 +81,12 @@ public class FreeMarkerAutoConfigurationTests { .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } + public static class DataModel { + + public String getGreeting() { + return "Hello World"; + } + + } + } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index 32c68504926..5a6796888bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class FreeMarkerTemplateAvailabilityProviderTests { +class FreeMarkerTemplateAvailabilityProviderTests { private final TemplateAvailabilityProvider provider = new FreeMarkerTemplateAvailabilityProvider(); @@ -39,40 +39,40 @@ public class FreeMarkerTemplateAvailabilityProviderTests { private final MockEnvironment environment = new MockEnvironment(); @Test - public void availabilityOfTemplateInDefaultLocation() { + void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateThatDoesNotExist() { + void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test - public void availabilityOfTemplateWithCustomLoaderPath() { + void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { + void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomPrefix() { + void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomSuffix() { + void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index 7d67b34e899..93ade47dd15 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -52,7 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class GroovyTemplateAutoConfigurationTests { +class GroovyTemplateAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); @@ -72,20 +72,20 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void defaultConfiguration() { + void defaultConfiguration() { registerAndRefreshContext(); assertThat(this.context.getBean(GroovyMarkupViewResolver.class)).isNotNull(); } @Test - public void emptyTemplateLocation() { + void emptyTemplateLocation() { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); registerAndRefreshContext( "spring.groovy.template.resource-loader-path:" + "classpath:/templates/empty-directory/"); } @Test - public void defaultViewResolution() throws Exception { + void defaultViewResolution() throws Exception { registerAndRefreshContext(); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); @@ -94,7 +94,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void includesViewResolution() throws Exception { + void includesViewResolution() throws Exception { registerAndRefreshContext(); MockHttpServletResponse response = render("includes"); String result = response.getContentAsString(); @@ -103,14 +103,14 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void disableViewResolution() { + void disableViewResolution() { TestPropertyValues.of("spring.groovy.template.enabled:false").applyTo(this.context); registerAndRefreshContext(); assertThat(this.context.getBeanNamesForType(ViewResolver.class)).isEmpty(); } @Test - public void localeViewResolution() throws Exception { + void localeViewResolution() throws Exception { registerAndRefreshContext(); MockHttpServletResponse response = render("includes", Locale.FRENCH); String result = response.getContentAsString(); @@ -119,7 +119,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void customContentType() throws Exception { + void customContentType() throws Exception { registerAndRefreshContext("spring.groovy.template.contentType:application/json"); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); @@ -128,7 +128,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void customPrefix() throws Exception { + void customPrefix() throws Exception { registerAndRefreshContext("spring.groovy.template.prefix:prefix/"); MockHttpServletResponse response = render("prefixed"); String result = response.getContentAsString(); @@ -136,7 +136,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void customSuffix() throws Exception { + void customSuffix() throws Exception { registerAndRefreshContext("spring.groovy.template.suffix:.groovytemplate"); MockHttpServletResponse response = render("suffixed"); String result = response.getContentAsString(); @@ -144,7 +144,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void customTemplateLoaderPath() throws Exception { + void customTemplateLoaderPath() throws Exception { registerAndRefreshContext("spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); @@ -152,13 +152,13 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void disableCache() { + void disableCache() { registerAndRefreshContext("spring.groovy.template.cache:false"); assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()).isEqualTo(0); } @Test - public void renderTemplate() throws Exception { + void renderTemplate() throws Exception { registerAndRefreshContext(); GroovyMarkupConfig config = this.context.getBean(GroovyMarkupConfig.class); MarkupTemplateEngine engine = config.getTemplateEngine(); @@ -169,7 +169,7 @@ public class GroovyTemplateAutoConfigurationTests { } @Test - public void customConfiguration() { + void customConfiguration() { registerAndRefreshContext("spring.groovy.template.configuration.auto-indent:true"); assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java index 5fd33f3e8f7..026c93d4e1e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class GroovyTemplateAvailabilityProviderTests { +class GroovyTemplateAvailabilityProviderTests { private TemplateAvailabilityProvider provider = new GroovyTemplateAvailabilityProvider(); @@ -39,40 +39,40 @@ public class GroovyTemplateAvailabilityProviderTests { private MockEnvironment environment = new MockEnvironment(); @Test - public void availabilityOfTemplateInDefaultLocation() { + void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateThatDoesNotExist() { + void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test - public void availabilityOfTemplateWithCustomLoaderPath() { + void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.groovy.template.resource-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { + void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomPrefix() { + void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.groovy.template.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomSuffix() { + void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java index ba7735696d6..eb9b422d77c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java @@ -43,13 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Ivan Golovko * @author Stephane Nicoll */ -public class GsonAutoConfigurationTests { +class GsonAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)); @Test - public void gsonRegistration() { + void gsonRegistration() { this.contextRunner.run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":1}"); @@ -57,7 +57,7 @@ public class GsonAutoConfigurationTests { } @Test - public void generateNonExecutableJson() { + void generateNonExecutableJson() { this.contextRunner.withPropertyValues("spring.gson.generate-non-executable-json:true").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isNotEqualTo("{\"data\":1}"); @@ -66,7 +66,7 @@ public class GsonAutoConfigurationTests { } @Test - public void excludeFieldsWithoutExposeAnnotation() { + void excludeFieldsWithoutExposeAnnotation() { this.contextRunner.withPropertyValues("spring.gson.exclude-fields-without-expose-annotation:true") .run((context) -> { Gson gson = context.getBean(Gson.class); @@ -75,7 +75,7 @@ public class GsonAutoConfigurationTests { } @Test - public void serializeNullsTrue() { + void serializeNullsTrue() { this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:true").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.serializeNulls()).isTrue(); @@ -83,7 +83,7 @@ public class GsonAutoConfigurationTests { } @Test - public void serializeNullsFalse() { + void serializeNullsFalse() { this.contextRunner.withPropertyValues("spring.gson.serialize-nulls:false").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.serializeNulls()).isFalse(); @@ -91,7 +91,7 @@ public class GsonAutoConfigurationTests { } @Test - public void enableComplexMapKeySerialization() { + void enableComplexMapKeySerialization() { this.contextRunner.withPropertyValues("spring.gson.enable-complex-map-key-serialization:true") .run((context) -> { Gson gson = context.getBean(Gson.class); @@ -102,7 +102,7 @@ public class GsonAutoConfigurationTests { } @Test - public void notDisableInnerClassSerialization() { + void notDisableInnerClassSerialization() { this.contextRunner.run((context) -> { Gson gson = context.getBean(Gson.class); WrapperObject wrapperObject = new WrapperObject(); @@ -111,7 +111,7 @@ public class GsonAutoConfigurationTests { } @Test - public void disableInnerClassSerialization() { + void disableInnerClassSerialization() { this.contextRunner.withPropertyValues("spring.gson.disable-inner-class-serialization:true").run((context) -> { Gson gson = context.getBean(Gson.class); WrapperObject wrapperObject = new WrapperObject(); @@ -120,7 +120,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withLongSerializationPolicy() { + void withLongSerializationPolicy() { this.contextRunner.withPropertyValues("spring.gson.long-serialization-policy:" + LongSerializationPolicy.STRING) .run((context) -> { Gson gson = context.getBean(Gson.class); @@ -129,7 +129,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withFieldNamingPolicy() { + void withFieldNamingPolicy() { FieldNamingPolicy fieldNamingPolicy = FieldNamingPolicy.UPPER_CAMEL_CASE; this.contextRunner.withPropertyValues("spring.gson.field-naming-policy:" + fieldNamingPolicy).run((context) -> { Gson gson = context.getBean(Gson.class); @@ -138,7 +138,7 @@ public class GsonAutoConfigurationTests { } @Test - public void additionalGsonBuilderCustomization() { + void additionalGsonBuilderCustomization() { this.contextRunner.withUserConfiguration(GsonBuilderCustomizerConfig.class).run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); @@ -146,7 +146,7 @@ public class GsonAutoConfigurationTests { } @Test - public void customGsonBuilder() { + void customGsonBuilder() { this.contextRunner.withUserConfiguration(GsonBuilderConfig.class).run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":1,\"owner\":null}"); @@ -154,7 +154,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withPrettyPrinting() { + void withPrettyPrinting() { this.contextRunner.withPropertyValues("spring.gson.pretty-printing:true").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.toJson(new DataObject())).isEqualTo("{\n \"data\": 1\n}"); @@ -162,7 +162,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withoutLenient() { + void withoutLenient() { this.contextRunner.run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson).hasFieldOrPropertyWithValue("lenient", false); @@ -170,7 +170,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withLenient() { + void withLenient() { this.contextRunner.withPropertyValues("spring.gson.lenient:true").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson).hasFieldOrPropertyWithValue("lenient", true); @@ -178,7 +178,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withHtmlEscaping() { + void withHtmlEscaping() { this.contextRunner.run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.htmlSafe()).isTrue(); @@ -186,7 +186,7 @@ public class GsonAutoConfigurationTests { } @Test - public void withoutHtmlEscaping() { + void withoutHtmlEscaping() { this.contextRunner.withPropertyValues("spring.gson.disable-html-escaping:true").run((context) -> { Gson gson = context.getBean(Gson.class); assertThat(gson.htmlSafe()).isFalse(); @@ -195,7 +195,7 @@ public class GsonAutoConfigurationTests { } @Test - public void customDateFormat() { + void customDateFormat() { this.contextRunner.withPropertyValues("spring.gson.date-format:H").run((context) -> { Gson gson = context.getBean(Gson.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 379a9813b41..9ad74811704 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Marten Deinum * @author Stephane Nicoll */ -public class H2ConsoleAutoConfigurationTests { +class H2ConsoleAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); @@ -53,14 +53,14 @@ public class H2ConsoleAutoConfigurationTests { } @Test - public void consoleIsDisabledByDefault() { + void consoleIsDisabledByDefault() { this.context.register(H2ConsoleAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).isEmpty(); } @Test - public void propertyCanEnableConsole() { + void propertyCanEnableConsole() { this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues.of("spring.h2.console.enabled:true").applyTo(this.context); this.context.refresh(); @@ -72,7 +72,7 @@ public class H2ConsoleAutoConfigurationTests { } @Test - public void customPathMustBeginWithASlash() { + void customPathMustBeginWithASlash() { this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:custom").applyTo(this.context); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh) @@ -80,7 +80,7 @@ public class H2ConsoleAutoConfigurationTests { } @Test - public void customPathWithTrailingSlash() { + void customPathWithTrailingSlash() { this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom/") .applyTo(this.context); @@ -91,7 +91,7 @@ public class H2ConsoleAutoConfigurationTests { } @Test - public void customPath() { + void customPath() { this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.path:/custom").applyTo(this.context); this.context.refresh(); @@ -101,7 +101,7 @@ public class H2ConsoleAutoConfigurationTests { } @Test - public void customInitParameters() { + void customInitParameters() { this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues.of("spring.h2.console.enabled:true", "spring.h2.console.settings.trace=true", "spring.h2.console.settings.webAllowOthers=true").applyTo(this.context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java index 0068ff465f5..eb3918b0e27 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java @@ -25,26 +25,26 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Madhura Bhave */ -public class H2ConsolePropertiesTests { +class H2ConsolePropertiesTests { private H2ConsoleProperties properties; @Test - public void pathMustNotBeEmpty() { + void pathMustNotBeEmpty() { this.properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) .withMessageContaining("Path must have length greater than 1"); } @Test - public void pathMustHaveLengthGreaterThanOne() { + void pathMustHaveLengthGreaterThanOne() { this.properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) .withMessageContaining("Path must have length greater than 1"); } @Test - public void customPathMustBeginWithASlash() { + void customPathMustBeginWithASlash() { this.properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) .withMessageContaining("Path must start with '/'"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index f9b92d4555b..9d111174ea1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -52,7 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Oliver Gierke * @author Andy Wilkinson */ -public class HypermediaAutoConfigurationTests { +class HypermediaAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext context; @@ -64,7 +64,7 @@ public class HypermediaAutoConfigurationTests { } @Test - public void linkDiscoverersCreated() { + void linkDiscoverersCreated() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); @@ -76,7 +76,7 @@ public class HypermediaAutoConfigurationTests { } @Test - public void entityLinksCreated() { + void entityLinksCreated() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); @@ -86,7 +86,7 @@ public class HypermediaAutoConfigurationTests { } @Test - public void doesBackOffIfEnableHypermediaSupportIsDeclaredManually() { + void doesBackOffIfEnableHypermediaSupportIsDeclaredManually() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(EnableHypermediaSupportConfig.class, BaseConfig.class); @@ -97,7 +97,7 @@ public class HypermediaAutoConfigurationTests { } @Test - public void supportedMediaTypesOfTypeConstrainedConvertersIsCustomized() { + void supportedMediaTypesOfTypeConstrainedConvertersIsCustomized() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); @@ -112,7 +112,7 @@ public class HypermediaAutoConfigurationTests { } @Test - public void customizationOfSupportedMediaTypesCanBeDisabled() { + void customizationOfSupportedMediaTypesCanBeDisabled() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(BaseConfig.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java index bbbdc732244..10ee8d6ecb0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic * @author Stephane Nicoll */ -public class HazelcastAutoConfigurationClientTests { +class HazelcastAutoConfigurationClientTests { /** * Servers the test clients will connect to. @@ -65,27 +65,27 @@ public class HazelcastAutoConfigurationClientTests { .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test - public void systemPropertyWithXml() { + void systemPropertyWithXml() { this.contextRunner.withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-client-specific.xml") .run(assertSpecificHazelcastClient("explicit-xml")); } @Test - public void systemPropertyWithYaml() { + void systemPropertyWithYaml() { this.contextRunner.withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-client-specific.yaml") .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test - public void explicitConfigFileWithXml() { + void explicitConfigFileWithXml() { this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + "hazelcast/hazelcast-client-specific.xml").run(assertSpecificHazelcastClient("explicit-xml")); } @Test - public void explicitConfigFileWithYaml() { + void explicitConfigFileWithYaml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + "hazelcast/hazelcast-client-specific.yaml") @@ -93,7 +93,7 @@ public class HazelcastAutoConfigurationClientTests { } @Test - public void explicitConfigUrlWithXml() { + void explicitConfigUrlWithXml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") @@ -101,7 +101,7 @@ public class HazelcastAutoConfigurationClientTests { } @Test - public void explicitConfigUrlWithYaml() { + void explicitConfigUrlWithYaml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") @@ -109,14 +109,14 @@ public class HazelcastAutoConfigurationClientTests { } @Test - public void unknownConfigFile() { + void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("foo/bar/unknown.xml")); } @Test - public void clientConfigTakesPrecedence() { + void clientConfigTakesPrecedence() { this.contextRunner.withUserConfiguration(HazelcastServerAndClientConfig.class) .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> assertThat(context) .getBean(HazelcastInstance.class).isInstanceOf(HazelcastClientProxy.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index 308267aa9b6..f389c683a7c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -31,13 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class HazelcastAutoConfigurationTests { +class HazelcastAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test - public void defaultConfigFile() { + void defaultConfigFile() { // no hazelcast-client.xml and hazelcast.xml is present in root classpath // this also asserts that XML has priority over YAML // as both hazelcast.yaml and hazelcast.xml in test classpath. diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index 872e7329c5b..7dc4ea32ee9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -42,7 +42,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class HazelcastJpaDependencyAutoConfigurationTests { +class HazelcastJpaDependencyAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -51,7 +51,7 @@ public class HazelcastJpaDependencyAutoConfigurationTests { "spring.datasource.initialization-mode=never"); @Test - public void registrationIfHazelcastInstanceHasRegularBeanName() { + void registrationIfHazelcastInstanceHasRegularBeanName() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class).run((context) -> { assertThat(postProcessors(context)).containsKey("hazelcastInstanceJpaDependencyPostProcessor"); assertThat(entityManagerFactoryDependencies(context)).contains("hazelcastInstance"); @@ -59,7 +59,7 @@ public class HazelcastJpaDependencyAutoConfigurationTests { } @Test - public void noRegistrationIfHazelcastInstanceHasCustomBeanName() { + void noRegistrationIfHazelcastInstanceHasCustomBeanName() { this.contextRunner.withUserConfiguration(HazelcastCustomNameConfiguration.class).run((context) -> { assertThat(entityManagerFactoryDependencies(context)).doesNotContain("hazelcastInstance"); assertThat(postProcessors(context)).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); @@ -67,7 +67,7 @@ public class HazelcastJpaDependencyAutoConfigurationTests { } @Test - public void noRegistrationWithNoHazelcastInstance() { + void noRegistrationWithNoHazelcastInstance() { this.contextRunner.run((context) -> { assertThat(entityManagerFactoryDependencies(context)).doesNotContain("hazelcastInstance"); assertThat(postProcessors(context)).doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); @@ -75,7 +75,7 @@ public class HazelcastJpaDependencyAutoConfigurationTests { } @Test - public void noRegistrationWithNoEntityManagerFactory() { + void noRegistrationWithNoEntityManagerFactory() { new ApplicationContextRunner().withUserConfiguration(HazelcastConfiguration.class) .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) .run((context) -> assertThat(postProcessors(context)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java index da0f0e80867..a8ea6d7d6e9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java @@ -60,13 +60,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Sebastien Deleuze * @author Eddú Meléndez */ -public class HttpMessageConvertersAutoConfigurationTests { +class HttpMessageConvertersAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test - public void jacksonNotAvailable() { + void jacksonNotAvailable() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(ObjectMapper.class); assertThat(context).doesNotHaveBean(MappingJackson2HttpMessageConverter.class); @@ -75,31 +75,31 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void jacksonDefaultConverter() { + void jacksonDefaultConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class) .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test - public void jacksonConverterWithBuilder() { + void jacksonConverterWithBuilder() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test - public void jacksonXmlConverterWithBuilder() { + void jacksonXmlConverterWithBuilder() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class).run(assertConverter( MappingJackson2XmlHttpMessageConverter.class, "mappingJackson2XmlHttpMessageConverter")); } @Test - public void jacksonCustomConverter() { + void jacksonCustomConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class, JacksonConverterConfig.class) .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); } @Test - public void gsonNotAvailable() { + void gsonNotAvailable() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(Gson.class); assertThat(context).doesNotHaveBean(GsonHttpMessageConverter.class); @@ -107,20 +107,20 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void gsonDefaultConverter() { + void gsonDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); } @Test - public void gsonCustomConverter() { + void gsonCustomConverter() { this.contextRunner.withUserConfiguration(GsonConverterConfig.class) .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); } @Test - public void gsonCanBePreferred() { + void gsonCanBePreferred() { allOptionsRunner().withPropertyValues("spring.http.converters.preferred-json-mapper:gson").run((context) -> { assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); @@ -130,7 +130,7 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void jsonbNotAvailable() { + void jsonbNotAvailable() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(Jsonb.class); assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); @@ -138,20 +138,20 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void jsonbDefaultConverter() { + void jsonbDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test - public void jsonbCustomConverter() { + void jsonbCustomConverter() { this.contextRunner.withUserConfiguration(JsonbConverterConfig.class) .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); } @Test - public void jsonbCanBePreferred() { + void jsonbCanBePreferred() { allOptionsRunner().withPropertyValues("spring.http.converters.preferred-json-mapper:jsonb").run((context) -> { assertConverterBeanExists(context, JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter"); assertConverterBeanRegisteredWithHttpMessageConverters(context, JsonbHttpMessageConverter.class); @@ -161,18 +161,18 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void stringDefaultConverter() { + void stringDefaultConverter() { this.contextRunner.run(assertConverter(StringHttpMessageConverter.class, "stringHttpMessageConverter")); } @Test - public void stringCustomConverter() { + void stringCustomConverter() { this.contextRunner.withUserConfiguration(StringConverterConfig.class) .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); } @Test - public void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() { + void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class, TypeConstrainedConverterConfiguration.class).run((context) -> { BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) @@ -183,7 +183,7 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() { + void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() { this.contextRunner .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) .run((context) -> { @@ -195,7 +195,7 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void jacksonIsPreferredByDefault() { + void jacksonIsPreferredByDefault() { allOptionsRunner().run((context) -> { assertConverterBeanExists(context, MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter"); @@ -206,7 +206,7 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void gsonIsPreferredIfJacksonIsNotAvailable() { + void gsonIsPreferredIfJacksonIsNotAvailable() { allOptionsRunner().withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName())) .run((context) -> { assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); @@ -216,7 +216,7 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void jsonbIsPreferredIfJacksonAndGsonAreNotAvailable() { + void jsonbIsPreferredIfJacksonAndGsonAreNotAvailable() { allOptionsRunner() .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), Gson.class.getPackage().getName())) @@ -224,14 +224,14 @@ public class HttpMessageConvertersAutoConfigurationTests { } @Test - public void whenServletWebApplicationHttpMessageConvertersIsConfigured() { + void whenServletWebApplicationHttpMessageConvertersIsConfigured() { new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); } @Test - public void whenReactiveWebApplicationHttpMessageConvertersIsNotConfigured() { + void whenReactiveWebApplicationHttpMessageConvertersIsNotConfigured() { new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java index 4e3a1fa4623..6859d5a5682 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.autoconfigure.http; +import org.junit.After; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; @@ -38,7 +38,7 @@ public class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @AfterEach + @After public void close() { if (this.context != null) { this.context.close(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java index ca36e1799e4..f8468fa85bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java @@ -44,10 +44,10 @@ import static org.mockito.Mockito.mock; * @author Dave Syer * @author Phillip Webb */ -public class HttpMessageConvertersTests { +class HttpMessageConvertersTests { @Test - public void containsDefaults() { + void containsDefaults() { HttpMessageConverters converters = new HttpMessageConverters(); List> converterClasses = new ArrayList<>(); for (HttpMessageConverter converter : converters) { @@ -62,7 +62,7 @@ public class HttpMessageConvertersTests { } @Test - public void addBeforeExistingConverter() { + void addBeforeExistingConverter() { MappingJackson2HttpMessageConverter converter1 = new MappingJackson2HttpMessageConverter(); MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter(); HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); @@ -82,7 +82,7 @@ public class HttpMessageConvertersTests { } @Test - public void addNewConverters() { + void addNewConverters() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); @@ -91,7 +91,7 @@ public class HttpMessageConvertersTests { } @Test - public void convertersAreAddedToFormPartConverter() { + void convertersAreAddedToFormPartConverter() { HttpMessageConverter converter1 = mock(HttpMessageConverter.class); HttpMessageConverter converter2 = mock(HttpMessageConverter.class); List> converters = new HttpMessageConverters(converter1, converter2).getConverters(); @@ -101,7 +101,7 @@ public class HttpMessageConvertersTests { } @Test - public void postProcessConverters() { + void postProcessConverters() { HttpMessageConverters converters = new HttpMessageConverters() { @Override @@ -123,7 +123,7 @@ public class HttpMessageConvertersTests { } @Test - public void postProcessPartConverters() { + void postProcessPartConverters() { HttpMessageConverters converters = new HttpMessageConverters() { @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java index 5d012863364..500f47f1926 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java @@ -40,13 +40,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Andy Wilkinson */ -public class CodecsAutoConfigurationTests { +class CodecsAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CodecsAutoConfiguration.class)); @Test - public void autoConfigShouldProvideALoggingRequestDetailsCustomizer() { + void autoConfigShouldProvideALoggingRequestDetailsCustomizer() { this.contextRunner.run((context) -> { CodecCustomizer customizer = context.getBean(CodecCustomizer.class); CodecConfigurer configurer = new DefaultClientCodecConfigurer(); @@ -57,7 +57,7 @@ public class CodecsAutoConfigurationTests { } @Test - public void loggingRequestDetailsCustomizerShouldUseHttpProperties() { + void loggingRequestDetailsCustomizerShouldUseHttpProperties() { this.contextRunner.withPropertyValues("spring.http.log-request-details=true").run((context) -> { CodecCustomizer customizer = context.getBean(CodecCustomizer.class); CodecConfigurer configurer = new DefaultClientCodecConfigurer(); @@ -67,7 +67,7 @@ public class CodecsAutoConfigurationTests { } @Test - public void loggingRequestDetailsBeanShouldHaveOrderZero() { + void loggingRequestDetailsBeanShouldHaveOrderZero() { this.contextRunner.run((context) -> { Method customizerMethod = ReflectionUtils.findMethod( CodecsAutoConfiguration.LoggingCodecConfiguration.class, "loggingCodecCustomizer", @@ -78,18 +78,18 @@ public class CodecsAutoConfigurationTests { } @Test - public void jacksonCodecCustomizerBacksOffWhenThereIsNoObjectMapper() { + void jacksonCodecCustomizerBacksOffWhenThereIsNoObjectMapper() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("jacksonCodecCustomizer")); } @Test - public void jacksonCodecCustomizerIsAutoConfiguredWhenObjectMapperIsPresent() { + void jacksonCodecCustomizerIsAutoConfiguredWhenObjectMapperIsPresent() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class) .run((context) -> assertThat(context).hasBean("jacksonCodecCustomizer")); } @Test - public void userProvidedCustomizerCanOverrideJacksonCodecCustomizer() { + void userProvidedCustomizerCanOverrideJacksonCodecCustomizer() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class, CodecCustomizerConfiguration.class) .run((context) -> { List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java index 22d3249e228..07337d87fbd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java @@ -39,18 +39,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Eddú Meléndez */ -public class InfluxDbAutoConfigurationTests { +class InfluxDbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class)); @Test - public void influxDbRequiresUrl() { + void influxDbRequiresUrl() { this.contextRunner.run((context) -> assertThat(context.getBeansOfType(InfluxDB.class)).isEmpty()); } @Test - public void influxDbCanBeCustomized() { + void influxDbCanBeCustomized() { this.contextRunner .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.password:password", "spring.influx.user:user") @@ -58,7 +58,7 @@ public class InfluxDbAutoConfigurationTests { } @Test - public void influxDbCanBeCreatedWithoutCredentials() { + void influxDbCanBeCreatedWithoutCredentials() { this.contextRunner.withPropertyValues("spring.influx.url=http://localhost").run((context) -> { assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); int readTimeout = getReadTimeoutProperty(context); @@ -67,7 +67,7 @@ public class InfluxDbAutoConfigurationTests { } @Test - public void influxDbWithOkHttpClientBuilderProvider() { + void influxDbWithOkHttpClientBuilderProvider() { this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderProviderConfig.class) .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index d29235ea8b7..2e1f7a74e38 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -35,18 +35,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ProjectInfoAutoConfigurationTests { +class ProjectInfoAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, ProjectInfoAutoConfiguration.class)); @Test - public void gitPropertiesUnavailableIfResourceNotAvailable() { + void gitPropertiesUnavailableIfResourceNotAvailable() { this.contextRunner.run((context) -> assertThat(context.getBeansOfType(GitProperties.class)).isEmpty()); } @Test - public void gitPropertiesWithNoData() { + void gitPropertiesWithNoData() { this.contextRunner .withPropertyValues("spring.info.git.location=" + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") @@ -57,7 +57,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void gitPropertiesFallbackWithGitPropertiesBean() { + void gitPropertiesFallbackWithGitPropertiesBean() { this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).withPropertyValues( "spring.info.git.location=" + "classpath:/org/springframework/boot/autoconfigure/info/git.properties") .run((context) -> { @@ -67,7 +67,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void gitPropertiesUsesUtf8ByDefault() { + void gitPropertiesUsesUtf8ByDefault() { this.contextRunner.withPropertyValues( "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") .run((context) -> { @@ -77,7 +77,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void gitPropertiesEncodingCanBeConfigured() { + void gitPropertiesEncodingCanBeConfigured() { this.contextRunner.withPropertyValues("spring.info.git.encoding=US-ASCII", "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") .run((context) -> { @@ -87,7 +87,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void buildPropertiesDefaultLocation() { + void buildPropertiesDefaultLocation() { this.contextRunner.run((context) -> { BuildProperties buildProperties = context.getBean(BuildProperties.class); assertThat(buildProperties.getGroup()).isEqualTo("com.example"); @@ -99,7 +99,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void buildPropertiesCustomLocation() { + void buildPropertiesCustomLocation() { this.contextRunner .withPropertyValues("spring.info.build.location=" + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") @@ -114,14 +114,14 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void buildPropertiesCustomInvalidLocation() { + void buildPropertiesCustomInvalidLocation() { this.contextRunner .withPropertyValues("spring.info.build.location=" + "classpath:/org/acme/no-build-info.properties") .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); } @Test - public void buildPropertiesFallbackWithBuildInfoBean() { + void buildPropertiesFallbackWithBuildInfoBean() { this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).run((context) -> { BuildProperties buildProperties = context.getBean(BuildProperties.class); assertThat(buildProperties).isSameAs(context.getBean("customBuildProperties")); @@ -129,7 +129,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void buildPropertiesUsesUtf8ByDefault() { + void buildPropertiesUsesUtf8ByDefault() { this.contextRunner.withPropertyValues( "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") .run((context) -> { @@ -139,7 +139,7 @@ public class ProjectInfoAutoConfigurationTests { } @Test - public void buildPropertiesEncodingCanBeConfigured() { + void buildPropertiesEncodingCanBeConfigured() { this.contextRunner.withPropertyValues("spring.info.build.encoding=US-ASCII", "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index 4aaf00394fb..2f88d96ca11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -54,13 +54,13 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Vedran Pavic */ -public class IntegrationAutoConfigurationTests { +class IntegrationAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); @Test - public void integrationIsAvailable() { + void integrationIsAvailable() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); assertThat(context).hasSingleBean(IntegrationComponentScanConfiguration.class); @@ -68,7 +68,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void explicitIntegrationComponentScan() { + void explicitIntegrationComponentScan() { this.contextRunner.withUserConfiguration(CustomIntegrationComponentScanConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); assertThat(context).doesNotHaveBean(IntegrationComponentScanConfiguration.class); @@ -76,7 +76,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void noMBeanServerAvailable() { + void noMBeanServerAvailable() { ApplicationContextRunner contextRunnerWithoutJmx = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); contextRunnerWithoutJmx.run((context) -> { @@ -86,14 +86,14 @@ public class IntegrationAutoConfigurationTests { } @Test - public void parentContext() { + void parentContext() { this.contextRunner.run((context) -> this.contextRunner.withParent(context) .withPropertyValues("spring.jmx.default_domain=org.foo") .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); } @Test - public void enableJmxIntegration() { + void enableJmxIntegration() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true").run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); assertThat(mBeanServer.getDomains()).contains("org.springframework.integration", @@ -103,7 +103,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void jmxIntegrationIsDisabledByDefault() { + void jmxIntegrationIsDisabledByDefault() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(MBeanServer.class); assertThat(context).hasSingleBean(IntegrationManagementConfigurer.class); @@ -111,7 +111,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void customizeJmxDomain() { + void customizeJmxDomain() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default_domain=org.foo") .run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); @@ -121,7 +121,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void primaryExporterIsAllowed() { + void primaryExporterIsAllowed() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true") .withUserConfiguration(CustomMBeanExporter.class).run((context) -> { assertThat(context).getBeans(MBeanExporter.class).hasSize(2); @@ -130,7 +130,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void integrationJdbcDataSourceInitializerEnabled() { + void integrationJdbcDataSourceInitializerEnabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) @@ -150,7 +150,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void integrationJdbcDataSourceInitializerDisabled() { + void integrationJdbcDataSourceInitializerDisabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) @@ -167,7 +167,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void integrationJdbcDataSourceInitializerEnabledByDefaultWithEmbeddedDb() { + void integrationJdbcDataSourceInitializerEnabledByDefaultWithEmbeddedDb() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) @@ -181,7 +181,7 @@ public class IntegrationAutoConfigurationTests { } @Test - public void integrationEnablesDefaultCounts() { + void integrationEnablesDefaultCounts() { this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class).run((context) -> { assertThat(context).hasBean("myMessageSource"); assertThat(((MessageProcessorMessageSource) context.getBean("myMessageSource")).isCountsEnabled()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index c3c1f50acc7..bc400c8a04b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -74,13 +74,13 @@ import static org.mockito.Mockito.mock; * @author Johannes Edmeier * @author Grzegorz Poznachowski */ -public class JacksonAutoConfigurationTests { +class JacksonAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)); @Test - public void registersJodaModuleAutomatically() { + void registersJodaModuleAutomatically() { this.contextRunner.run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); @@ -88,7 +88,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void doubleModuleRegistration() { + void doubleModuleRegistration() { this.contextRunner.withUserConfiguration(DoubleModulesConfig.class) .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .run((context) -> { @@ -98,7 +98,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void noCustomDateFormat() { + void noCustomDateFormat() { this.contextRunner.run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class); @@ -106,7 +106,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customDateFormat() { + void customDateFormat() { this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); DateFormat dateFormat = mapper.getDateFormat(); @@ -116,7 +116,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customJodaDateTimeFormat() throws Exception { + void customJodaDateTimeFormat() throws Exception { this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss", "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -128,7 +128,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customDateFormatClass() { + void customDateFormatClass() { this.contextRunner.withPropertyValues( "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat") .run((context) -> { @@ -138,7 +138,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void noCustomPropertyNamingStrategy() { + void noCustomPropertyNamingStrategy() { this.contextRunner.run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(mapper.getPropertyNamingStrategy()).isNull(); @@ -146,7 +146,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customPropertyNamingStrategyField() { + void customPropertyNamingStrategyField() { this.contextRunner.withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); @@ -154,7 +154,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customPropertyNamingStrategyClass() { + void customPropertyNamingStrategyClass() { this.contextRunner.withPropertyValues( "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy") .run((context) -> { @@ -164,7 +164,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void enableSerializationFeature() { + void enableSerializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.serialization.indent_output:true").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); @@ -174,7 +174,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void disableSerializationFeature() { + void disableSerializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -186,7 +186,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void enableDeserializationFeature() { + void enableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -198,7 +198,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void disableDeserializationFeature() { + void disableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -210,7 +210,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void enableMapperFeature() { + void enableMapperFeature() { this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -223,7 +223,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void disableMapperFeature() { + void disableMapperFeature() { this.contextRunner.withPropertyValues("spring.jackson.mapper.use_annotations:false").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); @@ -235,7 +235,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void enableParserFeature() { + void enableParserFeature() { this.contextRunner.withPropertyValues("spring.jackson.parser.allow_single_quotes:true").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse(); @@ -244,7 +244,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void disableParserFeature() { + void disableParserFeature() { this.contextRunner.withPropertyValues("spring.jackson.parser.auto_close_source:false").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue(); @@ -253,7 +253,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void enableGeneratorFeature() { + void enableGeneratorFeature() { this.contextRunner.withPropertyValues("spring.jackson.generator.write_numbers_as_strings:true") .run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); @@ -263,7 +263,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void disableGeneratorFeature() { + void disableGeneratorFeature() { this.contextRunner.withPropertyValues("spring.jackson.generator.auto_close_target:false").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue(); @@ -272,7 +272,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void defaultObjectMapperBuilder() { + void defaultObjectMapperBuilder() { this.contextRunner.run((context) -> { Jackson2ObjectMapperBuilder builder = context.getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); @@ -288,7 +288,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { + void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { this.contextRunner.withUserConfiguration(ModuleConfig.class).run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(context.getBean(CustomModule.class).getOwners()).contains((ObjectCodec) objectMapper); @@ -298,7 +298,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void defaultSerializationInclusion() { + void defaultSerializationInclusion() { this.contextRunner.run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) @@ -307,7 +307,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customSerializationInclusion() { + void customSerializationInclusion() { this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null").run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) @@ -316,7 +316,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customTimeZoneFormattingADateTime() { + void customTimeZoneFormattingADateTime() { this.contextRunner.withPropertyValues("spring.jackson.time-zone:America/Los_Angeles", "spring.jackson.date-format:zzzz", "spring.jackson.locale:en").run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); @@ -326,7 +326,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customTimeZoneFormattingADate() throws JsonProcessingException { + void customTimeZoneFormattingADate() throws JsonProcessingException { this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", "spring.jackson.date-format:z") .run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); @@ -336,7 +336,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void customLocaleWithJodaTime() throws JsonProcessingException { + void customLocaleWithJodaTime() throws JsonProcessingException { this.contextRunner.withPropertyValues("spring.jackson.locale:de_DE", "spring.jackson.date-format:zzzz", "spring.jackson.serialization.write-dates-with-zone-id:true").run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); @@ -346,7 +346,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void additionalJacksonBuilderCustomization() { + void additionalJacksonBuilderCustomization() { this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class).run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); @@ -354,18 +354,18 @@ public class JacksonAutoConfigurationTests { } @Test - public void parameterNamesModuleIsAutoConfigured() { + void parameterNamesModuleIsAutoConfigured() { assertParameterNamesModuleCreatorBinding(Mode.DEFAULT, JacksonAutoConfiguration.class); } @Test - public void customParameterNamesModuleCanBeConfigured() { + void customParameterNamesModuleCanBeConfigured() { assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, ParameterNamesModuleConfig.class, JacksonAutoConfiguration.class); } @Test - public void writeDatesAsTimestampsDefault() { + void writeDatesAsTimestampsDefault() { this.contextRunner.run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); @@ -376,7 +376,7 @@ public class JacksonAutoConfigurationTests { } @Test - public void writeWithVisibility() { + void writeWithVisibility() { this.contextRunner .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index 48447a02f91..fba0594d89e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -58,7 +58,7 @@ import static org.mockito.Mockito.mock; * @author Dave Syer * @author Stephane Nicoll */ -public class DataSourceAutoConfigurationTests { +class DataSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) @@ -66,12 +66,12 @@ public class DataSourceAutoConfigurationTests { "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); @Test - public void testDefaultDataSourceExists() { + void testDefaultDataSourceExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DataSource.class)); } @Test - public void testDataSourceHasEmbeddedDefault() { + void testDataSourceHasEmbeddedDefault() { this.contextRunner.run((context) -> { HikariDataSource dataSource = context.getBean(HikariDataSource.class); assertThat(dataSource.getJdbcUrl()).isNotNull(); @@ -80,34 +80,34 @@ public class DataSourceAutoConfigurationTests { } @Test - public void testBadUrl() { + void testBadUrl() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test - public void testBadDriverClass() { + void testBadDriverClass() { this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.none.jdbcDriver") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("org.none.jdbcDriver")); } @Test - public void hikariValidatesConnectionByDefault() { + void hikariValidatesConnectionByDefault() { assertDataSource(HikariDataSource.class, Collections.singletonList("org.apache.tomcat"), (dataSource) -> // Use Connection#isValid() assertThat(dataSource.getConnectionTestQuery()).isNull()); } @Test - public void tomcatIsFallback() { + void tomcatIsFallback() { assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, Collections.singletonList("com.zaxxer.hikari"), (dataSource) -> assertThat(dataSource.getUrl()).startsWith("jdbc:hsqldb:mem:testdb")); } @Test - public void tomcatValidatesConnectionByDefault() { + void tomcatValidatesConnectionByDefault() { assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, Collections.singletonList("com.zaxxer.hikari"), (dataSource) -> { assertThat(dataSource.isTestOnBorrow()).isTrue(); @@ -116,13 +116,13 @@ public class DataSourceAutoConfigurationTests { } @Test - public void commonsDbcp2IsFallback() { + void commonsDbcp2IsFallback() { assertDataSource(BasicDataSource.class, Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), (dataSource) -> assertThat(dataSource.getUrl()).startsWith("jdbc:hsqldb:mem:testdb")); } @Test - public void commonsDbcp2ValidatesConnectionByDefault() { + void commonsDbcp2ValidatesConnectionByDefault() { assertDataSource(org.apache.commons.dbcp2.BasicDataSource.class, Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), (dataSource) -> { assertThat(dataSource.getTestOnBorrow()).isTrue(); @@ -133,7 +133,7 @@ public class DataSourceAutoConfigurationTests { @Test @SuppressWarnings("resource") - public void testEmbeddedTypeDefaultsUsername() { + void testEmbeddedTypeDefaultsUsername() { this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((context) -> { DataSource bean = context.getBean(DataSource.class); @@ -148,7 +148,7 @@ public class DataSourceAutoConfigurationTests { * still created if "spring.datasource.type" is present. */ @Test - public void explicitTypeNoSupportedDataSource() { + void explicitTypeNoSupportedDataSource() { this.contextRunner .withClassLoader(new FilteredClassLoader("org.apache.tomcat", "com.zaxxer.hikari", "org.apache.commons.dbcp", "org.apache.commons.dbcp2")) @@ -159,7 +159,7 @@ public class DataSourceAutoConfigurationTests { } @Test - public void explicitTypeSupportedDataSource() { + void explicitTypeSupportedDataSource() { this.contextRunner .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", @@ -173,7 +173,7 @@ public class DataSourceAutoConfigurationTests { } @Test - public void testExplicitDriverClassClearsUsername() { + void testExplicitDriverClassClearsUsername() { this.contextRunner.withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), "spring.datasource.url:jdbc:foo://localhost").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); @@ -184,13 +184,13 @@ public class DataSourceAutoConfigurationTests { } @Test - public void testDefaultDataSourceCanBeOverridden() { + void testDefaultDataSourceCanBeOverridden() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test - public void testDataSourceIsInitializedEarly() { + void testDataSourceIsInitializedEarly() { this.contextRunner.withUserConfiguration(TestInitializedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.initialization-mode=always") .run((context) -> assertThat(context.getBean(TestInitializedDataSourceConfiguration.class).called) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java index 20ed8553103..aa6b9927165 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java @@ -55,7 +55,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Dave Syer * @author Stephane Nicoll */ -public class DataSourceInitializerInvokerTests { +class DataSourceInitializerInvokerTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) @@ -63,7 +63,7 @@ public class DataSourceInitializerInvokerTests { "spring.datasource.url:jdbc:hsqldb:mem:init-" + UUID.randomUUID()); @Test - public void dataSourceInitialized() { + void dataSourceInitialized() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); DataSource dataSource = context.getBean(DataSource.class); @@ -73,7 +73,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void initializationAppliesToCustomDataSource() { + void initializationAppliesToCustomDataSource() { this.contextRunner.withUserConfiguration(OneDataSource.class) .withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); @@ -87,7 +87,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithExplicitScript() { + void dataSourceInitializedWithExplicitScript() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.schema:" + getRelativeLocationFor("schema.sql"), "spring.datasource.data:" + getRelativeLocationFor("data.sql")).run((context) -> { @@ -100,7 +100,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithMultipleScripts() { + void dataSourceInitializedWithMultipleScripts() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.schema:" + getRelativeLocationFor("schema.sql") + "," + getRelativeLocationFor("another.sql"), @@ -115,7 +115,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithExplicitSqlScriptEncoding() { + void dataSourceInitializedWithExplicitSqlScriptEncoding() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.sqlScriptEncoding:UTF-8", "spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"), @@ -133,12 +133,12 @@ public class DataSourceInitializerInvokerTests { } @Test - public void initializationDisabled() { + void initializationDisabled() { this.contextRunner.run(assertInitializationIsDisabled()); } @Test - public void initializationDoesNotApplyWithSeveralDataSources() { + void initializationDoesNotApplyWithSeveralDataSources() { this.contextRunner.withUserConfiguration(TwoDataSources.class) .withPropertyValues("spring.datasource.initialization-mode:always").run((context) -> { assertThat(context.getBeanNamesForType(DataSource.class)).hasSize(2); @@ -168,7 +168,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithSchemaCredentials() { + void dataSourceInitializedWithSchemaCredentials() { this.contextRunner .withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.sqlScriptEncoding:UTF-8", @@ -182,7 +182,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithDataCredentials() { + void dataSourceInitializedWithDataCredentials() { this.contextRunner .withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.sqlScriptEncoding:UTF-8", @@ -196,7 +196,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void multipleScriptsAppliedInLexicalOrder() { + void multipleScriptsAppliedInLexicalOrder() { new ApplicationContextRunner(() -> { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setResourceLoader(new ReverseOrderResourceLoader(new DefaultResourceLoader())); @@ -216,7 +216,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void testDataSourceInitializedWithInvalidSchemaResource() { + void testDataSourceInitializedWithInvalidSchemaResource() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.schema:classpath:does/not/exist.sql").run((context) -> { assertThat(context).hasFailed(); @@ -227,7 +227,7 @@ public class DataSourceInitializerInvokerTests { } @Test - public void dataSourceInitializedWithInvalidDataResource() { + void dataSourceInitializedWithInvalidDataResource() { this.contextRunner.withPropertyValues("spring.datasource.initialization-mode:always", "spring.datasource.schema:" + getRelativeLocationFor("schema.sql"), "spring.datasource.data:classpath:does/not/exist.sql").run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java index f01c3cb12d5..a9e8d212cd6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java @@ -40,10 +40,10 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class DataSourceInitializerTests { +class DataSourceInitializerTests { @Test - public void initializeEmbeddedByDefault() { + void initializeEmbeddedByDefault() { try (HikariDataSource dataSource = createDataSource()) { DataSourceInitializer initializer = new DataSourceInitializer(dataSource, new DataSourceProperties()); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); @@ -55,7 +55,7 @@ public class DataSourceInitializerTests { } @Test - public void initializeWithModeAlways() { + void initializeWithModeAlways() { try (HikariDataSource dataSource = createDataSource()) { DataSourceProperties properties = new DataSourceProperties(); properties.setInitializationMode(DataSourceInitializationMode.ALWAYS); @@ -73,7 +73,7 @@ public class DataSourceInitializerTests { } @Test - public void initializeWithModeNever() { + void initializeWithModeNever() { try (HikariDataSource dataSource = createDataSource()) { DataSourceProperties properties = new DataSourceProperties(); properties.setInitializationMode(DataSourceInitializationMode.NEVER); @@ -83,7 +83,7 @@ public class DataSourceInitializerTests { } @Test - public void initializeOnlyEmbeddedByDefault() throws SQLException { + void initializeOnlyEmbeddedByDefault() throws SQLException { DatabaseMetaData metadata = mock(DatabaseMetaData.class); given(metadata.getDatabaseProductName()).willReturn("MySQL"); Connection connection = mock(Connection.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java index f674ae108ae..6cc01c4f758 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java @@ -48,14 +48,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Tadaya Tsuyukubo */ -public class DataSourceJmxConfigurationTests { +class DataSourceJmxConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.url=" + "jdbc:hsqldb:mem:test-" + UUID.randomUUID()) .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); @Test - public void hikariAutoConfiguredCanUseRegisterMBeans() { + void hikariAutoConfiguredCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner .withPropertyValues("spring.jmx.enabled=true", @@ -70,7 +70,7 @@ public class DataSourceJmxConfigurationTests { } @Test - public void hikariAutoConfiguredWithoutDataSourceName() throws MalformedObjectNameException { + void hikariAutoConfiguredWithoutDataSourceName() throws MalformedObjectNameException { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set existingInstances = mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null); @@ -87,7 +87,7 @@ public class DataSourceJmxConfigurationTests { } @Test - public void hikariAutoConfiguredUsesJmsFlag() { + void hikariAutoConfiguredUsesJmsFlag() { String poolName = UUID.randomUUID().toString(); this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, @@ -100,7 +100,7 @@ public class DataSourceJmxConfigurationTests { } @Test - public void hikariProxiedCanUseRegisterMBeans() { + void hikariProxiedCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) .withPropertyValues("spring.jmx.enabled=true", @@ -125,13 +125,13 @@ public class DataSourceJmxConfigurationTests { } @Test - public void tomcatDoesNotExposeMBeanPoolByDefault() { + void tomcatDoesNotExposeMBeanPoolByDefault() { this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName()) .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); } @Test - public void tomcatAutoConfiguredCanExposeMBeanPool() { + void tomcatAutoConfiguredCanExposeMBeanPool() { this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true").run((context) -> { assertThat(context).hasBean("dataSourceMBean"); @@ -142,7 +142,7 @@ public class DataSourceJmxConfigurationTests { } @Test - public void tomcatProxiedCanExposeMBeanPool() { + void tomcatProxiedCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true") @@ -153,7 +153,7 @@ public class DataSourceJmxConfigurationTests { } @Test - public void tomcatDelegateCanExposeMBeanPool() { + void tomcatDelegateCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceDelegateConfiguration.class) .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), "spring.datasource.tomcat.jmx-enabled=true") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index 424c117365d..cf01f66e21e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -50,10 +50,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class DataSourceJsonSerializationTests { +class DataSourceJsonSerializationTests { @Test - public void serializerFactory() throws Exception { + void serializerFactory() throws Exception { DataSource dataSource = new DataSource(); SerializerFactory factory = BeanSerializerFactory.instance .withSerializerModifier(new GenericSerializerModifier()); @@ -64,7 +64,7 @@ public class DataSourceJsonSerializationTests { } @Test - public void serializerWithMixin() throws Exception { + void serializerWithMixin() throws Exception { DataSource dataSource = new DataSource(); ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(DataSource.class, DataSourceJson.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 13abaa3bb0d..551caea1fa6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -31,10 +31,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Stephane Nicoll * @author Eddú Meléndez */ -public class DataSourcePropertiesTests { +class DataSourcePropertiesTests { @Test - public void determineDriver() { + void determineDriver() { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); assertThat(properties.getDriverClassName()).isNull(); @@ -42,7 +42,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineDriverWithExplicitConfig() { + void determineDriverWithExplicitConfig() { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); properties.setDriverClassName("org.hsqldb.jdbcDriver"); @@ -51,7 +51,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUrl() throws Exception { + void determineUrl() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); assertThat(properties.getUrl()).isNull(); @@ -59,7 +59,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUrlWithNoEmbeddedSupport() throws Exception { + void determineUrlWithNoEmbeddedSupport() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.setBeanClassLoader(new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); @@ -68,7 +68,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUrlWithExplicitConfig() throws Exception { + void determineUrlWithExplicitConfig() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); properties.afterPropertiesSet(); @@ -77,7 +77,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUrlWithGenerateUniqueName() throws Exception { + void determineUrlWithGenerateUniqueName() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.setGenerateUniqueName(true); properties.afterPropertiesSet(); @@ -90,7 +90,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUsername() throws Exception { + void determineUsername() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); assertThat(properties.getUsername()).isNull(); @@ -98,7 +98,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineUsernameWithExplicitConfig() throws Exception { + void determineUsernameWithExplicitConfig() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.setUsername("foo"); properties.afterPropertiesSet(); @@ -107,7 +107,7 @@ public class DataSourcePropertiesTests { } @Test - public void determinePassword() throws Exception { + void determinePassword() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); assertThat(properties.getPassword()).isNull(); @@ -115,7 +115,7 @@ public class DataSourcePropertiesTests { } @Test - public void determinePasswordWithExplicitConfig() throws Exception { + void determinePasswordWithExplicitConfig() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.setPassword("bar"); properties.afterPropertiesSet(); @@ -124,7 +124,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineCredentialsForSchemaScripts() { + void determineCredentialsForSchemaScripts() { DataSourceProperties properties = new DataSourceProperties(); properties.setSchemaUsername("foo"); properties.setSchemaPassword("bar"); @@ -133,7 +133,7 @@ public class DataSourcePropertiesTests { } @Test - public void determineCredentialsForDataScripts() { + void determineCredentialsForDataScripts() { DataSourceProperties properties = new DataSourceProperties(); properties.setDataUsername("foo"); properties.setDataPassword("bar"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index f6700dae3fa..c29896bb960 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -39,12 +39,12 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Kazuki Shimizu */ -public class DataSourceTransactionManagerAutoConfigurationTests { +class DataSourceTransactionManagerAutoConfigurationTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void testDataSourceExists() { + void testDataSourceExists() { this.context.register(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); @@ -53,7 +53,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testNoDataSourceExists() { + void testNoDataSourceExists() { this.context.register(DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(DataSource.class)).isEmpty(); @@ -61,7 +61,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testManualConfiguration() { + void testManualConfiguration() { this.context.register(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); @@ -70,7 +70,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testExistingTransactionManager() { + void testExistingTransactionManager() { this.context.register(TransactionManagerConfiguration.class, EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); @@ -80,7 +80,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testMultiDataSource() { + void testMultiDataSource() { this.context.register(MultiDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); @@ -88,7 +88,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testMultiDataSourceUsingPrimary() { + void testMultiDataSourceUsingPrimary() { this.context.register(MultiDataSourceUsingPrimaryConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class); this.context.refresh(); @@ -97,7 +97,7 @@ public class DataSourceTransactionManagerAutoConfigurationTests { } @Test - public void testCustomizeDataSourceTransactionManagerUsingProperties() { + void testCustomizeDataSourceTransactionManagerUsingProperties() { TestPropertyValues .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") .applyTo(this.context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java index 6cc4a341ac3..5ed596ee5c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public class EmbeddedDataSourceConfigurationTests { +class EmbeddedDataSourceConfigurationTests { private AnnotationConfigApplicationContext context; @@ -48,13 +48,13 @@ public class EmbeddedDataSourceConfigurationTests { } @Test - public void defaultEmbeddedDatabase() { + void defaultEmbeddedDatabase() { this.context = load(); assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test - public void generateUniqueName() throws Exception { + void generateUniqueName() throws Exception { this.context = load("spring.datasource.generate-unique-name=true"); try (AnnotationConfigApplicationContext context2 = load("spring.datasource.generate-unique-name=true")) { DataSource dataSource = this.context.getBean(DataSource.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index 60f21860ffd..4aee20fc1a8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public class HikariDataSourceConfigurationTests { +class HikariDataSourceConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) @@ -40,7 +40,7 @@ public class HikariDataSourceConfigurationTests { "spring.datasource.type=" + HikariDataSource.class.getName()); @Test - public void testDataSourceExists() { + void testDataSourceExists() { this.contextRunner.run((context) -> { assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); assertThat(context.getBeansOfType(HikariDataSource.class)).hasSize(1); @@ -48,7 +48,7 @@ public class HikariDataSourceConfigurationTests { } @Test - public void testDataSourcePropertiesOverridden() { + void testDataSourcePropertiesOverridden() { this.contextRunner.withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", "spring.datasource.hikari.max-lifetime=1234").run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); @@ -59,7 +59,7 @@ public class HikariDataSourceConfigurationTests { } @Test - public void testDataSourceGenericPropertiesOverridden() { + void testDataSourceGenericPropertiesOverridden() { this.contextRunner.withPropertyValues( "spring.datasource.hikari.data-source-properties" + ".dataSourceClassName=org.h2.JDBCDataSource") .run((context) -> { @@ -71,7 +71,7 @@ public class HikariDataSourceConfigurationTests { } @Test - public void testDataSourceDefaultsPreserved() { + void testDataSourceDefaultsPreserved() { this.contextRunner.run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); assertThat(ds.getMaxLifetime()).isEqualTo(1800000); @@ -79,7 +79,7 @@ public class HikariDataSourceConfigurationTests { } @Test - public void nameIsAliasedToPoolName() { + void nameIsAliasedToPoolName() { this.contextRunner.withPropertyValues("spring.datasource.name=myDS").run((context) -> { HikariDataSource ds = context.getBean(HikariDataSource.class); assertThat(ds.getPoolName()).isEqualTo("myDS"); @@ -88,7 +88,7 @@ public class HikariDataSourceConfigurationTests { } @Test - public void poolNameTakesPrecedenceOverName() { + void poolNameTakesPrecedenceOverName() { this.contextRunner .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java index c7587cd76e2..a57b390298c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class HikariDriverConfigurationFailureAnalyzerTests { +class HikariDriverConfigurationFailureAnalyzerTests { @Test - public void failureAnalysisIsPerformed() { + void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis).isNotNull(); assertThat(failureAnalysis.getDescription()).isEqualTo( @@ -45,7 +45,7 @@ public class HikariDriverConfigurationFailureAnalyzerTests { } @Test - public void unrelatedIllegalStateExceptionIsSkipped() { + void unrelatedIllegalStateExceptionIsSkipped() { FailureAnalysis failureAnalysis = new HikariDriverConfigurationFailureAnalyzer() .analyze(new RuntimeException("foo", new IllegalStateException("bar"))); assertThat(failureAnalysis).isNull(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java index 614d95925e1..3f5f4ad30e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java @@ -45,7 +45,7 @@ import static org.mockito.Mockito.mock; * @author Kazuki Shimizu * @author Dan Zheng */ -public class JdbcTemplateAutoConfigurationTests { +class JdbcTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.initialization-mode=never", @@ -54,7 +54,7 @@ public class JdbcTemplateAutoConfigurationTests { AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); @Test - public void testJdbcTemplateExists() { + void testJdbcTemplateExists() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); @@ -66,7 +66,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testJdbcTemplateWithCustomProperties() { + void testJdbcTemplateWithCustomProperties() { this.contextRunner.withPropertyValues("spring.jdbc.template.fetch-size:100", "spring.jdbc.template.query-timeout:60", "spring.jdbc.template.max-rows:1000").run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); @@ -79,7 +79,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testJdbcTemplateExistsWithCustomDataSource() { + void testJdbcTemplateExistsWithCustomDataSource() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); @@ -88,7 +88,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testNamedParameterJdbcTemplateExists() { + void testNamedParameterJdbcTemplateExists() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); NamedParameterJdbcTemplate namedParameterJdbcTemplate = context.getBean(NamedParameterJdbcTemplate.class); @@ -97,7 +97,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testMultiDataSource() { + void testMultiDataSource() { this.contextRunner.withUserConfiguration(MultiDataSourceConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(JdbcOperations.class); assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class); @@ -105,13 +105,13 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testMultiJdbcTemplate() { + void testMultiJdbcTemplate() { this.contextRunner.withUserConfiguration(MultiJdbcTemplateConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); } @Test - public void testMultiDataSourceUsingPrimary() { + void testMultiDataSourceUsingPrimary() { this.contextRunner.withUserConfiguration(MultiDataSourceUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); @@ -121,7 +121,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testMultiJdbcTemplateUsingPrimary() { + void testMultiJdbcTemplateUsingPrimary() { this.contextRunner.withUserConfiguration(MultiJdbcTemplateUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcTemplate.class).getJdbcOperations()) @@ -130,7 +130,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testExistingCustomJdbcTemplate() { + void testExistingCustomJdbcTemplate() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(JdbcOperations.class); assertThat(context.getBean(JdbcOperations.class)).isEqualTo(context.getBean("customJdbcOperations")); @@ -138,7 +138,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testExistingCustomNamedParameterJdbcTemplate() { + void testExistingCustomNamedParameterJdbcTemplate() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcOperations.class)) @@ -147,7 +147,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testDependencyToDataSourceInitialization() { + void testDependencyToDataSourceInitialization() { this.contextRunner.withUserConfiguration(DataSourceInitializationValidator.class) .withPropertyValues("spring.datasource.initialization-mode=always").run((context) -> { assertThat(context).hasNotFailed(); @@ -156,7 +156,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testDependencyToFlyway() { + void testDependencyToFlyway() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) .withPropertyValues("spring.flyway.locations:classpath:db/city") .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { @@ -166,7 +166,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testDependencyToFlywayWithJdbcTemplateMixed() { + void testDependencyToFlywayWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) .withPropertyValues("spring.flyway.locations:classpath:db/city") .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { @@ -177,7 +177,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testDependencyToLiquibase() { + void testDependencyToLiquibase() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { @@ -187,7 +187,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Test - public void testDependencyToLiquibaseWithJdbcTemplateMixed() { + void testDependencyToLiquibaseWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java index 7cf47d3d2f5..26ba9c978f3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class JndiDataSourceAutoConfigurationTests { +class JndiDataSourceAutoConfigurationTests { private ClassLoader threadContextClassLoader; @@ -80,7 +80,7 @@ public class JndiDataSourceAutoConfigurationTests { } @Test - public void dataSourceIsAvailableFromJndi() throws IllegalStateException, NamingException { + void dataSourceIsAvailableFromJndi() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); @@ -94,7 +94,7 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException { + void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); @@ -111,7 +111,7 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void mbeanDataSourceIsExcludedFromExportByAllExporters() throws IllegalStateException, NamingException { + void mbeanDataSourceIsExcludedFromExportByAllExporters() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); @@ -128,7 +128,7 @@ public class JndiDataSourceAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException { + void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = mock(DataSource.class); configureJndi("foo", dataSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index c57478eb382..23afb97cad6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -34,7 +34,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableMBeanExport; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link TomcatDataSourceConfiguration}. @@ -42,7 +42,7 @@ import static org.junit.Assert.fail; * @author Dave Syer * @author Stephane Nicoll */ -public class TomcatDataSourceConfigurationTests { +class TomcatDataSourceConfigurationTests { private static final String PREFIX = "spring.datasource.tomcat."; @@ -54,7 +54,7 @@ public class TomcatDataSourceConfigurationTests { } @Test - public void testDataSourceExists() { + void testDataSourceExists() { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context); this.context.refresh(); @@ -63,7 +63,7 @@ public class TomcatDataSourceConfigurationTests { } @Test - public void testDataSourcePropertiesOverridden() throws Exception { + void testDataSourcePropertiesOverridden() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", @@ -95,7 +95,7 @@ public class TomcatDataSourceConfigurationTests { } @Test - public void testDataSourceDefaultsPreserved() { + void testDataSourceDefaultsPreserved() { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues.of(PREFIX + "url:jdbc:h2:mem:testdb").applyTo(this.context); this.context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index 149656d50d7..37323084676 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -37,10 +37,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class XADataSourceAutoConfigurationTests { +class XADataSourceAutoConfigurationTests { @Test - public void wrapExistingXaDataSource() { + void wrapExistingXaDataSource() { ApplicationContext context = createContext(WrapExisting.class); context.getBean(DataSource.class); XADataSource source = context.getBean(XADataSource.class); @@ -49,7 +49,7 @@ public class XADataSourceAutoConfigurationTests { } @Test - public void createFromUrl() { + void createFromUrl() { ApplicationContext context = createContext(FromProperties.class, "spring.datasource.url:jdbc:hsqldb:mem:test", "spring.datasource.username:un"); context.getBean(DataSource.class); @@ -61,7 +61,7 @@ public class XADataSourceAutoConfigurationTests { } @Test - public void createFromClass() throws Exception { + void createFromClass() throws Exception { ApplicationContext context = createContext(FromProperties.class, "spring.datasource.xa.data-source-class-name:org.hsqldb.jdbc.pool.JDBCXADataSource", "spring.datasource.xa.properties.login-timeout:123"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java index 815705a26d3..7bef31309bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomApplicationTests.java @@ -46,13 +46,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class JerseyAutoConfigurationCustomApplicationTests { +class JerseyAutoConfigurationCustomApplicationTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/test/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java index 2573b1f4cbe..38ba5be5742 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java @@ -53,13 +53,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.jersey.type=filter", "server.servlet.context-path=/app" }) @DirtiesContext -public class JerseyAutoConfigurationCustomFilterContextPathTests { +class JerseyAutoConfigurationCustomFilterContextPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java index fbe639834e8..264447c0ba2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java @@ -52,13 +52,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext -public class JerseyAutoConfigurationCustomFilterPathTests { +class JerseyAutoConfigurationCustomFilterPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java index 4ded178348c..045f4bb5184 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomLoadOnStartupTests.java @@ -44,13 +44,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.servlet.load-on-startup=5") @DirtiesContext -public class JerseyAutoConfigurationCustomLoadOnStartupTests { +class JerseyAutoConfigurationCustomLoadOnStartupTests { @Autowired private ApplicationContext context; @Test - public void contextLoads() { + void contextLoads() { assertThat(this.context.getBean("jerseyServletRegistration")).hasFieldOrPropertyWithValue("loadOnStartup", 5); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java index c73731cc283..e1e23f002e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java @@ -53,13 +53,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jackson.default-property-inclusion=non_null") @DirtiesContext -public class JerseyAutoConfigurationCustomObjectMapperProviderTests { +class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat("{\"subject\":\"Jersey\"}").isEqualTo(response.getBody()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java index 76690556707..d7969492ba9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java @@ -52,13 +52,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.servlet.contextPath=/app") @DirtiesContext -public class JerseyAutoConfigurationCustomServletContextPathTests { +class JerseyAutoConfigurationCustomServletContextPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java index 8596eff12fd..d44065628a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java @@ -52,13 +52,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class JerseyAutoConfigurationCustomServletPathTests { +class JerseyAutoConfigurationCustomServletPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/rest/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java index 4f1bc4d7fb3..4d002111668 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java @@ -51,13 +51,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext -public class JerseyAutoConfigurationDefaultFilterPathTests { +class JerseyAutoConfigurationDefaultFilterPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java index 44d97d8dd9b..665f768db67 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java @@ -51,13 +51,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class JerseyAutoConfigurationDefaultServletPathTests { +class JerseyAutoConfigurationDefaultServletPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java index bd00603da97..dc3d1ae2ecb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java @@ -55,13 +55,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jackson.default-property-inclusion:non-null") @DirtiesContext -public class JerseyAutoConfigurationObjectMapperProviderTests { +class JerseyAutoConfigurationObjectMapperProviderTests { @Autowired private TestRestTemplate restTemplate; @Test - public void responseIsSerializedUsingAutoConfiguredObjectMapper() { + void responseIsSerializedUsingAutoConfiguredObjectMapper() { ResponseEntity response = this.restTemplate.getForEntity("/rest/message", String.class); assertThat(HttpStatus.OK).isEqualTo(response.getStatusCode()); assertThat(response.getBody()).isEqualTo("{\"subject\":\"Jersey\"}"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java index e5dead0087f..94206b4f321 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java @@ -55,10 +55,10 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext @ExtendWith(OutputCaptureExtension.class) -public class JerseyAutoConfigurationServletContainerTests { +class JerseyAutoConfigurationServletContainerTests { @Test - public void existingJerseyServletIsAmended(CapturedOutput output) { + void existingJerseyServletIsAmended(CapturedOutput output) { assertThat(output).contains("Configuring existing registration for Jersey servlet"); assertThat(output).contains("Servlet " + Application.class.getName() + " was not registered"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java index b903a229d82..01335873184 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.autoconfigure.jersey; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; import org.glassfish.jersey.server.ResourceConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class JerseyAutoConfigurationTests { +class JerseyAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)) @@ -47,7 +47,7 @@ public class JerseyAutoConfigurationTests { .withUserConfiguration(ResourceConfigConfiguration.class); @Test - public void requestContextFilterRegistrationIsAutoConfigured() { + void requestContextFilterRegistrationIsAutoConfigured() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(FilterRegistrationBean.class); FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); @@ -56,7 +56,7 @@ public class JerseyAutoConfigurationTests { } @Test - public void whenUserDefinesARequestContextFilterTheAutoConfiguredRegistrationBacksOff() { + void whenUserDefinesARequestContextFilterTheAutoConfiguredRegistrationBacksOff() { this.contextRunner.withUserConfiguration(RequestContextFilterConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(FilterRegistrationBean.class); assertThat(context).hasSingleBean(RequestContextFilter.class); @@ -64,7 +64,7 @@ public class JerseyAutoConfigurationTests { } @Test - public void whenUserDefinesARequestContextFilterRegistrationTheAutoConfiguredRegistrationBacksOff() { + void whenUserDefinesARequestContextFilterRegistrationTheAutoConfiguredRegistrationBacksOff() { this.contextRunner.withUserConfiguration(RequestContextFilterRegistrationConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(FilterRegistrationBean.class); assertThat(context).hasBean("customRequestContextFilterRegistration"); @@ -72,7 +72,7 @@ public class JerseyAutoConfigurationTests { } @Test - public void whenJaxbIsAvailableTheObjectMapperIsCustomizedWithAnAnnotationIntrospector() { + void whenJaxbIsAvailableTheObjectMapperIsCustomizedWithAnAnnotationIntrospector() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors().stream() @@ -81,7 +81,7 @@ public class JerseyAutoConfigurationTests { } @Test - public void whenJaxbIsNotAvailableTheObjectMapperCustomizationBacksOff() { + void whenJaxbIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader("javax.xml.bind.annotation")).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); @@ -91,7 +91,7 @@ public class JerseyAutoConfigurationTests { } @Test - public void whenJacksonJaxbModuleIsNotAvailableTheObjectMapperCustomizationBacksOff() { + void whenJacksonJaxbModuleIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader(JaxbAnnotationIntrospector.class)).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index fe8694a4d7c..825f31b53e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java @@ -51,13 +51,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.application-path=/api") @DirtiesContext -public class JerseyAutoConfigurationWithoutApplicationPathTests { +class JerseyAutoConfigurationWithoutApplicationPathTests { @Autowired private TestRestTemplate restTemplate; @Test - public void contextLoads() { + void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity("/api/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index 05bb5243c4d..4957242b4d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -57,7 +57,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Aurélien Leboulanger */ -public class JmsAutoConfigurationTests { +class JmsAutoConfigurationTests { private static final String ACTIVEMQ_EMBEDDED_URL = "vm://localhost?broker.persistent=false"; @@ -67,7 +67,7 @@ public class JmsAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test - public void testDefaultJmsConfiguration() { + void testDefaultJmsConfiguration() { this.contextRunner.withUserConfiguration(TestConfiguration.class).run(this::testDefaultJmsConfiguration); } @@ -85,27 +85,27 @@ public class JmsAutoConfigurationTests { } @Test - public void testConnectionFactoryBackOff() { + void testConnectionFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration2.class) .run((context) -> assertThat(context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) .isEqualTo("foobar")); } @Test - public void testJmsTemplateBackOff() { + void testJmsTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration3.class) .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); } @Test - public void testJmsMessagingTemplateBackOff() { + void testJmsMessagingTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class) .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) .isEqualTo("fooBar")); } @Test - public void testJmsTemplateBackOffEverything() { + void testJmsTemplateBackOffEverything() { this.contextRunner .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) .run(this::testJmsTemplateBackOffEverything); @@ -121,7 +121,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testEnableJmsCreateDefaultContainerFactory() { + void testEnableJmsCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) .run((context) -> assertThat(context) .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) @@ -129,7 +129,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testJmsListenerContainerFactoryBackOff() { + void testJmsListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration6.class, EnableJmsConfiguration.class) .run((context) -> assertThat(context) .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) @@ -137,13 +137,13 @@ public class JmsAutoConfigurationTests { } @Test - public void jmsListenerContainerFactoryWhenMultipleConnectionFactoryBeansShouldBackOff() { + void jmsListenerContainerFactoryWhenMultipleConnectionFactoryBeansShouldBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration10.class) .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); } @Test - public void testJmsListenerContainerFactoryWithCustomSettings() { + void testJmsListenerContainerFactoryWithCustomSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) .withPropertyValues("spring.jms.listener.autoStartup=false", "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", @@ -160,7 +160,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testDefaultContainerFactoryWithJtaTransactionManager() { + void testDefaultContainerFactoryWithJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration7.class, EnableJmsConfiguration.class) .run((context) -> { DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); @@ -171,7 +171,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testDefaultContainerFactoryNonJtaTransactionManager() { + void testDefaultContainerFactoryNonJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration8.class, EnableJmsConfiguration.class) .run((context) -> { DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); @@ -181,7 +181,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testDefaultContainerFactoryNoTransactionManager() { + void testDefaultContainerFactoryNoTransactionManager() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class).run((context) -> { DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); assertThat(container.isSessionTransacted()).isTrue(); @@ -190,7 +190,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testDefaultContainerFactoryWithMessageConverters() { + void testDefaultContainerFactoryWithMessageConverters() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, EnableJmsConfiguration.class) .run((context) -> { DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); @@ -199,7 +199,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testCustomContainerFactoryWithConfigurer() { + void testCustomContainerFactoryWithConfigurer() { this.contextRunner.withUserConfiguration(TestConfiguration9.class, EnableJmsConfiguration.class) .withPropertyValues("spring.jms.listener.autoStartup=false").run((context) -> { DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); @@ -215,7 +215,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testJmsTemplateWithMessageConverter() { + void testJmsTemplateWithMessageConverter() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class).run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); @@ -223,14 +223,14 @@ public class JmsAutoConfigurationTests { } @Test - public void testJmsTemplateWithDestinationResolver() { + void testJmsTemplateWithDestinationResolver() { this.contextRunner.withUserConfiguration(DestinationResolversConfiguration.class) .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) .isSameAs(context.getBean("myDestinationResolver"))); } @Test - public void testJmsTemplateFullCustomization() { + void testJmsTemplateFullCustomization() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) .withPropertyValues("spring.jms.template.default-destination=testQueue", "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", @@ -251,7 +251,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testJmsMessagingTemplateUseConfiguredDefaultDestination() { + void testJmsMessagingTemplateUseConfiguredDefaultDestination() { this.contextRunner.withPropertyValues("spring.jms.template.default-destination=testQueue").run((context) -> { JmsMessagingTemplate messagingTemplate = context.getBean(JmsMessagingTemplate.class); assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); @@ -259,19 +259,19 @@ public class JmsAutoConfigurationTests { } @Test - public void testPubSubDisabledByDefault() { + void testPubSubDisabledByDefault() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); } @Test - public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { + void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { this.contextRunner.withUserConfiguration(TestConfiguration4.class) .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); } @Test - public void testPubSubDomainActive() { + void testPubSubDomainActive() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.jms.pubSubDomain:true").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); @@ -284,7 +284,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testPubSubDomainOverride() { + void testPubSubDomainOverride() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.jms.pubSubDomain:false").run((context) -> { assertThat(context).hasSingleBean(JmsTemplate.class); @@ -298,7 +298,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testActiveMQOverriddenStandalone() { + void testActiveMQOverriddenStandalone() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.inMemory:false").run((context) -> { assertThat(context).hasSingleBean(JmsTemplate.class); @@ -311,7 +311,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testActiveMQOverriddenRemoteHost() { + void testActiveMQOverriddenRemoteHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000").run((context) -> { assertThat(context).hasSingleBean(JmsTemplate.class); @@ -329,7 +329,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testActiveMQOverriddenPool() { + void testActiveMQOverriddenPool() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); @@ -343,7 +343,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testActiveMQOverriddenPoolAndStandalone() { + void testActiveMQOverriddenPoolAndStandalone() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false") .run((context) -> { @@ -358,7 +358,7 @@ public class JmsAutoConfigurationTests { } @Test - public void testActiveMQOverriddenPoolAndRemoteServer() { + void testActiveMQOverriddenPoolAndRemoteServer() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.brokerUrl:tcp://remote-host:10000") @@ -374,7 +374,7 @@ public class JmsAutoConfigurationTests { } @Test - public void enableJmsAutomatically() { + void enableJmsAutomatically() { this.contextRunner.withUserConfiguration(NoEnableJmsConfiguration.class) .run((context) -> assertThat(context) .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java index d063298d6ed..ae4d4ac54be 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java @@ -27,30 +27,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class JmsPropertiesTests { +class JmsPropertiesTests { @Test - public void formatConcurrencyNull() { + void formatConcurrencyNull() { JmsProperties properties = new JmsProperties(); assertThat(properties.getListener().formatConcurrency()).isNull(); } @Test - public void formatConcurrencyOnlyLowerBound() { + void formatConcurrencyOnlyLowerBound() { JmsProperties properties = new JmsProperties(); properties.getListener().setConcurrency(2); assertThat(properties.getListener().formatConcurrency()).isEqualTo("2"); } @Test - public void formatConcurrencyOnlyHigherBound() { + void formatConcurrencyOnlyHigherBound() { JmsProperties properties = new JmsProperties(); properties.getListener().setMaxConcurrency(5); assertThat(properties.getListener().formatConcurrency()).isEqualTo("1-5"); } @Test - public void formatConcurrencyBothBounds() { + void formatConcurrencyBothBounds() { JmsProperties properties = new JmsProperties(); properties.getListener().setConcurrency(2); properties.getListener().setMaxConcurrency(10); @@ -58,21 +58,21 @@ public class JmsPropertiesTests { } @Test - public void setDeliveryModeEnablesQoS() { + void setDeliveryModeEnablesQoS() { JmsProperties properties = new JmsProperties(); properties.getTemplate().setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT); assertThat(properties.getTemplate().determineQosEnabled()).isTrue(); } @Test - public void setPriorityEnablesQoS() { + void setPriorityEnablesQoS() { JmsProperties properties = new JmsProperties(); properties.getTemplate().setPriority(6); assertThat(properties.getTemplate().determineQosEnabled()).isTrue(); } @Test - public void setTimeToLiveEnablesQoS() { + void setTimeToLiveEnablesQoS() { JmsProperties properties = new JmsProperties(); properties.getTemplate().setTimeToLive(Duration.ofSeconds(5)); assertThat(properties.getTemplate().determineQosEnabled()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java index 9495746e9da..2ccfcd82d44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java @@ -40,7 +40,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class JndiConnectionFactoryAutoConfigurationTests { +class JndiConnectionFactoryAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); @@ -70,38 +70,38 @@ public class JndiConnectionFactoryAutoConfigurationTests { } @Test - public void detectNoAvailableCandidates() { + void detectNoAvailableCandidates() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactory.class)); } @Test - public void detectWithJmsXAConnectionFactory() { + void detectWithJmsXAConnectionFactory() { ConnectionFactory connectionFactory = configureConnectionFactory("java:/JmsXA"); this.contextRunner.run(assertConnectionFactory(connectionFactory)); } @Test - public void detectWithXAConnectionFactory() { + void detectWithXAConnectionFactory() { ConnectionFactory connectionFactory = configureConnectionFactory("java:/XAConnectionFactory"); this.contextRunner.run(assertConnectionFactory(connectionFactory)); } @Test - public void jndiNamePropertySet() { + void jndiNamePropertySet() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=java:comp/env/myCF") .run(assertConnectionFactory(connectionFactory)); } @Test - public void jndiNamePropertySetWithResourceRef() { + void jndiNamePropertySetWithResourceRef() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=myCF") .run(assertConnectionFactory(connectionFactory)); } @Test - public void jndiNamePropertySetWithWrongValue() { + void jndiNamePropertySetWithWrongValue() { this.contextRunner.withPropertyValues("spring.jms.jndi-name=doesNotExistCF").run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index 40d176a9891..437f56dc999 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -41,13 +41,13 @@ import static org.mockito.Mockito.mockingDetails; * @author Aurélien Leboulanger * @author Stephane Nicoll */ -public class ActiveMQAutoConfigurationTests { +class ActiveMQAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class)); @Test - public void brokerIsEmbeddedByDefault() { + void brokerIsEmbeddedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CachingConnectionFactory.class); CachingConnectionFactory cachingConnectionFactory = context.getBean(CachingConnectionFactory.class); @@ -60,13 +60,13 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void configurationBacksOffWhenCustomConnectionFactoryExists() { + void configurationBacksOffWhenCustomConnectionFactoryExists() { this.contextRunner.withUserConfiguration(CustomConnectionFactoryConfiguration.class).run( (context) -> assertThat(mockingDetails(context.getBean(ConnectionFactory.class)).isMock()).isTrue()); } @Test - public void connectionFactoryIsCachedByDefault() { + void connectionFactoryIsCachedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); assertThat(context).hasSingleBean(CachingConnectionFactory.class); @@ -79,7 +79,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void connectionFactoryCachingCanBeCustomized() { + void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", "spring.jms.cache.session-cache-size=10") @@ -94,7 +94,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void connectionFactoryCachingCanBeDisabled() { + void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)).hasSize(1); @@ -114,7 +114,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void customConnectionFactoryIsApplied() { + void customConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.enabled=false", "spring.activemq.brokerUrl=vm://localhost?useJmx=false&broker.persistent=false", @@ -135,7 +135,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void defaultPoolConnectionFactoryIsApplied() { + void defaultPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled=true").run((context) -> { assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); @@ -158,7 +158,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void customPoolConnectionFactoryIsApplied() { + void customPoolConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled=true", "spring.activemq.pool.blockIfFull=false", "spring.activemq.pool.blockIfFullTimeout=64", "spring.activemq.pool.idleTimeout=512", @@ -179,7 +179,7 @@ public class ActiveMQAutoConfigurationTests { } @Test - public void poolConnectionFactoryConfiguration() { + void poolConnectionFactoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled:true").run((context) -> { ConnectionFactory factory = context.getBean(ConnectionFactory.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java index ad70a16729a..14b714070cb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Aurélien Leboulanger * @author Venil Noronha */ -public class ActiveMQPropertiesTests { +class ActiveMQPropertiesTests { private static final String DEFAULT_EMBEDDED_BROKER_URL = "vm://localhost?broker.persistent=false"; @@ -39,38 +39,38 @@ public class ActiveMQPropertiesTests { private final ActiveMQProperties properties = new ActiveMQProperties(); @Test - public void getBrokerUrlIsInMemoryByDefault() { + void getBrokerUrlIsInMemoryByDefault() { assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); } @Test - public void getBrokerUrlUseExplicitBrokerUrl() { + void getBrokerUrlUseExplicitBrokerUrl() { this.properties.setBrokerUrl("vm://foo-bar"); assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test - public void getBrokerUrlWithInMemorySetToFalse() { + void getBrokerUrlWithInMemorySetToFalse() { this.properties.setInMemory(false); assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo(DEFAULT_NETWORK_BROKER_URL); } @Test - public void getExplicitBrokerUrlAlwaysWins() { + void getExplicitBrokerUrlAlwaysWins() { this.properties.setBrokerUrl("vm://foo-bar"); this.properties.setInMemory(false); assertThat(createFactory(this.properties).determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test - public void setTrustAllPackages() { + void setTrustAllPackages() { this.properties.getPackages().setTrustAll(true); assertThat(createFactory(this.properties).createConnectionFactory(ActiveMQConnectionFactory.class) .isTrustAllPackages()).isTrue(); } @Test - public void setTrustedPackages() { + void setTrustedPackages() { this.properties.getPackages().setTrustAll(false); this.properties.getPackages().getTrusted().add("trusted.package"); ActiveMQConnectionFactory factory = createFactory(this.properties) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 82c85664484..77c15dcf5de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -63,13 +63,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class ArtemisAutoConfigurationTests { +class ArtemisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test - public void connectionFactoryIsCachedByDefault() { + void connectionFactoryIsCachedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); assertThat(context).hasSingleBean(CachingConnectionFactory.class); @@ -82,7 +82,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void connectionFactoryCachingCanBeCustomized() { + void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", "spring.jms.cache.session-cache-size=10") @@ -97,7 +97,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void connectionFactoryCachingCanBeDisabled() { + void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class); @@ -107,7 +107,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void nativeConnectionFactory() { + void nativeConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:native").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); @@ -122,7 +122,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void nativeConnectionFactoryCustomHost() { + void nativeConnectionFactoryCustomHost() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:native", "spring.artemis.host:192.168.1.144", "spring.artemis.port:9876") @@ -131,7 +131,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void nativeConnectionFactoryCredentials() { + void nativeConnectionFactoryCredentials() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", "spring.artemis.password:secret") @@ -148,7 +148,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedConnectionFactory() { + void embeddedConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:embedded").run((context) -> { ArtemisProperties properties = context.getBean(ArtemisProperties.class); @@ -163,7 +163,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedConnectionFactoryByDefault() { + void embeddedConnectionFactoryByDefault() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(EmbeddedJMS.class); @@ -176,7 +176,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { + void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.embedded.enabled:false").run((context) -> { @@ -187,7 +187,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { + void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") @@ -198,7 +198,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedServerWithDestinations() { + void embeddedServerWithDestinations() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", "spring.artemis.embedded.topics=Topic1") @@ -213,7 +213,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedServerWithDestinationConfig() { + void embeddedServerWithDestinationConfig() { this.contextRunner.withUserConfiguration(DestinationConfiguration.class).run((context) -> { DestinationChecker checker = new DestinationChecker(context); checker.checkQueue("sampleQueue", true); @@ -222,7 +222,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedServiceWithCustomJmsConfiguration() { + void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config this.contextRunner.withUserConfiguration(CustomJmsConfiguration.class) .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2").run((context) -> { @@ -234,7 +234,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedServiceWithCustomArtemisConfiguration() { + void embeddedServiceWithCustomArtemisConfiguration() { this.contextRunner.withUserConfiguration(CustomArtemisConfiguration.class) .run((context) -> assertThat( context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) @@ -242,7 +242,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void embeddedWithPersistentMode(@TempDir Path temp) throws IOException { + void embeddedWithPersistentMode(@TempDir Path temp) throws IOException { File dataFolder = Files.createTempDirectory(temp, null).toFile(); final String messageId = UUID.randomUUID().toString(); // Start the server and post a message to some queue @@ -263,7 +263,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void severalEmbeddedBrokers() { + void severalEmbeddedBrokers() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.embedded.queues=Queue1").run((first) -> { this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { @@ -282,7 +282,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void connectToASpecificEmbeddedBroker() { + void connectToASpecificEmbeddedBroker() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") .run((first) -> { @@ -302,7 +302,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void defaultPoolConnectionFactoryIsApplied() { + void defaultPoolConnectionFactoryIsApplied() { this.contextRunner.withPropertyValues("spring.artemis.pool.enabled=true").run((context) -> { assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); @@ -323,7 +323,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void customPoolConnectionFactoryIsApplied() { + void customPoolConnectionFactoryIsApplied() { this.contextRunner .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", @@ -344,7 +344,7 @@ public class ArtemisAutoConfigurationTests { } @Test - public void poolConnectionFactoryConfiguration() { + void poolConnectionFactoryConfiguration() { this.contextRunner.withPropertyValues("spring.artemis.pool.enabled:true").run((context) -> { ConnectionFactory factory = context.getBean(ConnectionFactory.class); assertThat(factory).isInstanceOf(JmsPoolConnectionFactory.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index 7c79510e803..0144ee3ae08 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Phillip Webb */ -public class ArtemisEmbeddedConfigurationFactoryTests { +class ArtemisEmbeddedConfigurationFactoryTests { @Test - public void defaultDataDir() { + void defaultDataDir() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); @@ -47,7 +47,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { } @Test - public void persistenceSetup() { + void persistenceSetup() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); @@ -56,14 +56,14 @@ public class ArtemisEmbeddedConfigurationFactoryTests { } @Test - public void generatedClusterPassword() { + void generatedClusterPassword() { ArtemisProperties properties = new ArtemisProperties(); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getClusterPassword().length()).isEqualTo(36); } @Test - public void specificClusterPassword() { + void specificClusterPassword() { ArtemisProperties properties = new ArtemisProperties(); properties.getEmbedded().setClusterPassword("password"); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); @@ -71,7 +71,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { } @Test - public void hasDlqExpiryQueueAddressSettingsConfigured() { + void hasDlqExpiryQueueAddressSettingsConfigured() { ArtemisProperties properties = new ArtemisProperties(); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); Map addressesSettings = configuration.getAddressesSettings(); @@ -82,7 +82,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { } @Test - public void hasDlqExpiryQueueConfigured() { + void hasDlqExpiryQueueConfigured() { ArtemisProperties properties = new ArtemisProperties(); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); List addressConfigurations = configuration.getAddressConfigurations(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index a6a7e35f85b..75d60c92d26 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Christian Dupuis * @author Artsiom Yudovin */ -public class JmxAutoConfigurationTests { +class JmxAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -59,7 +59,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testDefaultMBeanExport() { + void testDefaultMBeanExport() { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class); this.context.refresh(); @@ -68,7 +68,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testEnabledMBeanExport() { + void testEnabledMBeanExport() { MockEnvironment env = new MockEnvironment(); env.setProperty("spring.jmx.enabled", "true"); this.context = new AnnotationConfigApplicationContext(); @@ -79,7 +79,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testDisabledMBeanExport() { + void testDisabledMBeanExport() { MockEnvironment env = new MockEnvironment(); env.setProperty("spring.jmx.enabled", "false"); this.context = new AnnotationConfigApplicationContext(); @@ -91,7 +91,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testDefaultDomainConfiguredOnMBeanExport() { + void testDefaultDomainConfiguredOnMBeanExport() { MockEnvironment env = new MockEnvironment(); env.setProperty("spring.jmx.enabled", "true"); env.setProperty("spring.jmx.default-domain", "my-test-domain"); @@ -109,7 +109,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testBasicParentContext() { + void testBasicParentContext() { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class); this.context.refresh(); @@ -121,7 +121,7 @@ public class JmxAutoConfigurationTests { } @Test - public void testParentContext() { + void testParentContext() { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class, TestConfiguration.class); this.context.refresh(); @@ -133,7 +133,7 @@ public class JmxAutoConfigurationTests { } @Test - public void customJmxDomain() { + void customJmxDomain() { this.context = new AnnotationConfigApplicationContext(); this.context.register(CustomJmxDomainConfiguration.class, JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 4916260f6d4..871e04385ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -63,19 +63,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Stephane Nicoll * @author Dmytro Nosan */ -public class JooqAutoConfigurationTests { +class JooqAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) .withPropertyValues("spring.datasource.name:jooqtest"); @Test - public void noDataSource() { + void noDataSource() { this.contextRunner.run((context) -> assertThat(context.getBeansOfType(DSLContext.class)).isEmpty()); } @Test - public void jooqWithoutTx() { + void jooqWithoutTx() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(PlatformTransactionManager.class); assertThat(context).doesNotHaveBean(SpringTransactionProvider.class); @@ -92,7 +92,7 @@ public class JooqAutoConfigurationTests { } @Test - public void jooqWithTx() { + void jooqWithTx() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(PlatformTransactionManager.class); @@ -111,7 +111,7 @@ public class JooqAutoConfigurationTests { } @Test - public void customProvidersArePickedUp() { + void customProvidersArePickedUp() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, TestRecordMapperProvider.class, TestRecordUnmapperProvider.class, TestRecordListenerProvider.class, TestExecuteListenerProvider.class, TestVisitListenerProvider.class, @@ -133,7 +133,7 @@ public class JooqAutoConfigurationTests { } @Test - public void relaxedBindingOfSqlDialect() { + void relaxedBindingOfSqlDialect() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java index 5974c44a9eb..65d474040dd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqExceptionTranslatorTests.java @@ -21,10 +21,8 @@ import java.sql.SQLException; import org.jooq.Configuration; import org.jooq.ExecuteContext; import org.jooq.SQLDialect; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.springframework.jdbc.BadSqlGrammarException; @@ -39,17 +37,25 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class JooqExceptionTranslatorTests { +class JooqExceptionTranslatorTests { private final JooqExceptionTranslator exceptionTranslator = new JooqExceptionTranslator(); - private final SQLDialect dialect; + @ParameterizedTest(name = "{0}") + @MethodSource + void exceptionTranslation(SQLDialect dialect, SQLException sqlException) { + ExecuteContext context = mock(ExecuteContext.class); + Configuration configuration = mock(Configuration.class); + given(context.configuration()).willReturn(configuration); + given(configuration.dialect()).willReturn(dialect); + given(context.sqlException()).willReturn(sqlException); + this.exceptionTranslator.exception(context); + ArgumentCaptor captor = ArgumentCaptor.forClass(RuntimeException.class); + verify(context).exception(captor.capture()); + assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class); + } - private final SQLException sqlException; - - @Parameters(name = "{0}") - public static Object[] parameters() { + static Object[] exceptionTranslation() { return new Object[] { new Object[] { SQLDialect.DERBY, sqlException("42802") }, new Object[] { SQLDialect.H2, sqlException(42000) }, new Object[] { SQLDialect.HSQLDB, sqlException(-22) }, @@ -71,22 +77,4 @@ public class JooqExceptionTranslatorTests { } - public JooqExceptionTranslatorTests(SQLDialect dialect, SQLException sqlException) { - this.dialect = dialect; - this.sqlException = sqlException; - } - - @Test - public void exceptionTranslation() { - ExecuteContext context = mock(ExecuteContext.class); - Configuration configuration = mock(Configuration.class); - given(context.configuration()).willReturn(configuration); - given(configuration.dialect()).willReturn(this.dialect); - given(context.sqlException()).willReturn(this.sqlException); - this.exceptionTranslator.exception(context); - ArgumentCaptor captor = ArgumentCaptor.forClass(RuntimeException.class); - verify(context).exception(captor.capture()); - assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class); - } - } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java index f5b866dbd89..1419cb5cca1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqPropertiesTests.java @@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class JooqPropertiesTests { +class JooqPropertiesTests { private AnnotationConfigApplicationContext context; @@ -54,7 +54,7 @@ public class JooqPropertiesTests { } @Test - public void determineSqlDialectNoCheckIfDialectIsSet() throws SQLException { + void determineSqlDialectNoCheckIfDialectIsSet() throws SQLException { JooqProperties properties = load("spring.jooq.sql-dialect=postgres"); DataSource dataSource = mockStandaloneDataSource(); SQLDialect sqlDialect = properties.determineSqlDialect(dataSource); @@ -63,21 +63,21 @@ public class JooqPropertiesTests { } @Test - public void determineSqlDialectWithKnownUrl() { + void determineSqlDialectWithKnownUrl() { JooqProperties properties = load(); SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); assertThat(sqlDialect).isEqualTo(SQLDialect.H2); } @Test - public void determineSqlDialectWithKnownUrlAndUserConfig() { + void determineSqlDialectWithKnownUrlAndUserConfig() { JooqProperties properties = load("spring.jooq.sql-dialect=mysql"); SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:h2:mem:testdb")); assertThat(sqlDialect).isEqualTo(SQLDialect.MYSQL); } @Test - public void determineSqlDialectWithUnknownUrl() { + void determineSqlDialectWithUnknownUrl() { JooqProperties properties = load(); SQLDialect sqlDialect = properties.determineSqlDialect(mockDataSource("jdbc:unknown://localhost")); assertThat(sqlDialect).isEqualTo(SQLDialect.DEFAULT); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java index afcc9cb6a01..743bb80a2f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/SqlDialectLookupTests.java @@ -34,60 +34,60 @@ import static org.mockito.Mockito.mock; * @author Michael Simons * @author Stephane Nicoll */ -public class SqlDialectLookupTests { +class SqlDialectLookupTests { @Test - public void getSqlDialectWhenDataSourceIsNullShouldReturnDefault() { + void getSqlDialectWhenDataSourceIsNullShouldReturnDefault() { assertThat(SqlDialectLookup.getDialect(null)).isEqualTo(SQLDialect.DEFAULT); } @Test - public void getSqlDialectWhenDataSourceIsUnknownShouldReturnDefault() throws Exception { + void getSqlDialectWhenDataSourceIsUnknownShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:idontexist:", SQLDialect.DEFAULT); } @Test - public void getSqlDialectWhenDerbyShouldReturnDerby() throws Exception { + void getSqlDialectWhenDerbyShouldReturnDerby() throws Exception { testGetSqlDialect("jdbc:derby:", SQLDialect.DERBY); } @Test - public void getSqlDialectWhenH2ShouldReturnH2() throws Exception { + void getSqlDialectWhenH2ShouldReturnH2() throws Exception { testGetSqlDialect("jdbc:h2:", SQLDialect.H2); } @Test - public void getSqlDialectWhenHsqldbShouldReturnHsqldb() throws Exception { + void getSqlDialectWhenHsqldbShouldReturnHsqldb() throws Exception { testGetSqlDialect("jdbc:hsqldb:", SQLDialect.HSQLDB); } @Test - public void getSqlDialectWhenMysqlShouldReturnMysql() throws Exception { + void getSqlDialectWhenMysqlShouldReturnMysql() throws Exception { testGetSqlDialect("jdbc:mysql:", SQLDialect.MYSQL); } @Test - public void getSqlDialectWhenOracleShouldReturnDefault() throws Exception { + void getSqlDialectWhenOracleShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:oracle:", SQLDialect.DEFAULT); } @Test - public void getSqlDialectWhenPostgresShouldReturnPostgres() throws Exception { + void getSqlDialectWhenPostgresShouldReturnPostgres() throws Exception { testGetSqlDialect("jdbc:postgresql:", SQLDialect.POSTGRES); } @Test - public void getSqlDialectWhenSqlserverShouldReturnDefault() throws Exception { + void getSqlDialectWhenSqlserverShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:sqlserver:", SQLDialect.DEFAULT); } @Test - public void getSqlDialectWhenDb2ShouldReturnDefault() throws Exception { + void getSqlDialectWhenDb2ShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:db2:", SQLDialect.DEFAULT); } @Test - public void getSqlDialectWhenInformixShouldReturnDefault() throws Exception { + void getSqlDialectWhenInformixShouldReturnDefault() throws Exception { testGetSqlDialect("jdbc:informix-sqli:", SQLDialect.DEFAULT); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java index 9904a354dee..cf17fc37dbb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -public class JsonbAutoConfigurationTests { +class JsonbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test - public void jsonbRegistration() { + void jsonbRegistration() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Jsonb.class); Jsonb jsonb = context.getBean(Jsonb.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java index 26325c2e719..91729fbdee0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Gary Russell * @author Stephane Nicoll */ -public class KafkaAutoConfigurationIntegrationTests { +class KafkaAutoConfigurationIntegrationTests { private static final String TEST_TOPIC = "testTopic"; @@ -76,7 +76,7 @@ public class KafkaAutoConfigurationIntegrationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) @Test - public void testEndToEnd() throws Exception { + void testEndToEnd() throws Exception { load(KafkaConfig.class, "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString(), "spring.kafka.consumer.group-id=testGroup", "spring.kafka.consumer.auto-offset-reset=earliest"); KafkaTemplate template = this.context.getBean(KafkaTemplate.class); @@ -93,7 +93,7 @@ public class KafkaAutoConfigurationIntegrationTests { } @Test - public void testStreams() { + void testStreams() { load(KafkaStreamsConfig.class, "spring.application.name:my-app", "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString()); assertThat(this.context.getBean(StreamsBuilderFactoryBean.class).isAutoStartup()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java index e9974b0ae66..36f84c9d105 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java @@ -85,13 +85,13 @@ import static org.mockito.Mockito.verify; * @author Eddú Meléndez * @author Nakul Mishra */ -public class KafkaAutoConfigurationTests { +class KafkaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)); @Test - public void consumerProperties() { + void consumerProperties() { this.contextRunner.withPropertyValues("spring.kafka.bootstrap-servers=foo:1234", "spring.kafka.properties.foo=bar", "spring.kafka.properties.baz=qux", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.ssl.key-password=p1", @@ -145,7 +145,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void producerProperties() { + void producerProperties() { this.contextRunner.withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.producer.acks=all", "spring.kafka.producer.batch-size=2KB", "spring.kafka.producer.bootstrap-servers=bar:1234", // test @@ -195,7 +195,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void adminProperties() { + void adminProperties() { this.contextRunner .withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.admin.fail-fast=true", "spring.kafka.admin.properties.fiz.buz=fix.fox", @@ -230,7 +230,7 @@ public class KafkaAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void streamsProperties() { + void streamsProperties() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).withPropertyValues( "spring.kafka.client-id=cid", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.application.name=appName", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", @@ -273,7 +273,7 @@ public class KafkaAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void streamsApplicationIdUsesMainApplicationNameByDefault() { + void streamsApplicationIdUsesMainApplicationNameByDefault() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) .withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", @@ -290,7 +290,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void streamsWithCustomKafkaConfiguration() { + void streamsWithCustomKafkaConfiguration() { this.contextRunner .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) .withPropertyValues("spring.application.name=my-test-app", @@ -309,7 +309,7 @@ public class KafkaAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void streamsWithSeveralStreamsBuilderFactoryBeans() { + void streamsWithSeveralStreamsBuilderFactoryBeans() { this.contextRunner .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestStreamsBuilderFactoryBeanConfiguration.class) @@ -331,7 +331,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void streamsApplicationIdIsMandatory() { + void streamsApplicationIdIsMandatory() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasMessageContaining("spring.kafka.streams.application-id") @@ -342,7 +342,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void streamsApplicationIdIsNotMandatoryIfEnableKafkaStreamsIsNotSet() { + void streamsApplicationIdIsNotMandatoryIfEnableKafkaStreamsIsNotSet() { this.contextRunner.run((context) -> { assertThat(context).hasNotFailed(); assertThat(context).doesNotHaveBean(StreamsBuilder.class); @@ -351,7 +351,7 @@ public class KafkaAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void listenerProperties() { + void listenerProperties() { this.contextRunner .withPropertyValues("spring.kafka.template.default-topic=testTopic", "spring.kafka.listener.ack-mode=MANUAL", "spring.kafka.listener.client-id=client", @@ -400,7 +400,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void listenerPropertiesMatchDefaults() { + void listenerPropertiesMatchDefaults() { this.contextRunner.run((context) -> { Listener listenerProperties = new KafkaProperties().getListener(); AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context @@ -411,7 +411,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testKafkaTemplateRecordMessageConverters() { + void testKafkaTemplateRecordMessageConverters() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); @@ -420,7 +420,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverter() { + void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -430,7 +430,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryInBatchModeWithCustomMessageConverter() { + void testConcurrentKafkaListenerContainerFactoryInBatchModeWithCustomMessageConverter() { this.contextRunner .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { @@ -442,7 +442,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryInBatchModeWrapsCustomMessageConverter() { + void testConcurrentKafkaListenerContainerFactoryInBatchModeWrapsCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context @@ -456,7 +456,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryInBatchModeWithNoMessageConverter() { + void testConcurrentKafkaListenerContainerFactoryInBatchModeWithNoMessageConverter() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -467,7 +467,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithCustomErrorHandler() { + void testConcurrentKafkaListenerContainerFactoryWithCustomErrorHandler() { this.contextRunner.withUserConfiguration(ErrorHandlerConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -476,7 +476,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void concurrentKafkaListenerContainerFactoryInBatchModeShouldUseBatchErrorHandler() { + void concurrentKafkaListenerContainerFactoryInBatchModeShouldUseBatchErrorHandler() { this.contextRunner.withUserConfiguration(BatchErrorHandlerConfiguration.class) .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context @@ -487,7 +487,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void concurrentKafkaListenerContainerFactoryInBatchModeWhenBatchErrorHandlerNotAvailableShouldBeNull() { + void concurrentKafkaListenerContainerFactoryInBatchModeWhenBatchErrorHandlerNotAvailableShouldBeNull() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -496,7 +496,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void concurrentKafkaListenerContainerFactoryInBatchModeAndSimpleErrorHandlerShouldBeNull() { + void concurrentKafkaListenerContainerFactoryInBatchModeAndSimpleErrorHandlerShouldBeNull() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch") .withUserConfiguration(ErrorHandlerConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context @@ -506,7 +506,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithDefaultTransactionManager() { + void testConcurrentKafkaListenerContainerFactoryWithDefaultTransactionManager() { this.contextRunner.withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { assertThat(context).hasSingleBean(KafkaAwareTransactionManager.class); ConcurrentKafkaListenerContainerFactory factory = context @@ -517,7 +517,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithCustomTransactionManager() { + void testConcurrentKafkaListenerContainerFactoryWithCustomTransactionManager() { this.contextRunner.withUserConfiguration(TransactionManagerConfiguration.class) .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context @@ -528,7 +528,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithCustomAfterRollbackProcessor() { + void testConcurrentKafkaListenerContainerFactoryWithCustomAfterRollbackProcessor() { this.contextRunner.withUserConfiguration(AfterRollbackProcessorConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -538,7 +538,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithCustomRebalanceListener() { + void testConcurrentKafkaListenerContainerFactoryWithCustomRebalanceListener() { this.contextRunner.withUserConfiguration(RebalanceListenerConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); @@ -548,7 +548,7 @@ public class KafkaAutoConfigurationTests { } @Test - public void testConcurrentKafkaListenerContainerFactoryWithKafkaTemplate() { + void testConcurrentKafkaListenerContainerFactoryWithKafkaTemplate() { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index 16df62e88d0..d0d7559b149 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Vedran Pavic */ -public class LdapAutoConfigurationTests { +class LdapAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)); @Test - public void contextSourceWithDefaultUrl() { + void contextSourceWithDefaultUrl() { this.contextRunner.run((context) -> { LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:389"); @@ -52,7 +52,7 @@ public class LdapAutoConfigurationTests { } @Test - public void contextSourceWithSingleUrl() { + void contextSourceWithSingleUrl() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123").run((context) -> { LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123"); @@ -60,7 +60,7 @@ public class LdapAutoConfigurationTests { } @Test - public void contextSourceWithSeveralUrls() { + void contextSourceWithSeveralUrls() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123,ldap://mycompany:123") .run((context) -> { LdapContextSource contextSource = context.getBean(LdapContextSource.class); @@ -71,7 +71,7 @@ public class LdapAutoConfigurationTests { } @Test - public void contextSourceWithExtraCustomization() { + void contextSourceWithExtraCustomization() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", "spring.ldap.base:cn=SpringDevelopers", @@ -88,13 +88,13 @@ public class LdapAutoConfigurationTests { } @Test - public void templateExists() { + void templateExists() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:389") .run((context) -> assertThat(context).hasSingleBean(LdapTemplate.class)); } @Test - public void contextSourceWithUserProvidedPooledContextSource() { + void contextSourceWithUserProvidedPooledContextSource() { this.contextRunner.withUserConfiguration(PooledContextSourceConfig.class).run((context) -> { LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:389"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java index 292f17df6be..12c272afc70 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java @@ -41,13 +41,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -public class EmbeddedLdapAutoConfigurationTests { +class EmbeddedLdapAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); @Test - public void testSetDefaultPort() { + void testSetDefaultPort() { this.contextRunner .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") .run((context) -> { @@ -57,7 +57,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testRandomPortWithEnvironment() { + void testRandomPortWithEnvironment() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getListenPort()) @@ -66,7 +66,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testRandomPortWithValueAnnotation() { + void testRandomPortWithValueAnnotation() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.ldap.embedded.base-dn:dc=spring,dc=org").applyTo(context); context.register(EmbeddedLdapAutoConfiguration.class, LdapClientConfiguration.class, @@ -78,7 +78,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testSetCredentials() { + void testSetCredentials() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") .run((context) -> { @@ -89,7 +89,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testSetPartitionSuffix() { + void testSetPartitionSuffix() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getBaseDNs()).containsExactly(new DN("dc=spring,dc=org")); @@ -97,7 +97,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testSetLdifFile() { + void testSetLdifFile() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); @@ -105,7 +105,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testQueryEmbeddedLdap() { + void testQueryEmbeddedLdap() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)).run((context) -> { assertThat(context.getBeanNamesForType(LdapTemplate.class).length).isEqualTo(1); @@ -115,7 +115,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testDisableSchemaValidation() { + void testDisableSchemaValidation() { this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.enabled:false", "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); @@ -124,7 +124,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testCustomSchemaValidation() { + void testCustomSchemaValidation() { this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { @@ -136,7 +136,7 @@ public class EmbeddedLdapAutoConfigurationTests { } @Test - public void testMultiBaseDn() { + void testMultiBaseDn() { this.contextRunner.withPropertyValues("spring.ldap.embedded.ldif:classpath:schema-multi-basedn.ldif", "spring.ldap.embedded.base-dn[0]:dc=spring,dc=org", "spring.ldap.embedded.base-dn[1]:dc=pivotal,dc=io") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index 991685cdfa7..d5542959b2b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -30,6 +30,8 @@ import liquibase.integration.spring.SpringLiquibase; import liquibase.logging.core.Slf4jLogger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; @@ -45,7 +47,6 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ContextConsumer; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; -import org.springframework.boot.testsupport.Assume; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @@ -65,7 +66,7 @@ import static org.assertj.core.api.Assertions.contentOf; * @author Dominic Gunn */ @ExtendWith(OutputCaptureExtension.class) -public class LiquibaseAutoConfigurationTests { +class LiquibaseAutoConfigurationTests { @BeforeEach public void init() { @@ -78,12 +79,12 @@ public class LiquibaseAutoConfigurationTests { .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test - public void backsOffWithNoDataSourceBeanAndNoLiquibaseUrl() { + void backsOffWithNoDataSourceBeanAndNoLiquibaseUrl() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); } @Test - public void createsDataSourceWithNoDataSourceBeanAndLiquibaseUrl() { + void createsDataSourceWithNoDataSourceBeanAndLiquibaseUrl() { this.contextRunner.withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:liquibase") .run(assertLiquibase((liquibase) -> { DataSource dataSource = liquibase.getDataSource(); @@ -93,7 +94,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void defaultSpringLiquibase() { + void defaultSpringLiquibase() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .run(assertLiquibase((liquibase) -> { assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); @@ -104,7 +105,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void changelogXml() { + void changelogXml() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) @@ -112,7 +113,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void changelogJson() { + void changelogJson() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) @@ -120,8 +121,8 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void changelogSql() { - Assume.javaEight(); + @EnabledOnJre(JRE.JAVA_8) + void changelogSql() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) @@ -129,7 +130,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void defaultValues() { + void defaultValues() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .run(assertLiquibase((liquibase) -> { LiquibaseProperties properties = new LiquibaseProperties(); @@ -142,21 +143,21 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void overrideContexts() { + void overrideContexts() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.contexts:test, production") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); } @Test - public void overrideDefaultSchema() { + void overrideDefaultSchema() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.default-schema:public") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); } @Test - public void overrideLiquibaseInfrastructure() { + void overrideLiquibaseInfrastructure() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.liquibase-schema:public", "spring.liquibase.liquibase-tablespace:infra", @@ -177,14 +178,14 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void overrideDropFirst() { + void overrideDropFirst() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.drop-first:true") .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); } @Test - public void overrideDataSource() { + void overrideDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:liquibase") .run(assertLiquibase((liquibase) -> { @@ -195,7 +196,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void overrideUser() { + void overrideUser() { String jdbcUrl = "jdbc:hsqldb:mem:normal"; this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.url:" + jdbcUrl, "spring.datasource.username:not-sa", @@ -209,7 +210,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void overrideTestRollbackOnUpdate() { + void overrideTestRollbackOnUpdate() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.test-rollback-on-update:true").run((context) -> { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); @@ -218,7 +219,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void changeLogDoesNotExist() { + void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml").run((context) -> { assertThat(context).hasFailed(); @@ -227,7 +228,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void logging(CapturedOutput output) { + void logging(CapturedOutput output) { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .run(assertLiquibase((liquibase) -> { Object log = ReflectionTestUtils.getField(liquibase, "log"); @@ -237,7 +238,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void overrideLabels() { + void overrideLabels() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.labels:test, production") .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels()).isEqualTo("test, production"))); @@ -245,7 +246,7 @@ public class LiquibaseAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void testOverrideParameters() { + void testOverrideParameters() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.parameters.foo:bar").run(assertLiquibase((liquibase) -> { Map parameters = (Map) ReflectionTestUtils.getField(liquibase, @@ -256,7 +257,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void rollbackFile(@TempDir Path temp) throws IOException { + void rollbackFile(@TempDir Path temp) throws IOException { File file = Files.createTempFile(temp, "rollback-file", "sql").toFile(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()).run((context) -> { @@ -268,7 +269,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void liquibaseDataSource() { + void liquibaseDataSource() { this.contextRunner .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) .run((context) -> { @@ -278,7 +279,7 @@ public class LiquibaseAutoConfigurationTests { } @Test - public void liquibaseDataSourceWithoutDataSourceAutoConfiguration() { + void liquibaseDataSourceWithoutDataSourceAutoConfiguration() { this.contextRunner.withUserConfiguration(LiquibaseDataSourceConfiguration.class).run((context) -> { SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java index 381fbb2eb88..27393e47960 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java @@ -54,12 +54,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Madhura Bhave */ @ExtendWith(OutputCaptureExtension.class) -public class ConditionEvaluationReportLoggingListenerTests { +class ConditionEvaluationReportLoggingListenerTests { private ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(); @Test - public void logsDebugOnContextRefresh(CapturedOutput capturedOutput) { + void logsDebugOnContextRefresh(CapturedOutput capturedOutput) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(Config.class); @@ -69,7 +69,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void logsDebugOnError(CapturedOutput capturedOutput) { + void logsDebugOnError(CapturedOutput capturedOutput) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); @@ -80,7 +80,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void logsInfoOnErrorIfDebugDisabled(CapturedOutput capturedOutput) { + void logsInfoOnErrorIfDebugDisabled(CapturedOutput capturedOutput) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); @@ -92,7 +92,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void logsOutput(CapturedOutput capturedOutput) { + void logsOutput(CapturedOutput capturedOutput) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(Config.class); @@ -103,7 +103,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void canBeUsedInApplicationContext() { + void canBeUsedInApplicationContext() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Config.class); new ConditionEvaluationReportLoggingListener().initialize(context); @@ -112,7 +112,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void canBeUsedInNonGenericApplicationContext() { + void canBeUsedInNonGenericApplicationContext() { AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); context.setServletContext(new MockServletContext()); context.register(Config.class); @@ -122,7 +122,7 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void listenerWithInfoLevelShouldLogAtInfo(CapturedOutput capturedOutput) { + void listenerWithInfoLevelShouldLogAtInfo(CapturedOutput capturedOutput) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener( LogLevel.INFO); @@ -134,14 +134,14 @@ public class ConditionEvaluationReportLoggingListenerTests { } @Test - public void listenerSupportsOnlyInfoAndDebug() { + void listenerSupportsOnlyInfoAndDebug() { assertThatIllegalArgumentException() .isThrownBy(() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) .withMessageContaining("LogLevel must be INFO or DEBUG"); } @Test - public void noErrorIfNotInitialized(CapturedOutput capturedOutput) { + void noErrorIfNotInitialized(CapturedOutput capturedOutput) { this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, new RuntimeException("Planned"))); assertThat(capturedOutput).contains("Unable to provide the conditions report"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index e8467c07664..ccfeb66afef 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Eddú Meléndez */ -public class MailSenderAutoConfigurationTests { +class MailSenderAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(MailSenderAutoConfiguration.class, MailSenderValidatorAutoConfiguration.class)); @@ -78,7 +78,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void smtpHostSet() { + void smtpHostSet() { String host = "192.168.1.234"; this.contextRunner.withPropertyValues("spring.mail.host:" + host).run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); @@ -90,7 +90,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void smtpHostWithSettings() { + void smtpHostWithSettings() { String host = "192.168.1.234"; this.contextRunner.withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", "spring.mail.username:john", "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", @@ -107,7 +107,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void smtpHostWithJavaMailProperties() { + void smtpHostWithJavaMailProperties() { this.contextRunner .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") .run((context) -> { @@ -118,12 +118,12 @@ public class MailSenderAutoConfigurationTests { } @Test - public void smtpHostNotSet() { + void smtpHostNotSet() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(MailSender.class)); } @Test - public void mailSenderBackOff() { + void mailSenderBackOff() { this.contextRunner.withUserConfiguration(ManualMailConfiguration.class) .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", "spring.mail.password:secret") @@ -136,13 +136,13 @@ public class MailSenderAutoConfigurationTests { } @Test - public void jndiSessionAvailable() { + void jndiSessionAvailable() { Session session = configureJndiSession("java:comp/env/foo"); testJndiSessionLookup(session, "java:comp/env/foo"); } @Test - public void jndiSessionAvailableWithResourceRef() { + void jndiSessionAvailableWithResourceRef() { Session session = configureJndiSession("java:comp/env/foo"); testJndiSessionLookup(session, "foo"); } @@ -158,7 +158,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void jndiSessionIgnoredIfJndiNameNotSet() { + void jndiSessionIgnoredIfJndiNameNotSet() { configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.host:smtp.acme.org").run((context) -> { assertThat(context).doesNotHaveBean(Session.class); @@ -167,7 +167,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void jndiSessionNotUsedIfJndiNameNotSet() { + void jndiSessionNotUsedIfJndiNameNotSet() { configureJndiSession("foo"); this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(Session.class); @@ -176,7 +176,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void jndiSessionNotAvailableWithJndiName() { + void jndiSessionNotAvailableWithJndiName() { this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo").run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) @@ -185,7 +185,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void jndiSessionTakesPrecedenceOverProperties() { + void jndiSessionTakesPrecedenceOverProperties() { Session session = configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.host:localhost") .run((context) -> { @@ -197,7 +197,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void defaultEncodingWithProperties() { + void defaultEncodingWithProperties() { this.contextRunner.withPropertyValues("spring.mail.host:localhost", "spring.mail.default-encoding:UTF-16") .run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); @@ -207,7 +207,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void defaultEncodingWithJndi() { + void defaultEncodingWithJndi() { configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.default-encoding:UTF-16") .run((context) -> { @@ -218,7 +218,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void connectionOnStartup() { + void connectionOnStartup() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> { assertThat(context).hasSingleBean(JavaMailSenderImpl.class); @@ -228,7 +228,7 @@ public class MailSenderAutoConfigurationTests { } @Test - public void connectionOnStartupNotCalled() { + void connectionOnStartupNotCalled() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index b92ee39ea10..9d111732b09 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -37,32 +37,32 @@ import static org.mockito.Mockito.mock; * @author Dave Syer * @author Stephane Nicoll */ -public class MongoAutoConfigurationTests { +class MongoAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)); @Test - public void clientExists() { + void clientExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test - public void optionsAdded() { + void optionsAdded() { this.contextRunner.withUserConfiguration(OptionsConfig.class).run( (context) -> assertThat(context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()) .isEqualTo(300)); } @Test - public void optionsAddedButNoHost() { + void optionsAddedButNoHost() { this.contextRunner.withUserConfiguration(OptionsConfig.class).run( (context) -> assertThat(context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()) .isEqualTo(300)); } @Test - public void optionsSslConfig() { + void optionsSslConfig() { this.contextRunner.withUserConfiguration(SslOptionsConfig.class).run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); MongoClient mongo = context.getBean(MongoClient.class); @@ -73,7 +73,7 @@ public class MongoAutoConfigurationTests { } @Test - public void doesNotCreateMongoClientWhenAlreadyDefined() { + void doesNotCreateMongoClientWhenAlreadyDefined() { this.contextRunner.withUserConfiguration(FallbackMongoClientConfig.class).run((context) -> { assertThat(context).doesNotHaveBean(MongoClient.class); assertThat(context).hasSingleBean(com.mongodb.client.MongoClient.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java index a4124662fc2..0e59b9bd682 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactoryTests.java @@ -38,12 +38,12 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Mark Paluch */ -public class MongoClientFactoryTests { +class MongoClientFactoryTests { private MockEnvironment environment = new MockEnvironment(); @Test - public void portCanBeCustomized() { + void portCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setPort(12345); MongoClient client = createMongoClient(properties); @@ -53,7 +53,7 @@ public class MongoClientFactoryTests { } @Test - public void hostCanBeCustomized() { + void hostCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setHost("mongo.example.com"); MongoClient client = createMongoClient(properties); @@ -63,7 +63,7 @@ public class MongoClientFactoryTests { } @Test - public void credentialsCanBeCustomized() { + void credentialsCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setUsername("user"); properties.setPassword("secret".toCharArray()); @@ -72,7 +72,7 @@ public class MongoClientFactoryTests { } @Test - public void databaseCanBeCustomized() { + void databaseCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setDatabase("foo"); properties.setUsername("user"); @@ -82,7 +82,7 @@ public class MongoClientFactoryTests { } @Test - public void authenticationDatabaseCanBeCustomized() { + void authenticationDatabaseCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setAuthenticationDatabase("foo"); properties.setUsername("user"); @@ -92,7 +92,7 @@ public class MongoClientFactoryTests { } @Test - public void uriCanBeCustomized() { + void uriCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test"); MongoClient client = createMongoClient(properties); @@ -106,7 +106,7 @@ public class MongoClientFactoryTests { } @Test - public void uriIsIgnoredInEmbeddedMode() { + void uriIsIgnoredInEmbeddedMode() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://mongo.example.com:1234/mydb"); this.environment.setProperty("local.mongo.port", "4000"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java index eaf529aa630..a3717838699 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java @@ -39,10 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch * @author Artsiom Yudovin */ -public class MongoPropertiesTests { +class MongoPropertiesTests { @Test - public void canBindCharArrayPassword() { + void canBindCharArrayPassword() { // gh-1572 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.data.mongodb.password:word").applyTo(context); @@ -54,7 +54,7 @@ public class MongoPropertiesTests { @Test @SuppressWarnings("deprecation") - public void allMongoClientOptionsCanBeSet() { + void allMongoClientOptionsCanBeSet() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.alwaysUseMBeans(true); builder.connectionsPerHost(101); @@ -100,7 +100,7 @@ public class MongoPropertiesTests { } @Test - public void uriOverridesHostAndPort() { + void uriOverridesHostAndPort() { MongoProperties properties = new MongoProperties(); properties.setHost("localhost"); properties.setPort(27017); @@ -112,7 +112,7 @@ public class MongoPropertiesTests { } @Test - public void onlyHostAndPortSetShouldUseThat() { + void onlyHostAndPortSetShouldUseThat() { MongoProperties properties = new MongoProperties(); properties.setHost("localhost"); properties.setPort(27017); @@ -123,7 +123,7 @@ public class MongoPropertiesTests { } @Test - public void onlyUriSetShouldUseThat() { + void onlyUriSetShouldUseThat() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://mongo1.example.com:12345"); MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); @@ -133,7 +133,7 @@ public class MongoPropertiesTests { } @Test - public void noCustomAddressAndNoUriUsesDefaultUri() { + void noCustomAddressAndNoUriUsesDefaultUri() { MongoProperties properties = new MongoProperties(); MongoClient client = new MongoClientFactory(properties, null).createMongoClient(null); List allAddresses = getAllAddresses(client); @@ -149,7 +149,7 @@ public class MongoPropertiesTests { } @Test - public void canBindAutoIndexCreation() { + void canBindAutoIndexCreation() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.data.mongodb.autoIndexCreation:true").applyTo(context); context.register(Config.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java index 33e713cd2b9..e16f7b491bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java @@ -47,18 +47,18 @@ import static org.mockito.Mockito.mock; * @author Mark Paluch * @author Stephane Nicoll */ -public class MongoReactiveAutoConfigurationTests { +class MongoReactiveAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); @Test - public void clientExists() { + void clientExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test - public void optionsAdded() { + void optionsAdded() { this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost") .withUserConfiguration(OptionsConfig.class) .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) @@ -66,7 +66,7 @@ public class MongoReactiveAutoConfigurationTests { } @Test - public void optionsAddedButNoHost() { + void optionsAddedButNoHost() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") .withUserConfiguration(OptionsConfig.class) .run((context) -> assertThat(getSettings(context).getReadPreference()) @@ -74,7 +74,7 @@ public class MongoReactiveAutoConfigurationTests { } @Test - public void optionsSslConfig() { + void optionsSslConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") .withUserConfiguration(SslOptionsConfig.class).run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); @@ -85,7 +85,7 @@ public class MongoReactiveAutoConfigurationTests { } @Test - public void nettyStreamFactoryFactoryIsConfiguredAutomatically() { + void nettyStreamFactoryFactoryIsConfiguredAutomatically() { AtomicReference eventLoopGroupReference = new AtomicReference<>(); this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); @@ -99,7 +99,7 @@ public class MongoReactiveAutoConfigurationTests { } @Test - public void customizerOverridesAutoConfig() { + void customizerOverridesAutoConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") .withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java index ea819b63cca..bc60f0d15a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java @@ -42,12 +42,12 @@ import static org.mockito.Mockito.verify; * @author Mark Paluch * @author Stephane Nicoll */ -public class ReactiveMongoClientFactoryTests { +class ReactiveMongoClientFactoryTests { private MockEnvironment environment = new MockEnvironment(); @Test - public void portCanBeCustomized() { + void portCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setPort(12345); MongoClient client = createMongoClient(properties); @@ -57,7 +57,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void hostCanBeCustomized() { + void hostCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setHost("mongo.example.com"); MongoClient client = createMongoClient(properties); @@ -67,7 +67,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void credentialsCanBeCustomized() { + void credentialsCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setUsername("user"); properties.setPassword("secret".toCharArray()); @@ -76,7 +76,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void databaseCanBeCustomized() { + void databaseCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setDatabase("foo"); properties.setUsername("user"); @@ -86,7 +86,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void authenticationDatabaseCanBeCustomized() { + void authenticationDatabaseCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setAuthenticationDatabase("foo"); properties.setUsername("user"); @@ -96,7 +96,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void uriCanBeCustomized() { + void uriCanBeCustomized() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://user:secret@mongo1.example.com:12345," + "mongo2.example.com:23456/test"); MongoClient client = createMongoClient(properties); @@ -109,7 +109,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void retryWritesIsPropagatedFromUri() { + void retryWritesIsPropagatedFromUri() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://localhost/test?retryWrites=true"); MongoClient client = createMongoClient(properties); @@ -117,7 +117,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void uriCannotBeSetWithCredentials() { + void uriCannotBeSetWithCredentials() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setUsername("user"); @@ -127,7 +127,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void uriCannotBeSetWithHostPort() { + void uriCannotBeSetWithHostPort() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setHost("localhost"); @@ -137,7 +137,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void uriIsIgnoredInEmbeddedMode() { + void uriIsIgnoredInEmbeddedMode() { MongoProperties properties = new MongoProperties(); properties.setUri("mongodb://mongo.example.com:1234/mydb"); this.environment.setProperty("local.mongo.port", "4000"); @@ -148,7 +148,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void customizerIsInvoked() { + void customizerIsInvoked() { MongoProperties properties = new MongoProperties(); MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); createMongoClient(properties, this.environment, customizer); @@ -156,7 +156,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void customizerIsInvokedWhenHostIsSet() { + void customizerIsInvokedWhenHostIsSet() { MongoProperties properties = new MongoProperties(); properties.setHost("localhost"); MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); @@ -165,7 +165,7 @@ public class ReactiveMongoClientFactoryTests { } @Test - public void customizerIsInvokedForEmbeddedMongo() { + void customizerIsInvokedForEmbeddedMongo() { MongoProperties properties = new MongoProperties(); this.environment.setProperty("local.mongo.port", "27017"); MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index e1395887e32..f03f157d0a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -57,7 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class EmbeddedMongoAutoConfigurationTests { +class EmbeddedMongoAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -69,23 +69,23 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void defaultVersion() { + void defaultVersion() { assertVersionConfiguration(null, "3.5.5"); } @Test - public void customVersion() { + void customVersion() { String version = Version.V3_4_15.asInDownloadPath(); assertVersionConfiguration(version, version); } @Test - public void customUnknownVersion() { + void customUnknownVersion() { assertVersionConfiguration("3.4.1", "3.4.1"); } @Test - public void customFeatures() { + void customFeatures() { EnumSet features = EnumSet.of(Feature.TEXT_SEARCH, Feature.SYNC_DELAY, Feature.ONLY_WITH_SSL, Feature.NO_HTTP_INTERFACE_ARG); if (isWindows()) { @@ -98,7 +98,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void useRandomPortByDefault() { + void useRandomPortByDefault() { load(); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); @@ -107,7 +107,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void specifyPortToZeroAllocateRandomPort() { + void specifyPortToZeroAllocateRandomPort() { load("spring.data.mongodb.port=0"); assertThat(this.context.getBeansOfType(MongoClient.class)).hasSize(1); MongoClient client = this.context.getBean(MongoClient.class); @@ -116,7 +116,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() { + void randomlyAllocatedPortIsAvailableWhenCreatingMongoClient() { load(MongoClientConfiguration.class); MongoClient client = this.context.getBean(MongoClient.class); Integer mongoPort = Integer.valueOf(this.context.getEnvironment().getProperty("local.mongo.port")); @@ -124,7 +124,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void portIsAvailableInParentContext() { + void portIsAvailableInParentContext() { try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) { parent.refresh(); this.context = new AnnotationConfigApplicationContext(); @@ -136,7 +136,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void defaultStorageConfiguration() { + void defaultStorageConfiguration() { load(MongoClientConfiguration.class); Storage replication = this.context.getBean(IMongodConfig.class).replication(); assertThat(replication.getOplogSize()).isEqualTo(0); @@ -145,7 +145,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void mongoWritesToCustomDatabaseDir(@TempDir Path temp) throws IOException { + void mongoWritesToCustomDatabaseDir(@TempDir Path temp) throws IOException { File customDatabaseDir = new File(temp.toFile(), "custom-database-dir"); FileSystemUtils.deleteRecursively(customDatabaseDir); load("spring.mongodb.embedded.storage.databaseDir=" + customDatabaseDir.getPath()); @@ -154,25 +154,25 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void customOpLogSizeIsAppliedToConfiguration() { + void customOpLogSizeIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.oplogSize=1024KB"); assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()).isEqualTo(1); } @Test - public void customOpLogSizeUsesMegabytesPerDefault() { + void customOpLogSizeUsesMegabytesPerDefault() { load("spring.mongodb.embedded.storage.oplogSize=10"); assertThat(this.context.getBean(IMongodConfig.class).replication().getOplogSize()).isEqualTo(10); } @Test - public void customReplicaSetNameIsAppliedToConfiguration() { + void customReplicaSetNameIsAppliedToConfiguration() { load("spring.mongodb.embedded.storage.replSetName=testing"); assertThat(this.context.getBean(IMongodConfig.class).replication().getReplSetName()).isEqualTo("testing"); } @Test - public void customizeDownloadConfiguration() { + void customizeDownloadConfiguration() { load(DownloadConfigBuilderCustomizerConfiguration.class); IRuntimeConfig runtimeConfig = this.context.getBean(IRuntimeConfig.class); IDownloadConfig downloadConfig = (IDownloadConfig) new DirectFieldAccessor(runtimeConfig.getArtifactStore()) @@ -181,7 +181,7 @@ public class EmbeddedMongoAutoConfigurationTests { } @Test - public void shutdownHookIsNotRegistered() { + void shutdownHookIsNotRegistered() { load(); assertThat(this.context.getBean(MongodExecutable.class).isRegisteredJobKiller()).isFalse(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java index 5ed54e1dbb7..ca50273aebc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java @@ -49,20 +49,20 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") -public class MustacheAutoConfigurationReactiveIntegrationTests { +class MustacheAutoConfigurationReactiveIntegrationTests { @Autowired private WebTestClient client; @Test - public void testHomePage() { + void testHomePage() { String result = this.client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) .returnResult().getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @Test - public void testPartialPage() { + void testPartialPage() { String result = this.client.get().uri("/partial").exchange().expectStatus().isOk().expectBody(String.class) .returnResult().getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java index 3bfe6db6804..34fc97fe029 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java @@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class MustacheAutoConfigurationServletIntegrationTests { +class MustacheAutoConfigurationServletIntegrationTests { @Autowired private ServletWebServerApplicationContext context; @@ -71,7 +71,7 @@ public class MustacheAutoConfigurationServletIntegrationTests { } @Test - public void contextLoads() { + void contextLoads() { String source = "Hello {{arg}}!"; Template tmpl = Mustache.compiler().compile(source); Map context = new HashMap<>(); @@ -80,13 +80,13 @@ public class MustacheAutoConfigurationServletIntegrationTests { } @Test - public void testHomePage() { + void testHomePage() { String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); assertThat(body.contains("Hello World")).isTrue(); } @Test - public void testPartialPage() { + void testPartialPage() { String body = new TestRestTemplate().getForObject("http://localhost:" + this.port + "/partial", String.class); assertThat(body.contains("Hello World")).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java index 323ad205443..9cd478020b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java @@ -34,14 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class MustacheAutoConfigurationTests { +class MustacheAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext webContext; private AnnotationConfigReactiveWebApplicationContext reactiveWebContext; @Test - public void registerBeansForServletApp() { + void registerBeansForServletApp() { loadWithServlet(null); assertThat(this.webContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); @@ -49,7 +49,7 @@ public class MustacheAutoConfigurationTests { } @Test - public void registerCompilerForServletApp() { + void registerCompilerForServletApp() { loadWithServlet(CustomCompilerConfiguration.class); assertThat(this.webContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); assertThat(this.webContext.getBeansOfType(MustacheViewResolver.class)).hasSize(1); @@ -58,7 +58,7 @@ public class MustacheAutoConfigurationTests { } @Test - public void registerBeansForReactiveApp() { + void registerBeansForReactiveApp() { loadWithReactive(null); assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); assertThat(this.reactiveWebContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); @@ -69,7 +69,7 @@ public class MustacheAutoConfigurationTests { } @Test - public void registerCompilerForReactiveApp() { + void registerCompilerForReactiveApp() { loadWithReactive(CustomCompilerConfiguration.class); assertThat(this.reactiveWebContext.getBeansOfType(Mustache.Compiler.class)).hasSize(1); assertThat(this.reactiveWebContext.getBeansOfType(MustacheResourceTemplateLoader.class)).hasSize(1); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index be3aeafc4d2..9046145c555 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -38,30 +38,30 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = { "env.FOO=There", "foo=World" }) -public class MustacheStandaloneIntegrationTests { +class MustacheStandaloneIntegrationTests { @Autowired private Mustache.Compiler compiler; @Test - public void directCompilation() { + void directCompilation() { assertThat(this.compiler.compile("Hello: {{world}}").execute(Collections.singletonMap("world", "World"))) .isEqualTo("Hello: World"); } @Test - public void environmentCollectorCompoundKey() { + void environmentCollectorCompoundKey() { assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())).isEqualTo("Hello: There"); } @Test - public void environmentCollectorCompoundKeyStandard() { + void environmentCollectorCompoundKeyStandard() { assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}").execute(new Object())) .isEqualTo("Hello: There"); } @Test - public void environmentCollectorSimpleKey() { + void environmentCollectorSimpleKey() { assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())).isEqualTo("Hello: World"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index 31dc8198d64..0915e48a088 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public abstract class AbstractJpaAutoConfigurationTests { +abstract class AbstractJpaAutoConfigurationTests { private final Class autoConfiguredClass; @@ -78,13 +78,13 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void notConfiguredIfDataSourceIsNotAvailable() { + void notConfiguredIfDataSourceIsNotAvailable() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) .run(assertJpaIsNotAutoConfigured()); } @Test - public void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() { + void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() { new ApplicationContextRunner().withUserConfiguration(TestTwoDataSourcesConfiguration.class) .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)).run(assertJpaIsNotAutoConfigured()); } @@ -99,7 +99,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void configuredWithAutoConfiguredDataSource() { + void configuredWithAutoConfiguredDataSource() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DataSource.class); assertThat(context).hasSingleBean(JpaTransactionManager.class); @@ -108,7 +108,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void configuredWithSingleCandidateDataSource() { + void configuredWithSingleCandidateDataSource() { this.contextRunner.withUserConfiguration(TestTwoDataSourcesAndPrimaryConfiguration.class).run((context) -> { assertThat(context).getBeans(DataSource.class).hasSize(2); assertThat(context).hasSingleBean(JpaTransactionManager.class); @@ -117,7 +117,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void jtaTransactionManagerTakesPrecedence() { + void jtaTransactionManagerTakesPrecedence() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class)) .run((context) -> { assertThat(context).hasSingleBean(DataSource.class); @@ -127,7 +127,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void openEntityManagerInViewInterceptorIsCreated() { + void openEntityManagerInViewInterceptorIsCreated() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -136,7 +136,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() { + void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestFilterConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -145,7 +145,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() { + void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestFilterRegistrationConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -154,7 +154,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() { + void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") .withUserConfiguration(TestInterceptorManualConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -165,7 +165,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() { + void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() { new WebApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") .withUserConfiguration(TestConfiguration.class) @@ -175,7 +175,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void customJpaProperties() { + void customJpaProperties() { this.contextRunner.withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d").run((context) -> { LocalContainerEntityManagerFactoryBean bean = context @@ -188,7 +188,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { + void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) .run((context) -> { LocalContainerEntityManagerFactoryBean factoryBean = context @@ -199,7 +199,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void usesManuallyDefinedEntityManagerFactoryIfAvailable() { + void usesManuallyDefinedEntityManagerFactoryIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) .run((context) -> { EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); @@ -209,7 +209,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void usesManuallyDefinedTransactionManagerBeanIfAvailable() { + void usesManuallyDefinedTransactionManagerBeanIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithTransactionManager.class).run((context) -> { PlatformTransactionManager txManager = context.getBean(PlatformTransactionManager.class); assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class); @@ -217,7 +217,7 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Test - public void customPersistenceUnitManager() { + void customPersistenceUnitManager() { this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitManager.class) .run((context) -> { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index 2148c05ae9d..d9447e85d90 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -53,7 +53,7 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class CustomHibernateJpaAutoConfigurationTests { +class CustomHibernateJpaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true") @@ -61,7 +61,7 @@ public class CustomHibernateJpaAutoConfigurationTests { AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); @Test - public void namingStrategyDelegatorTakesPrecedence() { + void namingStrategyDelegatorTakesPrecedence() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator").run((context) -> { JpaProperties jpaProperties = context.getBean(JpaProperties.class); @@ -73,7 +73,7 @@ public class CustomHibernateJpaAutoConfigurationTests { } @Test - public void namingStrategyBeansAreUsed() { + void namingStrategyBeansAreUsed() { this.contextRunner.withUserConfiguration(NamingStrategyConfiguration.class) .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans").run((context) -> { HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); @@ -86,7 +86,7 @@ public class CustomHibernateJpaAutoConfigurationTests { } @Test - public void hibernatePropertiesCustomizersAreAppliedInOrder() { + void hibernatePropertiesCustomizersAreAppliedInOrder() { this.contextRunner.withUserConfiguration(HibernatePropertiesCustomizerConfiguration.class).run((context) -> { HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); Map hibernateProperties = jpaConfiguration.getVendorProperties(); @@ -95,7 +95,7 @@ public class CustomHibernateJpaAutoConfigurationTests { } @Test - public void defaultDatabaseIsSet() { + void defaultDatabaseIsSet() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:h2:mem:testdb", "spring.datasource.initialization-mode:never").run((context) -> { HibernateJpaVendorAdapter bean = context.getBean(HibernateJpaVendorAdapter.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/DatabaseLookupTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/DatabaseLookupTests.java index e315d95cbda..9de0b98ad20 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/DatabaseLookupTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/DatabaseLookupTests.java @@ -35,65 +35,65 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @author Phillip Webb */ -public class DatabaseLookupTests { +class DatabaseLookupTests { @Test - public void getDatabaseWhenDataSourceIsNullShouldReturnDefault() { + void getDatabaseWhenDataSourceIsNullShouldReturnDefault() { assertThat(DatabaseLookup.getDatabase(null)).isEqualTo(Database.DEFAULT); } @Test - public void getDatabaseWhenDataSourceIsUnknownShouldReturnDefault() throws Exception { + void getDatabaseWhenDataSourceIsUnknownShouldReturnDefault() throws Exception { testGetDatabase("jdbc:idontexist:", Database.DEFAULT); } @Test - public void getDatabaseWhenDerbyShouldReturnDerby() throws Exception { + void getDatabaseWhenDerbyShouldReturnDerby() throws Exception { testGetDatabase("jdbc:derby:", Database.DERBY); } @Test - public void getDatabaseWhenH2ShouldReturnH2() throws Exception { + void getDatabaseWhenH2ShouldReturnH2() throws Exception { testGetDatabase("jdbc:h2:", Database.H2); } @Test - public void getDatabaseWhenHsqldbShouldReturnHsqldb() throws Exception { + void getDatabaseWhenHsqldbShouldReturnHsqldb() throws Exception { testGetDatabase("jdbc:hsqldb:", Database.HSQL); } @Test - public void getDatabaseWhenMysqlShouldReturnMysql() throws Exception { + void getDatabaseWhenMysqlShouldReturnMysql() throws Exception { testGetDatabase("jdbc:mysql:", Database.MYSQL); } @Test - public void getDatabaseWhenOracleShouldReturnOracle() throws Exception { + void getDatabaseWhenOracleShouldReturnOracle() throws Exception { testGetDatabase("jdbc:oracle:", Database.ORACLE); } @Test - public void getDatabaseWhenPostgresShouldReturnPostgres() throws Exception { + void getDatabaseWhenPostgresShouldReturnPostgres() throws Exception { testGetDatabase("jdbc:postgresql:", Database.POSTGRESQL); } @Test - public void getDatabaseWhenSqlserverShouldReturnSqlserver() throws Exception { + void getDatabaseWhenSqlserverShouldReturnSqlserver() throws Exception { testGetDatabase("jdbc:sqlserver:", Database.SQL_SERVER); } @Test - public void getDatabaseWhenDb2ShouldReturnDb2() throws Exception { + void getDatabaseWhenDb2ShouldReturnDb2() throws Exception { testGetDatabase("jdbc:db2:", Database.DB2); } @Test - public void getDatabaseWhenInformixShouldReturnInformix() throws Exception { + void getDatabaseWhenInformixShouldReturnInformix() throws Exception { testGetDatabase("jdbc:informix-sqli:", Database.INFORMIX); } @Test - public void getDatabaseWhenSapShouldReturnHana() throws Exception { + void getDatabaseWhenSapShouldReturnHana() throws Exception { testGetDatabase("jdbc:sap:", Database.HANA); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java index 3fe317e3e75..14e0cffd261 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class HibernateDefaultDdlAutoProviderTests { +class HibernateDefaultDdlAutoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( @@ -45,7 +45,7 @@ public class HibernateDefaultDdlAutoProviderTests { .withPropertyValues("spring.datasource.initialization-mode:never"); @Test - public void defaultDDlAutoForEmbedded() { + void defaultDDlAutoForEmbedded() { this.contextRunner.run((context) -> { HibernateDefaultDdlAutoProvider ddlAutoProvider = new HibernateDefaultDdlAutoProvider( Collections.emptyList()); @@ -54,7 +54,7 @@ public class HibernateDefaultDdlAutoProviderTests { } @Test - public void defaultDDlAutoForEmbeddedWithPositiveContributor() { + void defaultDDlAutoForEmbeddedWithPositiveContributor() { this.contextRunner.run((context) -> { DataSource dataSource = context.getBean(DataSource.class); SchemaManagementProvider provider = mock(SchemaManagementProvider.class); @@ -66,7 +66,7 @@ public class HibernateDefaultDdlAutoProviderTests { } @Test - public void defaultDDlAutoForEmbeddedWithNegativeContributor() { + void defaultDDlAutoForEmbeddedWithNegativeContributor() { this.contextRunner.run((context) -> { DataSource dataSource = context.getBean(DataSource.class); SchemaManagementProvider provider = mock(SchemaManagementProvider.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index 226ed3ed4f5..e52a024bc80 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -85,14 +85,14 @@ import static org.mockito.Mockito.mock; * @author Kazuki Shimizu * @author Stephane Nicoll */ -public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTests { +class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTests { public HibernateJpaAutoConfigurationTests() { super(HibernateJpaAutoConfiguration.class); } @Test - public void testDataScriptWithMissingDdl() { + void testDataScriptWithMissingDdl() { contextRunner().withPropertyValues("spring.datasource.data:classpath:/city.sql", // Missing: "spring.datasource.schema:classpath:/ddl.sql").run((context) -> { @@ -103,7 +103,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void testDataScript() { + void testDataScript() { // This can't succeed because the data SQL is executed immediately after the // schema // and Hibernate hasn't initialized yet at that point @@ -114,7 +114,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void testDataScriptRunsEarly() { + void testDataScriptRunsEarly() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) .withClassLoader(new HideDataScriptClassLoader()) .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", @@ -123,7 +123,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void testFlywaySwitchOffDdlAuto() { + void testFlywaySwitchOffDdlAuto() { contextRunner() .withPropertyValues("spring.datasource.initialization-mode:never", "spring.flyway.locations:classpath:db/city") @@ -132,7 +132,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void testFlywayPlusValidation() { + void testFlywayPlusValidation() { contextRunner() .withPropertyValues("spring.datasource.initialization-mode:never", "spring.flyway.locations:classpath:db/city", "spring.jpa.hibernate.ddl-auto:validate") @@ -141,7 +141,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void testLiquibasePlusValidation() { + void testLiquibasePlusValidation() { contextRunner() .withPropertyValues("spring.datasource.initialization-mode:never", "spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", @@ -151,20 +151,20 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void hibernateDialectIsNotSetByDefault() { + void hibernateDialectIsNotSetByDefault() { contextRunner().run(assertJpaVendorAdapter( (adapter) -> assertThat(adapter.getJpaPropertyMap()).doesNotContainKeys("hibernate.dialect"))); } @Test - public void hibernateDialectIsSetWhenDatabaseIsSet() { + void hibernateDialectIsSetWhenDatabaseIsSet() { contextRunner().withPropertyValues("spring.jpa.database=H2") .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); } @Test - public void hibernateDialectIsSetWhenDatabasePlatformIsSet() { + void hibernateDialectIsSetWhenDatabasePlatformIsSet() { String databasePlatform = TestH2Dialect.class.getName(); contextRunner().withPropertyValues("spring.jpa.database-platform=" + databasePlatform) .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) @@ -181,13 +181,13 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void jtaDefaultPlatform() { + void jtaDefaultPlatform() { contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) .run(assertJtaPlatform(SpringJtaPlatform.class)); } @Test - public void jtaCustomPlatform() { + void jtaCustomPlatform() { contextRunner() .withPropertyValues( "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) @@ -196,7 +196,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void jtaNotUsedByTheApplication() { + void jtaNotUsedByTheApplication() { contextRunner().run(assertJtaPlatform(NoJtaPlatform.class)); } @@ -209,7 +209,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void jtaCustomTransactionManagerUsingProperties() { + void jtaCustomTransactionManagerUsingProperties() { contextRunner().withPropertyValues("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true").run((context) -> { JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); @@ -219,7 +219,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void autoConfigurationBacksOffWithSeveralDataSources() { + void autoConfigurationBacksOffWithSeveralDataSources() { contextRunner() .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) @@ -230,7 +230,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void providerDisablesAutoCommitIsConfigured() { + void providerDisablesAutoCommitIsConfigured() { contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:false").run((context) -> { Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) @@ -241,7 +241,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() { + void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() { contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:true").run((context) -> { Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) @@ -251,7 +251,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() { + void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() { contextRunner() .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:false", @@ -265,7 +265,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void providerDisablesAutoCommitIsNotConfiguredWithJta() { + void providerDisablesAutoCommitIsNotConfiguredWithJta() { contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.auto-commit:false") @@ -277,7 +277,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void customResourceMapping() { + void customResourceMapping() { contextRunner().withClassLoader(new HideDataScriptClassLoader()) .withPropertyValues("spring.datasource.data:classpath:/db/non-annotated-data.sql", "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml") @@ -290,7 +290,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void physicalNamingStrategyCanBeUsed() { + void physicalNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) .getVendorProperties(); @@ -301,7 +301,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void implicitNamingStrategyCanBeUsed() { + void implicitNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestImplicitNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) .getVendorProperties(); @@ -312,7 +312,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void namingStrategyInstancesTakePrecedenceOverNamingStrategyProperties() { + void namingStrategyInstancesTakePrecedenceOverNamingStrategyProperties() { contextRunner() .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) @@ -329,7 +329,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() { + void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() { contextRunner() .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) @@ -348,7 +348,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void eventListenerCanBeRegisteredAsBeans() { + void eventListenerCanBeRegisteredAsBeans() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) .withClassLoader(new HideDataScriptClassLoader()).withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", "spring.datasource.data:classpath:/city.sql") @@ -360,13 +360,13 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void hibernatePropertiesCustomizerCanDisableBeanContainer() { + void hibernatePropertiesCustomizerCanDisableBeanContainer() { contextRunner().withUserConfiguration(DisableBeanContainerConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(City.class)); } @Test - public void withSyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { + void withSyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { contextRunner().withUserConfiguration(JpaUsingApplicationListenerConfiguration.class) .withPropertyValues("spring.datasource.initialization-mode=never").run((context) -> { assertThat(context).hasNotFailed(); @@ -376,7 +376,7 @@ public class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigura } @Test - public void withAsyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { + void withAsyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { contextRunner() .withUserConfiguration(AsyncBootstrappingConfiguration.class, JpaUsingApplicationListenerConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java index 0687ab45b21..996c2134557 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java @@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Artsiom Yudovin */ -public class HibernatePropertiesTests { +class HibernatePropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfiguration.class); @@ -59,7 +59,7 @@ public class HibernatePropertiesTests { } @Test - public void noCustomNamingStrategy() { + void noCustomNamingStrategy() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> { assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); assertThat(hibernateProperties).containsEntry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, @@ -70,7 +70,7 @@ public class HibernatePropertiesTests { } @Test - public void hibernate5CustomNamingStrategies() { + void hibernate5CustomNamingStrategies() { this.contextRunner .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") @@ -83,7 +83,7 @@ public class HibernatePropertiesTests { } @Test - public void hibernate5CustomNamingStrategiesViaJpaProperties() { + void hibernate5CustomNamingStrategiesViaJpaProperties() { this.contextRunner .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") @@ -97,26 +97,26 @@ public class HibernatePropertiesTests { } @Test - public void useNewIdGeneratorMappingsDefault() { + void useNewIdGeneratorMappingsDefault() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"))); } @Test - public void useNewIdGeneratorMappingsFalse() { + void useNewIdGeneratorMappingsFalse() { this.contextRunner.withPropertyValues("spring.jpa.hibernate.use-new-id-generator-mappings:false") .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) .containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"))); } @Test - public void scannerUsesDisabledScannerByDefault() { + void scannerUsesDisabledScannerByDefault() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); } @Test - public void scannerCanBeCustomized() { + void scannerCanBeCustomized() { this.contextRunner.withPropertyValues( "spring.jpa.properties.hibernate.archive.scanner:org.hibernate.boot.archive.scan.internal.StandardScanner") .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties).containsEntry( @@ -124,13 +124,13 @@ public class HibernatePropertiesTests { } @Test - public void defaultDdlAutoIsNotInvokedIfPropertyIsSet() { + void defaultDdlAutoIsNotInvokedIfPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=validate") .run(assertDefaultDdlAutoNotInvoked("validate")); } @Test - public void defaultDdlAutoIsNotInvokedIfHibernateSpecificPropertyIsSet() { + void defaultDdlAutoIsNotInvokedIfHibernateSpecificPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=create") .run(assertDefaultDdlAutoNotInvoked("create")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java index 0ca8fbbd55f..2453e9d985d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/JpaPropertiesTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class JpaPropertiesTests { +class JpaPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfiguration.class); @@ -51,7 +51,7 @@ public class JpaPropertiesTests { @Test @Deprecated @SuppressWarnings("deprecation") - public void determineDatabaseNoCheckIfDatabaseIsSet() { + void determineDatabaseNoCheckIfDatabaseIsSet() { this.contextRunner.withPropertyValues("spring.jpa.database=postgresql") .run(assertJpaProperties((properties) -> { DataSource dataSource = mockStandaloneDataSource(); @@ -69,7 +69,7 @@ public class JpaPropertiesTests { @Test @Deprecated @SuppressWarnings("deprecation") - public void determineDatabaseWithKnownUrl() { + void determineDatabaseWithKnownUrl() { this.contextRunner.run(assertJpaProperties((properties) -> { Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); assertThat(database).isEqualTo(Database.H2); @@ -79,7 +79,7 @@ public class JpaPropertiesTests { @Test @Deprecated @SuppressWarnings("deprecation") - public void determineDatabaseWithKnownUrlAndUserConfig() { + void determineDatabaseWithKnownUrlAndUserConfig() { this.contextRunner.withPropertyValues("spring.jpa.database=mysql").run(assertJpaProperties((properties) -> { Database database = properties.determineDatabase(mockDataSource("jdbc:h2:mem:testdb")); assertThat(database).isEqualTo(Database.MYSQL); @@ -89,7 +89,7 @@ public class JpaPropertiesTests { @Test @Deprecated @SuppressWarnings("deprecation") - public void determineDatabaseWithUnknownUrl() { + void determineDatabaseWithUnknownUrl() { this.contextRunner.run(assertJpaProperties((properties) -> { Database database = properties.determineDatabase(mockDataSource("jdbc:unknown://localhost")); assertThat(database).isEqualTo(Database.DEFAULT); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/packagestest/one/FirstConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/packagestest/one/FirstConfiguration.java index 8e68da5ae15..5f85e951088 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/packagestest/one/FirstConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/packagestest/one/FirstConfiguration.java @@ -22,7 +22,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** - * Sample configuration used in {@link AutoConfigurationPackagesTests}. + * Sample configuration used in {@code AutoConfigurationPackagesTests}. * * @author Oliver Gierke */ diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java index 650df9f0251..9f6c4e3560d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java @@ -69,14 +69,14 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Stephane Nicoll */ @ExtendWith(OutputCaptureExtension.class) -public class QuartzAutoConfigurationTests { +class QuartzAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.datasource.generate-unique-name=true") .withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class)); @Test - public void withNoDataSource() { + void withNoDataSource() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); @@ -85,7 +85,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withDataSourceUseMemoryByDefault() { + void withDataSourceUseMemoryByDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)).run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); @@ -95,7 +95,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withDataSource() { + void withDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)) @@ -103,14 +103,14 @@ public class QuartzAutoConfigurationTests { } @Test - public void withDataSourceNoTransactionManager() { + void withDataSourceNoTransactionManager() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withPropertyValues("spring.quartz.job-store-type=jdbc").run(assertDataSourceJobStore("dataSource")); } @Test - public void dataSourceWithQuartzDataSourceQualifierUsedWhenMultiplePresent() { + void dataSourceWithQuartzDataSourceQualifierUsedWhenMultiplePresent() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class, MultipleDataSourceConfiguration.class) .withPropertyValues("spring.quartz.job-store-type=jdbc") .run(assertDataSourceJobStore("quartzDataSource")); @@ -130,7 +130,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withTaskExecutor() { + void withTaskExecutor() { this.contextRunner.withUserConfiguration(MockExecutorConfiguration.class) .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); @@ -142,7 +142,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withOverwriteExistingJobs() { + void withOverwriteExistingJobs() { this.contextRunner.withUserConfiguration(OverwriteTriggerConfiguration.class) .withPropertyValues("spring.quartz.overwrite-existing-jobs=true").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); @@ -154,7 +154,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withConfiguredJobAndTrigger(CapturedOutput capturedOutput) { + void withConfiguredJobAndTrigger(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class) .withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); @@ -167,7 +167,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withConfiguredCalendars() { + void withConfiguredCalendars() { this.contextRunner.withUserConfiguration(QuartzCalendarsConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); @@ -177,7 +177,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withQuartzProperties() { + void withQuartzProperties() { this.contextRunner.withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceId=FOO") .run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); @@ -187,7 +187,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withCustomizer() { + void withCustomizer() { this.contextRunner.withUserConfiguration(QuartzCustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class); @@ -196,7 +196,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void validateDefaultProperties() { + void validateDefaultProperties() { this.contextRunner.withUserConfiguration(ManualSchedulerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(SchedulerFactoryBean.class); SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); @@ -214,7 +214,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void withCustomConfiguration() { + void withCustomConfiguration() { this.contextRunner.withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", "spring.quartz.overwrite-existing-jobs=true").run((context) -> { @@ -228,20 +228,20 @@ public class QuartzAutoConfigurationTests { } @Test - public void schedulerNameWithDedicatedProperty() { + void schedulerNameWithDedicatedProperty() { this.contextRunner.withPropertyValues("spring.quartz.scheduler-name=testScheduler") .run(assertSchedulerName("testScheduler")); } @Test - public void schedulerNameWithQuartzProperty() { + void schedulerNameWithQuartzProperty() { this.contextRunner .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") .run(assertSchedulerName("testScheduler")); } @Test - public void schedulerNameWithDedicatedPropertyTakesPrecedence() { + void schedulerNameWithDedicatedPropertyTakesPrecedence() { this.contextRunner .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") @@ -249,7 +249,7 @@ public class QuartzAutoConfigurationTests { } @Test - public void schedulerNameUseBeanNameByDefault() { + void schedulerNameUseBeanNameByDefault() { this.contextRunner.withPropertyValues().run(assertSchedulerName("quartzScheduler")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java index 88cdf9eb898..df1b07dd23d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceInitializerTests.java @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class QuartzDataSourceInitializerTests { +class QuartzDataSourceInitializerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( @@ -48,7 +48,7 @@ public class QuartzDataSourceInitializerTests { "jdbc:h2:mem:test-%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", UUID.randomUUID().toString())); @Test - public void commentPrefixCanBeCustomized() { + void commentPrefixCanBeCustomized() { this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( "spring.quartz.jdbc.comment-prefix=##", "spring.quartz.jdbc.schema=classpath:org/springframework/boot/autoconfigure/quartz/tables_@@platform@@.sql") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java index c979f46e9b0..d109a238505 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.autoconfigure.rsocket; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class RSocketMessagingAutoConfigurationTests { +class RSocketMessagingAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) @@ -51,7 +51,7 @@ public class RSocketMessagingAutoConfigurationTests { } @Test - public void shouldFailOnMissingStrategies() { + void shouldFailOnMissingStrategies() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) .run((context) -> { assertThat(context).hasFailed(); @@ -61,7 +61,7 @@ public class RSocketMessagingAutoConfigurationTests { } @Test - public void shouldUseCustomMessageHandlerAcceptor() { + void shouldUseCustomMessageHandlerAcceptor() { this.contextRunner.withUserConfiguration(CustomMessageHandlerAcceptor.class) .run((context) -> assertThat(context).getBeanNames(MessageHandlerAcceptor.class) .containsOnly("customMessageHandlerAcceptor")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java index d295a6b0144..8c2cd610bb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java @@ -32,18 +32,18 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class RSocketRequesterAutoConfigurationTests { +class RSocketRequesterAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)); @Test - public void shouldCreateBuilder() { + void shouldCreateBuilder() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RSocketRequester.Builder.class)); } @Test - public void shouldGetPrototypeScopedBean() { + void shouldGetPrototypeScopedBean() { this.contextRunner.run((context) -> { RSocketRequester.Builder first = context.getBean(RSocketRequester.Builder.class); RSocketRequester.Builder second = context.getBean(RSocketRequester.Builder.class); @@ -52,7 +52,7 @@ public class RSocketRequesterAutoConfigurationTests { } @Test - public void shouldNotCreateBuilderIfAlreadyPresent() { + void shouldNotCreateBuilderIfAlreadyPresent() { this.contextRunner.withUserConfiguration(CustomRSocketRequesterBuilder.class).run((context) -> { RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); assertThat(builder).isInstanceOf(MyRSocketRequesterBuilder.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java index 7a3fd5805af..ce1817c7838 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.autoconfigure.rsocket; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.rsocket.server.RSocketServerBootstrap; @@ -38,24 +38,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class RSocketServerAutoConfigurationTests { +class RSocketServerAutoConfigurationTests { @Test - public void shouldNotCreateBeansByDefault() { + void shouldNotCreateBeansByDefault() { ApplicationContextRunner contextRunner = createContextRunner(); contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); } @Test - public void shouldNotCreateDefaultBeansForReactiveWebAppWithoutMapping() { + void shouldNotCreateDefaultBeansForReactiveWebAppWithoutMapping() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); } @Test - public void shouldNotCreateDefaultBeansForReactiveWebAppWithWrongTransport() { + void shouldNotCreateDefaultBeansForReactiveWebAppWithWrongTransport() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); contextRunner .withPropertyValues("spring.rsocket.server.transport=tcp", @@ -65,7 +65,7 @@ public class RSocketServerAutoConfigurationTests { } @Test - public void shouldCreateDefaultBeansForReactiveWebApp() { + void shouldCreateDefaultBeansForReactiveWebApp() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); contextRunner .withPropertyValues("spring.rsocket.server.transport=websocket", @@ -74,7 +74,7 @@ public class RSocketServerAutoConfigurationTests { } @Test - public void shouldCreateDefaultBeansForRSocketServerWhenPortIsSet() { + void shouldCreateDefaultBeansForRSocketServerWhenPortIsSet() { ReactiveWebApplicationContextRunner contextRunner = createReactiveWebContextRunner(); contextRunner.withPropertyValues("spring.rsocket.server.port=0").run((context) -> assertThat(context) .hasSingleBean(RSocketServerFactory.class).hasSingleBean(RSocketServerBootstrap.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java index 5fd8d8ceceb..d30102da1a9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java @@ -17,7 +17,7 @@ package org.springframework.boot.autoconfigure.rsocket; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.rsocket.messaging.RSocketStrategiesCustomizer; @@ -42,14 +42,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class RSocketStrategiesAutoConfigurationTests { +class RSocketStrategiesAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(BaseConfiguration.class) .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class)); @Test - public void shouldCreateDefaultBeans() { + void shouldCreateDefaultBeans() { this.contextRunner.run((context) -> { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); RSocketStrategies strategies = context.getBean(RSocketStrategies.class); @@ -65,7 +65,7 @@ public class RSocketStrategiesAutoConfigurationTests { } @Test - public void shouldUseCustomStrategies() { + void shouldUseCustomStrategies() { this.contextRunner.withUserConfiguration(UserStrategies.class).run((context) -> { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); assertThat(context.getBeanNamesForType(RSocketStrategies.class)).contains("customRSocketStrategies"); @@ -73,7 +73,7 @@ public class RSocketStrategiesAutoConfigurationTests { } @Test - public void shouldUseStrategiesCustomizer() { + void shouldUseStrategiesCustomizer() { this.contextRunner.withUserConfiguration(StrategiesCustomizer.class).run((context) -> { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); RSocketStrategies strategies = context.getBean(RSocketStrategies.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java index bf18eb8bef7..116416d460e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java @@ -52,10 +52,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel */ -public class RSocketWebSocketNettyRouteProviderTests { +class RSocketWebSocketNettyRouteProviderTests { @Test - public void webEndpointsShouldWork() throws Exception { + void webEndpointsShouldWork() throws Exception { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) .withConfiguration( AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java index a834706a51e..09d9c0dd1d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Madhura Bhave */ -public class SecurityPropertiesTests { +class SecurityPropertiesTests { private SecurityProperties security = new SecurityProperties(); @@ -45,19 +45,19 @@ public class SecurityPropertiesTests { } @Test - public void validateDefaultFilterOrderMatchesMetadata() { + void validateDefaultFilterOrderMatchesMetadata() { assertThat(this.security.getFilter().getOrder()).isEqualTo(-100); } @Test - public void filterOrderShouldBind() { + void filterOrderShouldBind() { this.source.put("spring.security.filter.order", "55"); this.binder.bind("spring.security", Bindable.ofInstance(this.security)); assertThat(this.security.getFilter().getOrder()).isEqualTo(55); } @Test - public void userWhenNotConfiguredShouldUseDefaultNameAndGeneratedPassword() { + void userWhenNotConfiguredShouldUseDefaultNameAndGeneratedPassword() { SecurityProperties.User user = this.security.getUser(); assertThat(user.getName()).isEqualTo("user"); assertThat(user.getPassword()).isNotNull(); @@ -66,7 +66,7 @@ public class SecurityPropertiesTests { } @Test - public void userShouldBindProperly() { + void userShouldBindProperly() { this.source.put("spring.security.user.name", "foo"); this.source.put("spring.security.user.password", "password"); this.source.put("spring.security.user.roles", "ADMIN,USER"); @@ -79,7 +79,7 @@ public class SecurityPropertiesTests { } @Test - public void passwordAutogeneratedIfEmpty() { + void passwordAutogeneratedIfEmpty() { this.source.put("spring.security.user.password", ""); this.binder.bind("spring.security", Bindable.ofInstance(this.security)); assertThat(this.security.getUser().isPasswordGenerated()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java index 6b22408abfd..f38ad6c8299 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java @@ -39,10 +39,10 @@ import org.springframework.test.context.ContextConfiguration; */ @ContextConfiguration(classes = JpaUserDetailsTests.Main.class, loader = SpringBootContextLoader.class) @DirtiesContext -public class JpaUserDetailsTests { +class JpaUserDetailsTests { @Test - public void contextLoads() { + void contextLoads() { } public static void main(String[] args) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java index ead7f3c5abf..b02dd6e6ed3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java @@ -24,8 +24,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Provider; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Registration; @@ -49,11 +49,11 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Madhura Bhave * @author Thiago Hirata */ -public class OAuth2ClientPropertiesRegistrationAdapterTests { +class OAuth2ClientPropertiesRegistrationAdapterTests { private MockWebServer server; - @After + @AfterEach public void cleanup() throws Exception { if (this.server != null) { this.server.shutdown(); @@ -61,7 +61,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenUsingDefinedProviderShouldAdapt() { + void getClientRegistrationsWhenUsingDefinedProviderShouldAdapt() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); Provider provider = createProvider(); provider.setUserInfoAuthenticationMethod("form"); @@ -94,7 +94,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenUsingCommonProviderShouldAdapt() { + void getClientRegistrationsWhenUsingCommonProviderShouldAdapt() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); registration.setProvider("google"); @@ -124,7 +124,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenUsingCommonProviderWithOverrideShouldAdapt() { + void getClientRegistrationsWhenUsingCommonProviderWithOverrideShouldAdapt() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.Registration registration = createRegistration("google"); registration.setClientName("clientName"); @@ -154,7 +154,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenUnknownProviderShouldThrowException() { + void getClientRegistrationsWhenUnknownProviderShouldThrowException() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); registration.setProvider("missing"); @@ -165,7 +165,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenProviderNotSpecifiedShouldUseRegistrationId() { + void getClientRegistrationsWhenProviderNotSpecifiedShouldUseRegistrationId() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); registration.setClientId("clientId"); @@ -195,7 +195,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void getClientRegistrationsWhenProviderNotSpecifiedAndUnknownProviderShouldThrowException() { + void getClientRegistrationsWhenProviderNotSpecifiedAndUnknownProviderShouldThrowException() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); properties.getRegistration().put("missing", registration); @@ -205,7 +205,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void oidcProviderConfigurationWhenProviderNotSpecifiedOnRegistration() throws Exception { + void oidcProviderConfigurationWhenProviderNotSpecifiedOnRegistration() throws Exception { Registration login = new OAuth2ClientProperties.Registration(); login.setClientId("clientId"); login.setClientSecret("clientSecret"); @@ -213,7 +213,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void oidcProviderConfigurationWhenProviderSpecifiedOnRegistration() throws Exception { + void oidcProviderConfigurationWhenProviderSpecifiedOnRegistration() throws Exception { OAuth2ClientProperties.Registration login = new Registration(); login.setProvider("okta-oidc"); login.setClientId("clientId"); @@ -222,7 +222,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } @Test - public void oidcProviderConfigurationWithCustomConfigurationOverridesProviderDefaults() throws Exception { + void oidcProviderConfigurationWithCustomConfigurationOverridesProviderDefaults() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java index 283cf9091c8..6b940ff5a31 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java @@ -26,12 +26,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Madhura Bhave * @author Artsiom Yudovin */ -public class OAuth2ClientPropertiesTests { +class OAuth2ClientPropertiesTests { private OAuth2ClientProperties properties = new OAuth2ClientProperties(); @Test - public void clientIdAbsentThrowsException() { + void clientIdAbsentThrowsException() { OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); registration.setClientSecret("secret"); registration.setProvider("google"); @@ -41,7 +41,7 @@ public class OAuth2ClientPropertiesTests { } @Test - public void clientSecretAbsentShouldNotThrowException() { + void clientSecretAbsentShouldNotThrowException() { OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); registration.setClientId("foo"); registration.setProvider("google"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java index a86f8e3f765..ed7426bdeda 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class ReactiveOAuth2ClientAutoConfigurationTests { +class ReactiveOAuth2ClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)); @@ -55,19 +55,19 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration"; @Test - public void autoConfigurationShouldBackOffForServletEnvironments() { + void autoConfigurationShouldBackOffForServletEnvironments() { new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @Test - public void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { + void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test - public void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { + void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") @@ -82,19 +82,19 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { } @Test - public void authorizedClientServiceBeanIsConditionalOnClientRegistrationRepository() { + void authorizedClientServiceBeanIsConditionalOnClientRegistrationRepository() { this.contextRunner .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2AuthorizedClientService.class)); } @Test - public void configurationRegistersAuthorizedClientServiceBean() { + void configurationRegistersAuthorizedClientServiceBean() { this.contextRunner.withUserConfiguration(ReactiveClientRepositoryConfiguration.class).run( (context) -> assertThat(context).hasSingleBean(InMemoryReactiveClientRegistrationRepository.class)); } @Test - public void authorizedClientServiceBeanIsConditionalOnMissingBean() { + void authorizedClientServiceBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); @@ -103,20 +103,20 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { } @Test - public void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() { + void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() { this.contextRunner .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); } @Test - public void configurationRegistersAuthorizedClientRepositoryBean() { + void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class) .run((context) -> assertThat(context) .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); } @Test - public void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { + void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); @@ -125,17 +125,17 @@ public class ReactiveOAuth2ClientAutoConfigurationTests { } @Test - public void autoConfigurationConditionalOnClassFlux() { + void autoConfigurationConditionalOnClassFlux() { assertWhenClassNotPresent(Flux.class); } @Test - public void autoConfigurationConditionalOnClassEnableWebFluxSecurity() { + void autoConfigurationConditionalOnClassEnableWebFluxSecurity() { assertWhenClassNotPresent(EnableWebFluxSecurity.class); } @Test - public void autoConfigurationConditionalOnClassClientRegistration() { + void autoConfigurationConditionalOnClassClientRegistration() { assertWhenClassNotPresent(ClientRegistration.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java index 867a5241f47..ddaf275d2c5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java @@ -29,20 +29,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class OAuth2ClientRegistrationRepositoryConfigurationTests { +class OAuth2ClientRegistrationRepositoryConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration"; @Test - public void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { + void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test - public void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { + void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java index 24c06cfb9bd..650b2a2fd1e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java @@ -55,12 +55,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class OAuth2WebSecurityConfigurationTests { +class OAuth2WebSecurityConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void securityConfigurerConfiguresOAuth2Login() { + void securityConfigurerConfiguresOAuth2Login() { this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class).run((context) -> { ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); @@ -75,7 +75,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void securityConfigurerConfiguresAuthorizationCode() { + void securityConfigurerConfiguresAuthorizationCode() { this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class).run((context) -> { ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); @@ -90,7 +90,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void securityConfigurerBacksOffWhenClientRegistrationBeanAbsent() { + void securityConfigurerBacksOffWhenClientRegistrationBeanAbsent() { this.contextRunner.withUserConfiguration(TestConfig.class, OAuth2WebSecurityConfiguration.class) .run((context) -> { assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); @@ -99,7 +99,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void configurationRegistersAuthorizedClientServiceBean() { + void configurationRegistersAuthorizedClientServiceBean() { this.contextRunner .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class) @@ -107,7 +107,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void configurationRegistersAuthorizedClientRepositoryBean() { + void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class) @@ -115,7 +115,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void securityConfigurerBacksOffWhenOtherWebSecurityAdapterPresent() { + void securityConfigurerBacksOffWhenOtherWebSecurityAdapterPresent() { this.contextRunner .withUserConfiguration(TestWebSecurityConfigurerConfig.class, OAuth2WebSecurityConfiguration.class) .run((context) -> { @@ -126,7 +126,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void authorizedClientServiceBeanIsConditionalOnMissingBean() { + void authorizedClientServiceBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, OAuth2WebSecurityConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); @@ -135,7 +135,7 @@ public class OAuth2WebSecurityConfigurationTests { } @Test - public void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { + void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java index a373612f1f1..1edeea138f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java @@ -25,8 +25,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -61,7 +61,7 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Artsiom Yudovin */ -public class ReactiveOAuth2ResourceServerAutoConfigurationTests { +class ReactiveOAuth2ResourceServerAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) @@ -69,7 +69,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { private MockWebServer server; - @After + @AfterEach public void cleanup() throws Exception { if (this.server != null) { this.server.shutdown(); @@ -77,7 +77,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServer() { + void autoConfigurationShouldConfigureResourceServer() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { @@ -87,7 +87,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws IOException { + void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws IOException { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -101,7 +101,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() { + void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") @@ -112,7 +112,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { + void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") @@ -122,7 +122,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenSetUriKeyLocationIssuerUriPresentShouldUseSetUri() { + void autoConfigurationWhenSetUriKeyLocationIssuerUriPresentShouldUseSetUri() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", @@ -136,7 +136,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { + void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -155,12 +155,12 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenJwkSetUriNullShouldNotFail() { + void autoConfigurationWhenJwkSetUriNullShouldNotFail() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test - public void jwtDecoderBeanIsConditionalOnMissingBean() { + void jwtDecoderBeanIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) @@ -168,7 +168,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void jwtDecoderByIssuerUriBeanIsConditionalOnMissingBean() { + void jwtDecoderByIssuerUriBeanIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") @@ -177,7 +177,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldBeConditionalOnBearerTokenAuthenticationTokenClass() { + void autoConfigurationShouldBeConditionalOnBearerTokenAuthenticationTokenClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) @@ -186,7 +186,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldBeConditionalOnReactiveJwtDecoderClass() { + void autoConfigurationShouldBeConditionalOnReactiveJwtDecoderClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) @@ -195,7 +195,7 @@ public class ReactiveOAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { + void autoConfigurationWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java index ca1baf23b11..1c1840b66fd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java @@ -27,8 +27,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.nimbusds.jose.JWSAlgorithm; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -57,7 +57,7 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Artsiom Yudovin */ -public class OAuth2ResourceServerAutoConfigurationTests { +class OAuth2ResourceServerAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) @@ -65,7 +65,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { private MockWebServer server; - @After + @AfterEach public void cleanup() throws Exception { if (this.server != null) { this.server.shutdown(); @@ -73,7 +73,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServer() { + void autoConfigurationShouldConfigureResourceServer() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { @@ -83,7 +83,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldMatchDefaultJwsAlgorithm() { + void autoConfigurationShouldMatchDefaultJwsAlgorithm() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .run((context) -> { @@ -95,7 +95,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerWithJwsAlgorithm() { + void autoConfigurationShouldConfigureResourceServerWithJwsAlgorithm() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS384") @@ -109,7 +109,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws Exception { + void autoConfigurationShouldConfigureResourceServerUsingOidcIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -123,7 +123,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() throws Exception { + void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -139,7 +139,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { + void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") @@ -149,7 +149,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { + void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", @@ -163,7 +163,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { + void autoConfigurationWhenKeyLocationAndIssuerUriPresentShouldUseIssuerUri() throws Exception { this.server = new MockWebServer(); this.server.start(); String issuer = this.server.url("").toString(); @@ -182,12 +182,12 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationWhenJwkSetUriNullShouldNotFail() { + void autoConfigurationWhenJwkSetUriNullShouldNotFail() { this.contextRunner.run((context) -> assertThat(getBearerTokenFilter(context)).isNull()); } @Test - public void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { + void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) @@ -195,7 +195,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { + void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { this.contextRunner .withPropertyValues( "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") @@ -204,7 +204,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldBeConditionalOnJwtAuthenticationTokenClass() { + void autoConfigurationShouldBeConditionalOnJwtAuthenticationTokenClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) @@ -213,7 +213,7 @@ public class OAuth2ResourceServerAutoConfigurationTests { } @Test - public void autoConfigurationShouldBeConditionalOnJwtDecoderClass() { + void autoConfigurationShouldBeConditionalOnJwtDecoderClass() { this.contextRunner .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") .withUserConfiguration(JwtDecoderConfig.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java index 9ba113965c8..7e891e74bb3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/PathRequestTests.java @@ -25,10 +25,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class PathRequestTests { +class PathRequestTests { @Test - public void toStaticResourcesShouldReturnStaticResourceRequest() { + void toStaticResourcesShouldReturnStaticResourceRequest() { assertThat(PathRequest.toStaticResources()).isInstanceOf(StaticResourceRequest.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java index 381948a130b..a3c002917c5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java @@ -32,19 +32,19 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ReactiveSecurityAutoConfigurationTests { +class ReactiveSecurityAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner(); @Test - public void backsOffWhenWebFilterChainProxyBeanPresent() { + void backsOffWhenWebFilterChainProxyBeanPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) .withUserConfiguration(WebFilterChainProxyConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); } @Test - public void enablesWebFluxSecurity() { + void enablesWebFluxSecurity() { this.contextRunner .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java index 2ff2db5f8af..def96c3b16f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java @@ -43,13 +43,13 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ReactiveUserDetailsServiceAutoConfigurationTests { +class ReactiveUserDetailsServiceAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); @Test - public void configuresADefaultUser() { + void configuresADefaultUser() { this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run((context) -> { ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); @@ -57,7 +57,7 @@ public class ReactiveUserDetailsServiceAutoConfigurationTests { } @Test - public void doesNotConfigureDefaultUserIfUserDetailsServiceAvailable() { + void doesNotConfigureDefaultUserIfUserDetailsServiceAvailable() { this.contextRunner.withUserConfiguration(UserConfig.class, TestSecurityConfiguration.class).run((context) -> { ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNull(); @@ -67,14 +67,14 @@ public class ReactiveUserDetailsServiceAutoConfigurationTests { } @Test - public void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() { + void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() { this.contextRunner.withUserConfiguration(AuthenticationManagerConfig.class, TestSecurityConfiguration.class) .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run(((context) -> { MapReactiveUserDetailsService userDetailsService = context.getBean(MapReactiveUserDetailsService.class); String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)).getPassword(); @@ -83,18 +83,18 @@ public class ReactiveUserDetailsServiceAutoConfigurationTests { } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndRawPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndRawPassword() { testPasswordEncoding(TestSecurityConfiguration.class, "secret", "{noop}secret"); } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndEncodedPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndEncodedPassword() { String password = "{bcrypt}$2a$10$sCBi9fy9814vUPf2ZRbtp.fR5/VgRk2iBFZ.ypu5IyZ28bZgxrVDa"; testPasswordEncoding(TestSecurityConfiguration.class, password, password); } @Test - public void userDetailsServiceWhenPasswordEncoderBeanPresent() { + void userDetailsServiceWhenPasswordEncoderBeanPresent() { testPasswordEncoding(TestConfigWithPasswordEncoder.class, "secret", "secret"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java index 199d8fb16ac..6f6b954d862 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java @@ -43,12 +43,12 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class StaticResourceRequestTests { +class StaticResourceRequestTests { private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE; @Test - public void atCommonLocationsShouldMatchCommonLocations() { + void atCommonLocationsShouldMatchCommonLocations() { ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations(); assertMatcher(matcher).matches("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); @@ -59,7 +59,7 @@ public class StaticResourceRequestTests { } @Test - public void atCommonLocationsWithExcludeShouldNotMatchExcluded() { + void atCommonLocationsWithExcludeShouldNotMatchExcluded() { ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations() .excluding(StaticResourceLocation.CSS); assertMatcher(matcher).doesNotMatch("/css/file.css"); @@ -67,20 +67,20 @@ public class StaticResourceRequestTests { } @Test - public void atLocationShouldMatchLocation() { + void atLocationShouldMatchLocation() { ServerWebExchangeMatcher matcher = this.resourceRequest.at(StaticResourceLocation.CSS); assertMatcher(matcher).matches("/css/file.css"); assertMatcher(matcher).doesNotMatch("/js/file.js"); } @Test - public void atLocationsFromSetWhenSetIsNullShouldThrowException() { + void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) .withMessageContaining("Locations must not be null"); } @Test - public void excludeFromSetWhenSetIsNullShouldThrowException() { + void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) .withMessageContaining("Locations must not be null"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java index a3ffae78632..b4fd17b09fe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/PathRequestTests.java @@ -36,15 +36,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class PathRequestTests { +class PathRequestTests { @Test - public void toStaticResourcesShouldReturnStaticResourceRequest() { + void toStaticResourcesShouldReturnStaticResourceRequest() { assertThat(PathRequest.toStaticResources()).isInstanceOf(StaticResourceRequest.class); } @Test - public void toH2ConsoleShouldMatchH2ConsolePath() { + void toH2ConsoleShouldMatchH2ConsolePath() { RequestMatcher matcher = PathRequest.toH2Console(); assertMatcher(matcher).matches("/h2-console"); assertMatcher(matcher).matches("/h2-console/subpath"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java index 8b8903fbba9..29d090a2919 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java @@ -56,13 +56,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Madhura Bhave */ -public class SecurityAutoConfigurationTests { +class SecurityAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( AutoConfigurations.of(SecurityAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test - public void testWebConfiguration() { + void testWebConfiguration() { this.contextRunner.run((context) -> { assertThat(context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); assertThat(context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(1); @@ -70,7 +70,7 @@ public class SecurityAutoConfigurationTests { } @Test - public void testDefaultFilterOrderWithSecurityAdapter() { + void testDefaultFilterOrderWithSecurityAdapter() { this.contextRunner .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) .run((context) -> assertThat( @@ -79,7 +79,7 @@ public class SecurityAutoConfigurationTests { } @Test - public void testFilterIsNotRegisteredInNonWeb() { + void testFilterIsNotRegisteredInNonWeb() { try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) { customContext.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); @@ -89,20 +89,20 @@ public class SecurityAutoConfigurationTests { } @Test - public void defaultAuthenticationEventPublisherRegistered() { + void defaultAuthenticationEventPublisherRegistered() { this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) .isInstanceOf(DefaultAuthenticationEventPublisher.class)); } @Test - public void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { + void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class) .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); } @Test - public void testDefaultFilterOrder() { + void testDefaultFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .run((context) -> assertThat( context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) @@ -110,7 +110,7 @@ public class SecurityAutoConfigurationTests { } @Test - public void testCustomFilterOrder() { + void testCustomFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .withPropertyValues("spring.security.filter.order:12345") .run((context) -> assertThat( @@ -119,7 +119,7 @@ public class SecurityAutoConfigurationTests { } @Test - public void testJpaCoexistsHappily() { + void testJpaCoexistsHappily() { this.contextRunner .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testsecdb", "spring.datasource.initialization-mode:never") @@ -132,13 +132,13 @@ public class SecurityAutoConfigurationTests { } @Test - public void testSecurityEvaluationContextExtensionSupport() { + void testSecurityEvaluationContextExtensionSupport() { this.contextRunner .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); } @Test - public void defaultFilterDispatcherTypes() { + void defaultFilterDispatcherTypes() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) .run((context) -> { DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", @@ -152,7 +152,7 @@ public class SecurityAutoConfigurationTests { } @Test - public void customFilterDispatcherTypes() { + void customFilterDispatcherTypes() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR") .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java index 4cb70055246..c2aac19b844 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationEarlyInitializationTests.java @@ -52,10 +52,10 @@ import org.springframework.web.bind.annotation.RestController; * @author Phillip Webb */ @ExtendWith(OutputCaptureExtension.class) -public class SecurityFilterAutoConfigurationEarlyInitializationTests { +class SecurityFilterAutoConfigurationEarlyInitializationTests { @Test - public void testSecurityFilterDoesNotCauseEarlyInitialization(CapturedOutput capturedOutput) { + void testSecurityFilterDoesNotCauseEarlyInitialization(CapturedOutput capturedOutput) { try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) { TestPropertyValues.of("server.port:0").applyTo(context); context.register(Config.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java index 69615849188..73f2bd39dfa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfigurationTests.java @@ -39,10 +39,10 @@ import org.springframework.mock.web.MockServletContext; * * @author Andy Wilkinson */ -public class SecurityFilterAutoConfigurationTests { +class SecurityFilterAutoConfigurationTests { @Test - public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() { + void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() { try (AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext()) { context.setServletContext(new MockServletContext()); context.register(Config.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java index 644e5bbdb48..7d303d911bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityRequestMatcherProviderAutoConfigurationTests.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class SecurityRequestMatcherProviderAutoConfigurationTests { +class SecurityRequestMatcherProviderAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)); @Test - public void configurationConditionalOnWebApplication() { + void configurationConditionalOnWebApplication() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) .withUserConfiguration(TestMvcConfiguration.class) @@ -47,7 +47,7 @@ public class SecurityRequestMatcherProviderAutoConfigurationTests { } @Test - public void configurationConditionalOnRequestMatcherClass() { + void configurationConditionalOnRequestMatcherClass() { this.contextRunner .withClassLoader( new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) @@ -55,39 +55,39 @@ public class SecurityRequestMatcherProviderAutoConfigurationTests { } @Test - public void registersMvcRequestMatcherProviderIfMvcPresent() { + void registersMvcRequestMatcherProviderIfMvcPresent() { this.contextRunner.withUserConfiguration(TestMvcConfiguration.class).run((context) -> assertThat(context) .getBean(RequestMatcherProvider.class).isInstanceOf(MvcRequestMatcherProvider.class)); } @Test - public void registersRequestMatcherForJerseyProviderIfJerseyPresentAndMvcAbsent() { + void registersRequestMatcherForJerseyProviderIfJerseyPresentAndMvcAbsent() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) .withUserConfiguration(TestJerseyConfiguration.class).run((context) -> assertThat(context) .getBean(RequestMatcherProvider.class).isInstanceOf(JerseyRequestMatcherProvider.class)); } @Test - public void mvcRequestMatcherProviderConditionalOnDispatcherServletClass() { + void mvcRequestMatcherProviderConditionalOnDispatcherServletClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) .run((context) -> assertThat(context).doesNotHaveBean(MvcRequestMatcherProvider.class)); } @Test - public void jerseyRequestMatcherProviderConditionalOnResourceConfigClass() { + void jerseyRequestMatcherProviderConditionalOnResourceConfigClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.glassfish.jersey.server.ResourceConfig")) .run((context) -> assertThat(context).doesNotHaveBean(JerseyRequestMatcherProvider.class)); } @Test - public void mvcRequestMatcherProviderConditionalOnHandlerMappingIntrospectorBean() { + void mvcRequestMatcherProviderConditionalOnHandlerMappingIntrospectorBean() { new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(MvcRequestMatcherProvider.class)); } @Test - public void jerseyRequestMatcherProviderConditionalOnJerseyApplicationPathBean() { + void jerseyRequestMatcherProviderConditionalOnJerseyApplicationPathBean() { new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SecurityRequestMatcherProviderAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java index 350a8a3b99b..f4f424528d5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java @@ -38,12 +38,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Madhura Bhave * @author Phillip Webb */ -public class StaticResourceRequestTests { +class StaticResourceRequestTests { private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE; @Test - public void atCommonLocationsShouldMatchCommonLocations() { + void atCommonLocationsShouldMatchCommonLocations() { RequestMatcher matcher = this.resourceRequest.atCommonLocations(); assertMatcher(matcher).matches("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); @@ -54,34 +54,34 @@ public class StaticResourceRequestTests { } @Test - public void atCommonLocationsWithExcludeShouldNotMatchExcluded() { + void atCommonLocationsWithExcludeShouldNotMatchExcluded() { RequestMatcher matcher = this.resourceRequest.atCommonLocations().excluding(StaticResourceLocation.CSS); assertMatcher(matcher).doesNotMatch("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); } @Test - public void atLocationShouldMatchLocation() { + void atLocationShouldMatchLocation() { RequestMatcher matcher = this.resourceRequest.at(StaticResourceLocation.CSS); assertMatcher(matcher).matches("/css/file.css"); assertMatcher(matcher).doesNotMatch("/js/file.js"); } @Test - public void atLocationWhenHasServletPathShouldMatchLocation() { + void atLocationWhenHasServletPathShouldMatchLocation() { RequestMatcher matcher = this.resourceRequest.at(StaticResourceLocation.CSS); assertMatcher(matcher, "/foo").matches("/foo", "/css/file.css"); assertMatcher(matcher, "/foo").doesNotMatch("/foo", "/js/file.js"); } @Test - public void atLocationsFromSetWhenSetIsNullShouldThrowException() { + void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) .withMessageContaining("Locations must not be null"); } @Test - public void excludeFromSetWhenSetIsNullShouldThrowException() { + void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) .withMessageContaining("Locations must not be null"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java index 6614102bd2e..cbc3fbe52c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java @@ -53,14 +53,14 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave */ @ExtendWith(OutputCaptureExtension.class) -public class UserDetailsServiceAutoConfigurationTests { +class UserDetailsServiceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestSecurityConfiguration.class) .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); @Test - public void testDefaultUsernamePassword(CapturedOutput capturedOutput) { + void testDefaultUsernamePassword(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { UserDetailsService manager = context.getBean(UserDetailsService.class); assertThat(capturedOutput.toString()).contains("Using generated security password:"); @@ -69,7 +69,7 @@ public class UserDetailsServiceAutoConfigurationTests { } @Test - public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(CapturedOutput capturedOutput) { + void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { AuthenticationManager manager = context.getBean(AuthenticationManager.class); assertThat(manager) @@ -81,7 +81,7 @@ public class UserDetailsServiceAutoConfigurationTests { } @Test - public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(CapturedOutput capturedOutput) { + void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestUserDetailsServiceConfiguration.class).run((context) -> { UserDetailsService userDetailsService = context.getBean(UserDetailsService.class); assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); @@ -90,7 +90,7 @@ public class UserDetailsServiceAutoConfigurationTests { } @Test - public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(CapturedOutput capturedOutput) { + void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestAuthenticationProviderConfiguration.class).run((context) -> { AuthenticationProvider provider = context.getBean(AuthenticationProvider.class); assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); @@ -100,7 +100,7 @@ public class UserDetailsServiceAutoConfigurationTests { } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class).run(((context) -> { InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); String password = userDetailsService.loadUserByUsername("user").getPassword(); @@ -109,29 +109,29 @@ public class UserDetailsServiceAutoConfigurationTests { } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndRawPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndRawPassword() { testPasswordEncoding(TestSecurityConfiguration.class, "secret", "{noop}secret"); } @Test - public void userDetailsServiceWhenPasswordEncoderAbsentAndEncodedPassword() { + void userDetailsServiceWhenPasswordEncoderAbsentAndEncodedPassword() { String password = "{bcrypt}$2a$10$sCBi9fy9814vUPf2ZRbtp.fR5/VgRk2iBFZ.ypu5IyZ28bZgxrVDa"; testPasswordEncoding(TestSecurityConfiguration.class, password, password); } @Test - public void userDetailsServiceWhenPasswordEncoderBeanPresent() { + void userDetailsServiceWhenPasswordEncoderBeanPresent() { testPasswordEncoding(TestConfigWithPasswordEncoder.class, "secret", "secret"); } @Test - public void userDetailsServiceWhenClientRegistrationRepositoryBeanPresent() { + void userDetailsServiceWhenClientRegistrationRepositoryBeanPresent() { this.contextRunner.withUserConfiguration(TestConfigWithClientRegistrationRepository.class) .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } @Test - public void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput capturedOutput) { + void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput capturedOutput) { this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) .run(((context) -> assertThat(capturedOutput.toString()) .doesNotContain("Using generated security password: "))); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index 7642e8d89c6..81a814b3525 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Maciej Walkowiak * @author Patrick Bray */ -public class SendGridAutoConfigurationTests { +class SendGridAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -49,28 +49,28 @@ public class SendGridAutoConfigurationTests { } @Test - public void expectedSendGridBeanCreatedApiKey() { + void expectedSendGridBeanCreatedApiKey() { loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY"); SendGrid sendGrid = this.context.getBean(SendGrid.class); assertThat(sendGrid).extracting("apiKey").containsExactly("SG.SECRET-API-KEY"); } @Test - public void autoConfigurationNotFiredWhenPropertiesNotSet() { + void autoConfigurationNotFiredWhenPropertiesNotSet() { loadContext(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(SendGrid.class)); } @Test - public void autoConfigurationNotFiredWhenBeanAlreadyCreated() { + void autoConfigurationNotFiredWhenBeanAlreadyCreated() { loadContext(ManualSendGridConfiguration.class, "spring.sendgrid.api-key:SG.SECRET-API-KEY"); SendGrid sendGrid = this.context.getBean(SendGrid.class); assertThat(sendGrid).extracting("apiKey").containsExactly("SG.CUSTOM_API_KEY"); } @Test - public void expectedSendGridBeanWithProxyCreated() { + void expectedSendGridBeanWithProxyCreated() { loadContext("spring.sendgrid.api-key:SG.SECRET-API-KEY", "spring.sendgrid.proxy.host:localhost", "spring.sendgrid.proxy.port:5678"); SendGrid sendGrid = this.context.getBean(SendGrid.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java index 561bce13c69..5efd0a3bc45 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/NonUniqueSessionRepositoryFailureAnalyzerTests.java @@ -34,12 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class NonUniqueSessionRepositoryFailureAnalyzerTests { +class NonUniqueSessionRepositoryFailureAnalyzerTests { private final FailureAnalyzer analyzer = new NonUniqueSessionRepositoryFailureAnalyzer(); @Test - public void failureAnalysisWithMultipleCandidates() { + void failureAnalysisWithMultipleCandidates() { FailureAnalysis analysis = analyzeFailure( createFailure(JdbcOperationsSessionRepository.class, HazelcastSessionRepository.class)); assertThat(analysis).isNotNull(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java index 65ba6a2d874..a4185aedfca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java @@ -38,13 +38,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { +class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb") .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -53,7 +53,7 @@ public class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionA } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveRedisOperationsSessionRepository.class)) .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -62,7 +62,7 @@ public class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionA } @Test - public void mongoSessionStoreWithCustomizations() { + void mongoSessionStoreWithCustomizations() { this.contextRunner .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java index 0332c417096..767943a84ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java @@ -38,13 +38,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Vedran Pavic */ -public class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { +class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=redis") .withConfiguration( AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) @@ -52,7 +52,7 @@ public class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionA } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner.withClassLoader(new FilteredClassLoader(ReactiveMongoOperationsSessionRepository.class)) .withConfiguration( AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) @@ -60,7 +60,7 @@ public class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionA } @Test - public void redisSessionStoreWithCustomizations() { + void redisSessionStoreWithCustomizations() { this.contextRunner .withConfiguration( AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java index 47d6d4dbcca..3f8bb15d12a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java @@ -43,19 +43,19 @@ import static org.mockito.Mockito.verify; * * @author Vedran Pavic */ -public class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) .withUserConfiguration(HazelcastConfiguration.class); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast").run(this::validateDefaultConfig); } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(JdbcOperationsSessionRepository.class, RedisOperationsSessionRepository.class, MongoOperationsSessionRepository.class)) @@ -69,7 +69,7 @@ public class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoC } @Test - public void customMapName() { + void customMapName() { this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.map-name=foo:bar:biz").run((context) -> { validateSessionRepository(context, HazelcastSessionRepository.class); @@ -79,7 +79,7 @@ public class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoC } @Test - public void customFlushMode() { + void customFlushMode() { this.contextRunner.withPropertyValues("spring.session.store-type=hazelcast", "spring.session.hazelcast.flush-mode=immediate").run((context) -> { HazelcastSessionRepository repository = validateSessionRepository(context, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java index ad2c73f6734..58cbe08006d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationIntegrationTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class SessionAutoConfigurationIntegrationTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationIntegrationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -45,7 +45,7 @@ public class SessionAutoConfigurationIntegrationTests extends AbstractSessionAut .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test - public void severalCandidatesWithNoSessionStore() { + void severalCandidatesWithNoSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasCauseInstanceOf(NonUniqueSessionRepositoryException.class); @@ -57,7 +57,7 @@ public class SessionAutoConfigurationIntegrationTests extends AbstractSessionAut } @Test - public void severalCandidatesWithWrongSessionStore() { + void severalCandidatesWithWrongSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) .withPropertyValues("spring.session.store-type=redis").run((context) -> { assertThat(context).hasFailed(); @@ -69,7 +69,7 @@ public class SessionAutoConfigurationIntegrationTests extends AbstractSessionAut } @Test - public void severalCandidatesWithValidSessionStore() { + void severalCandidatesWithValidSessionStore() { this.contextRunner.withUserConfiguration(HazelcastConfiguration.class) .withPropertyValues("spring.session.store-type=jdbc") .run((context) -> validateSessionRepository(context, JdbcOperationsSessionRepository.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index 542c6428881..e959fd6842b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Vedran Pavic * @author Stephane Nicoll */ -public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, @@ -53,12 +53,12 @@ public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfig .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=jdbc").run(this::validateDefaultConfig); } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, MongoOperationsSessionRepository.class, RedisOperationsSessionRepository.class)) @@ -78,7 +78,7 @@ public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfig } @Test - public void filterOrderCanBeCustomized() { + void filterOrderCanBeCustomized() { this.contextRunner .withPropertyValues("spring.session.store-type=jdbc", "spring.session.servlet.filter-order=123") .run((context) -> { @@ -88,7 +88,7 @@ public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfig } @Test - public void disableDataSourceInitializer() { + void disableDataSourceInitializer() { this.contextRunner .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") .run((context) -> { @@ -103,7 +103,7 @@ public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfig } @Test - public void customTableName() { + void customTableName() { this.contextRunner .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR", "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") @@ -118,7 +118,7 @@ public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfig } @Test - public void customCleanupCron() { + void customCleanupCron() { this.contextRunner .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.cleanup-cron=0 0 12 * * *") .run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java index 8a7dc3b4094..f0e168406c6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java @@ -38,13 +38,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner.withPropertyValues("spring.session.store-type=mongodb") .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)) @@ -52,7 +52,7 @@ public class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfi } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, JdbcOperationsSessionRepository.class, RedisOperationsSessionRepository.class)) @@ -62,7 +62,7 @@ public class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfi } @Test - public void mongoSessionStoreWithCustomizations() { + void mongoSessionStoreWithCustomizations() { this.contextRunner .withConfiguration(AutoConfigurations.of(EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java index 7d3e9fa838a..b96028db238 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java @@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.session; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; @@ -27,6 +26,7 @@ import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext; import org.springframework.boot.test.context.runner.ContextConsumer; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.boot.testsupport.testcontainers.RedisContainer; import org.springframework.session.data.mongo.MongoOperationsSessionRepository; import org.springframework.session.data.redis.RedisFlushMode; @@ -42,8 +42,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Vedran Pavic */ -@Testcontainers -public class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { +@DisabledWithoutDockerTestcontainers +class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { @Container public static RedisContainer redis = new RedisContainer(); @@ -52,30 +52,32 @@ public class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfi .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void defaultConfig() { + void defaultConfig() { this.contextRunner - .withPropertyValues("spring.session.store-type=redis", "spring.redis.port=" + redis.getMappedPort()) + .withPropertyValues("spring.session.store-type=redis", + "spring.redis.port=" + redis.getFirstMappedPort()) .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", RedisFlushMode.ON_SAVE, "0 * * * * *")); } @Test - public void defaultConfigWithUniqueStoreImplementation() { + void defaultConfigWithUniqueStoreImplementation() { this.contextRunner .withClassLoader(new FilteredClassLoader(HazelcastSessionRepository.class, JdbcOperationsSessionRepository.class, MongoOperationsSessionRepository.class)) .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.redis.port=" + redis.getMappedPort()).run(validateSpringSessionUsesRedis( - "spring:session:event:0:created:", RedisFlushMode.ON_SAVE, "0 * * * * *")); + .withPropertyValues("spring.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesRedis("spring:session:event:0:created:", RedisFlushMode.ON_SAVE, + "0 * * * * *")); } @Test - public void redisSessionStoreWithCustomizations() { + void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", "spring.session.redis.cleanup-cron=0 0 12 * * *", - "spring.redis.port=" + redis.getMappedPort()) + "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", RedisFlushMode.IMMEDIATE, "0 0 12 * * *")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 290d3922b15..ddf54c8c371 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -53,13 +53,13 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Vedran Pavic */ -public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void contextFailsIfMultipleStoresAreAvailable() { + void contextFailsIfMultipleStoresAreAvailable() { this.contextRunner.run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasCauseInstanceOf(NonUniqueSessionRepositoryException.class); @@ -69,7 +69,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void contextFailsIfStoreTypeNotAvailable() { + void contextFailsIfStoreTypeNotAvailable() { this.contextRunner.withPropertyValues("spring.session.store-type=jdbc").run((context) -> { assertThat(context).hasFailed(); assertThat(context).getFailure().hasCauseInstanceOf(SessionRepositoryUnavailableException.class); @@ -79,13 +79,13 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void autoConfigurationDisabledIfStoreTypeSetToNone() { + void autoConfigurationDisabledIfStoreTypeSetToNone() { this.contextRunner.withPropertyValues("spring.session.store-type=none") .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); } @Test - public void backOffIfSessionRepositoryIsPresent() { + void backOffIfSessionRepositoryIsPresent() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("spring.session.store-type=redis").run((context) -> { MapSessionRepository repository = validateSessionRepository(context, MapSessionRepository.class); @@ -94,7 +94,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void autoConfigWhenSpringSessionTimeoutIsSetShouldUseThat() { + void autoConfigWhenSpringSessionTimeoutIsSetShouldUseThat() { this.contextRunner .withUserConfiguration(ServerPropertiesConfiguration.class, SessionRepositoryConfiguration.class) .withPropertyValues("server.servlet.session.timeout=1", "spring.session.timeout=3") @@ -103,7 +103,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void autoConfigWhenSpringSessionTimeoutIsNotSetShouldUseServerSessionTimeout() { + void autoConfigWhenSpringSessionTimeoutIsNotSetShouldUseServerSessionTimeout() { this.contextRunner .withUserConfiguration(ServerPropertiesConfiguration.class, SessionRepositoryConfiguration.class) .withPropertyValues("server.servlet.session.timeout=3") @@ -113,7 +113,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @SuppressWarnings("unchecked") @Test - public void filterIsRegisteredWithAsyncErrorAndRequestDispatcherTypes() { + void filterIsRegisteredWithAsyncErrorAndRequestDispatcherTypes() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class).run((context) -> { FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isSameAs(context.getBean(SessionRepositoryFilter.class)); @@ -123,7 +123,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void filterOrderCanBeCustomizedWithCustomStore() { + void filterOrderCanBeCustomizedWithCustomStore() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("spring.session.servlet.filter-order=123").run((context) -> { FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); @@ -133,7 +133,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @SuppressWarnings("unchecked") @Test - public void filterDispatcherTypesCanBeCustomized() { + void filterDispatcherTypesCanBeCustomized() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request").run((context) -> { FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); @@ -143,7 +143,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { + void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("server.servlet.session.cookie.name=sid", "server.servlet.session.cookie.domain=spring", "server.servlet.session.cookie.path=/test", @@ -161,7 +161,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void autoConfiguredCookieSerializerIsUsedBySessionRepositoryFilter() { + void autoConfiguredCookieSerializerIsUsedBySessionRepositoryFilter() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) .withPropertyValues("server.port=0").run((context) -> { SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); @@ -174,7 +174,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresACookieSerializer() { + void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresACookieSerializer() { this.contextRunner.withUserConfiguration(UserProvidedCookieSerializerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(DefaultCookieSerializer.class); assertThat(context).hasBean("myCookieSerializer"); @@ -182,25 +182,25 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat } @Test - public void cookiesSerializerIsAutoConfiguredWhenUserConfiguresCookieHttpSessionIdResolver() { + void cookiesSerializerIsAutoConfiguredWhenUserConfiguresCookieHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCookieHttpSessionStrategyConfiguration.class) .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); } @Test - public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresHeaderHttpSessionIdResolver() { + void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresHeaderHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedHeaderHttpSessionStrategyConfiguration.class) .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test - public void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresCustomHttpSessionIdResolver() { + void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresCustomHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCustomHttpSessionStrategyConfiguration.class) .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test - public void autoConfiguredCookieSerializerIsConfiguredWithRememberMeRequestAttribute() { + void autoConfiguredCookieSerializerIsConfiguredWithRememberMeRequestAttribute() { this.contextRunner.withBean(SpringSessionRememberMeServicesConfiguration.class).run((context) -> { DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); assertThat(cookieSerializer).hasFieldOrPropertyWithValue("rememberMeRequestAttribute", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java index 20f8f8928bf..ef25b48f8f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java @@ -54,13 +54,13 @@ import static org.mockito.Mockito.verify; * @author Camille Vienot */ @ExtendWith(OutputCaptureExtension.class) -public class TaskExecutionAutoConfigurationTests { +class TaskExecutionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); @Test - public void taskExecutorBuilderShouldApplyCustomSettings() { + void taskExecutorBuilderShouldApplyCustomSettings() { this.contextRunner.withPropertyValues("spring.task.execution.pool.queue-capacity=10", "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", "spring.task.execution.pool.allow-core-thread-timeout=true", "spring.task.execution.pool.keep-alive=5s", @@ -79,7 +79,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void taskExecutorBuilderWhenHasCustomBuilderShouldUseCustomBuilder() { + void taskExecutorBuilderWhenHasCustomBuilderShouldUseCustomBuilder() { this.contextRunner.withUserConfiguration(CustomTaskExecutorBuilderConfig.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutorBuilder.class); assertThat(context.getBean(TaskExecutorBuilder.class)) @@ -88,7 +88,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void taskExecutorBuilderShouldUseTaskDecorator() { + void taskExecutorBuilderShouldUseTaskDecorator() { this.contextRunner.withUserConfiguration(TaskDecoratorConfig.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutorBuilder.class); ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build(); @@ -98,7 +98,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void taskExecutorAutoConfigured(CapturedOutput capturedOutput) { + void taskExecutorAutoConfigured(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { assertThat(capturedOutput).doesNotContain("Initializing ExecutorService"); assertThat(context).hasSingleBean(Executor.class); @@ -109,7 +109,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void taskExecutorWhenHasCustomTaskExecutorShouldBackOff() { + void taskExecutorWhenHasCustomTaskExecutorShouldBackOff() { this.contextRunner.withUserConfiguration(CustomTaskExecutorConfig.class).run((context) -> { assertThat(context).hasSingleBean(Executor.class); assertThat(context.getBean(Executor.class)).isSameAs(context.getBean("customTaskExecutor")); @@ -117,7 +117,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void taskExecutorBuilderShouldApplyCustomizer() { + void taskExecutorBuilderShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(TaskExecutorCustomizerConfig.class).run((context) -> { TaskExecutorCustomizer customizer = context.getBean(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build(); @@ -126,7 +126,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void enableAsyncUsesAutoConfiguredOneByDefault() { + void enableAsyncUsesAutoConfiguredOneByDefault() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") .withUserConfiguration(AsyncConfiguration.class, TestBean.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutor.class); @@ -137,7 +137,7 @@ public class TaskExecutionAutoConfigurationTests { } @Test - public void enableAsyncUsesAutoConfiguredOneByDefaultEvenThoughSchedulingIsConfigured() { + void enableAsyncUsesAutoConfiguredOneByDefaultEvenThoughSchedulingIsConfigured() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java index 143193ea2e7..ccb8994d3a9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java @@ -45,19 +45,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class TaskSchedulingAutoConfigurationTests { +class TaskSchedulingAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfiguration.class) .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); @Test - public void noSchedulingDoesNotExposeTaskScheduler() { + void noSchedulingDoesNotExposeTaskScheduler() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(TaskScheduler.class)); } @Test - public void enableSchedulingWithNoTaskExecutorAutoConfiguresOne() { + void enableSchedulingWithNoTaskExecutorAutoConfiguresOne() { this.contextRunner .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", "spring.task.scheduling.shutdown.await-termination-period=30s", @@ -74,7 +74,7 @@ public class TaskSchedulingAutoConfigurationTests { } @Test - public void enableSchedulingWithNoTaskExecutorAppliesCustomizers() { + void enableSchedulingWithNoTaskExecutorAppliesCustomizers() { this.contextRunner.withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) .run((context) -> { @@ -86,7 +86,7 @@ public class TaskSchedulingAutoConfigurationTests { } @Test - public void enableSchedulingWithExistingTaskSchedulerBacksOff() { + void enableSchedulingWithExistingTaskSchedulerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(TaskScheduler.class); @@ -98,7 +98,7 @@ public class TaskSchedulingAutoConfigurationTests { } @Test - public void enableSchedulingWithExistingScheduledExecutorServiceBacksOff() { + void enableSchedulingWithExistingScheduledExecutorServiceBacksOff() { this.contextRunner .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) .run((context) -> { @@ -111,7 +111,7 @@ public class TaskSchedulingAutoConfigurationTests { } @Test - public void enableSchedulingWithConfigurerBacksOff() { + void enableSchedulingWithConfigurerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, SchedulingConfigurerConfiguration.class) .run((context) -> { assertThat(context).doesNotHaveBean(TaskScheduler.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index c747f10fdd1..c85a761775b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -40,7 +40,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class TemplateAvailabilityProvidersTests { +class TemplateAvailabilityProvidersTests { private TemplateAvailabilityProviders providers; @@ -63,14 +63,14 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void createWhenApplicationContextIsNullShouldThrowException() { + void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) .withMessageContaining("ClassLoader must not be null"); } @Test - public void createWhenUsingApplicationContextShouldLoadProviders() { + void createWhenUsingApplicationContextShouldLoadProviders() { ApplicationContext applicationContext = mock(ApplicationContext.class); given(applicationContext.getClassLoader()).willReturn(this.classLoader); TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext); @@ -79,39 +79,39 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void createWhenClassLoaderIsNullShouldThrowException() { + void createWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) .withMessageContaining("ClassLoader must not be null"); } @Test - public void createWhenUsingClassLoaderShouldLoadProviders() { + void createWhenUsingClassLoaderShouldLoadProviders() { TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(this.classLoader); assertThat(providers.getProviders()).isNotEmpty(); } @Test - public void createWhenProvidersIsNullShouldThrowException() { + void createWhenProvidersIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) .withMessageContaining("Providers must not be null"); } @Test - public void createWhenUsingProvidersShouldUseProviders() { + void createWhenUsingProvidersShouldUseProviders() { TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( Collections.singleton(this.provider)); assertThat(providers.getProviders()).containsOnly(this.provider); } @Test - public void getProviderWhenApplicationContextIsNullShouldThrowException() { + void getProviderWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null)) .withMessageContaining("ApplicationContext must not be null"); } @Test - public void getProviderWhenViewIsNullShouldThrowException() { + void getProviderWhenViewIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) @@ -119,28 +119,28 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderWhenEnvironmentIsNullShouldThrowException() { + void getProviderWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) .withMessageContaining("Environment must not be null"); } @Test - public void getProviderWhenClassLoaderIsNullShouldThrowException() { + void getProviderWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) .withMessageContaining("ClassLoader must not be null"); } @Test - public void getProviderWhenResourceLoaderIsNullShouldThrowException() { + void getProviderWhenResourceLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) .withMessageContaining("ResourceLoader must not be null"); } @Test - public void getProviderWhenNoneMatchShouldReturnNull() { + void getProviderWhenNoneMatchShouldReturnNull() { TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); assertThat(found).isNull(); @@ -148,7 +148,7 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderWhenMatchShouldReturnProvider() { + void getProviderWhenMatchShouldReturnProvider() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) .willReturn(true); TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, @@ -158,7 +158,7 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderShouldCacheMatchResult() { + void getProviderShouldCacheMatchResult() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) .willReturn(true); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); @@ -168,7 +168,7 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderShouldCacheNoMatchResult() { + void getProviderShouldCacheNoMatchResult() { this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, @@ -176,7 +176,7 @@ public class TemplateAvailabilityProvidersTests { } @Test - public void getProviderWhenCacheDisabledShouldNotUseCache() { + void getProviderWhenCacheDisabledShouldNotUseCache() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) .willReturn(true); this.environment.setProperty("spring.template.provider.cache", "false"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java index 2535be704b9..41f9b66ef66 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java @@ -29,29 +29,29 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ViewResolverPropertiesTests { +class ViewResolverPropertiesTests { @Test - public void defaultContentType() { + void defaultContentType() { assertThat(new ViewResolverProperties().getContentType()).hasToString("text/html;charset=UTF-8"); } @Test - public void customContentTypeDefaultCharset() { + void customContentTypeDefaultCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain")); assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-8"); } @Test - public void defaultContentTypeCustomCharset() { + void defaultContentTypeCustomCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setCharset(StandardCharsets.UTF_16); assertThat(properties.getContentType()).hasToString("text/html;charset=UTF-16"); } @Test - public void customContentTypeCustomCharset() { + void customContentTypeCustomCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain")); properties.setCharset(StandardCharsets.UTF_16); @@ -59,7 +59,7 @@ public class ViewResolverPropertiesTests { } @Test - public void customContentTypeWithPropertyAndCustomCharset() { + void customContentTypeWithPropertyAndCustomCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain;foo=bar")); properties.setCharset(StandardCharsets.UTF_16); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java index c51f1e0da61..7f656a5f67e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @ExtendWith(OutputCaptureExtension.class) -public class ThymeleafReactiveAutoConfigurationTests { +class ThymeleafReactiveAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); @@ -67,7 +67,7 @@ public class ThymeleafReactiveAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.contextRunner.withPropertyValues("spring.thymeleaf.suffix:.html").run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -77,7 +77,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void overrideCharacterEncoding() { + void overrideCharacterEncoding() { this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16").run((context) -> { ITemplateResolver resolver = context.getBean(ITemplateResolver.class); assertThat(resolver).isInstanceOf(SpringResourceTemplateResolver.class); @@ -88,28 +88,28 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void overrideMediaTypes() { + void overrideMediaTypes() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain").run( (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) .contains(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); } @Test - public void overrideTemplateResolverOrder() { + void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) .isEqualTo(Integer.valueOf(25))); } @Test - public void overrideViewNames() { + void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) .isEqualTo(new String[] { "foo", "bar" })); } @Test - public void overrideMaxChunkSize() { + void overrideMaxChunkSize() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.maxChunkSize:8KB") .run((context) -> assertThat( context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) @@ -117,35 +117,35 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void overrideFullModeViewNames() { + void overrideFullModeViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar").run( (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) .isEqualTo(new String[] { "foo", "bar" })); } @Test - public void overrideChunkedModeViewNames() { + void overrideChunkedModeViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar").run( (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) .isEqualTo(new String[] { "foo", "bar" })); } @Test - public void overrideEnableSpringElCompiler() { + void overrideEnableSpringElCompiler() { this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true").run( (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) .isTrue()); } @Test - public void enableSpringElCompilerIsDisabledByDefault() { + void enableSpringElCompilerIsDisabledByDefault() { this.contextRunner.run( (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) .isFalse()); } @Test - public void overrideRenderHiddenMarkersBeforeCheckboxes() { + void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") .run((context) -> assertThat( context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) @@ -153,26 +153,26 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { + void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); } @Test - public void templateLocationDoesNotExist(CapturedOutput capturedOutput) { + void templateLocationDoesNotExist(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") .run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); } @Test - public void templateLocationEmpty(CapturedOutput capturedOutput) { + void templateLocationEmpty(CapturedOutput capturedOutput) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } @Test - public void useDataDialect() { + void useDataDialect() { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -182,7 +182,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void useJava8TimeDialect() { + void useJava8TimeDialect() { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); Context attrs = new Context(Locale.UK); @@ -192,7 +192,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void useSecurityDialect() { + void useSecurityDialect() { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); @@ -205,7 +205,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void renderTemplate() { + void renderTemplate() { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -215,7 +215,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Test - public void layoutDialectCanBeCustomized() { + void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) .run((context) -> assertThat( ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java index 5fc1551d061..ed9445860ac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java @@ -26,8 +26,8 @@ import javax.servlet.DispatcherType; import nz.net.ultraq.thymeleaf.LayoutDialect; import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingRespectLayoutTitleStrategy; -import org.junit.Rule; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.context.WebContext; @@ -41,7 +41,8 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter; @@ -59,8 +60,6 @@ import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; import org.springframework.web.servlet.support.RequestContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; /** * Tests for {@link ThymeleafAutoConfiguration} in Servlet-based applications. @@ -72,10 +71,8 @@ import static org.hamcrest.Matchers.not; * @author Kazuki Shimizu * @author Artsiom Yudovin */ -public class ThymeleafServletAutoConfigurationTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class ThymeleafServletAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); @@ -83,13 +80,13 @@ public class ThymeleafServletAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test - public void autoConfigurationBackOffWithoutThymeleafSpring() { + void autoConfigurationBackOffWithoutThymeleafSpring() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.thymeleaf.spring5")) .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); } @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:") .run((context) -> { assertThat(context).hasSingleBean(TemplateEngine.class); @@ -101,7 +98,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void overrideCharacterEncoding() { + void overrideCharacterEncoding() { this.contextRunner.withPropertyValues("spring.thymeleaf.encoding:UTF-16").run((context) -> { ITemplateResolver resolver = context.getBean(ITemplateResolver.class); assertThat(resolver).isInstanceOf(SpringResourceTemplateResolver.class); @@ -113,7 +110,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void overrideDisableProducePartialOutputWhileProcessing() { + void overrideDisableProducePartialOutputWhileProcessing() { this.contextRunner.withPropertyValues("spring.thymeleaf.servlet.produce-partial-output-while-processing:false") .run((context) -> assertThat( context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) @@ -121,67 +118,67 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void disableProducePartialOutputWhileProcessingIsEnabledByDefault() { + void disableProducePartialOutputWhileProcessingIsEnabledByDefault() { this.contextRunner.run((context) -> assertThat( context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()).isTrue()); } @Test - public void overrideTemplateResolverOrder() { + void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) .isEqualTo(Integer.valueOf(25))); } @Test - public void overrideViewNames() { + void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) .isEqualTo(new String[] { "foo", "bar" })); } @Test - public void overrideEnableSpringElCompiler() { + void overrideEnableSpringElCompiler() { this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) .isTrue()); } @Test - public void enableSpringElCompilerIsDisabledByDefault() { + void enableSpringElCompilerIsDisabledByDefault() { this.contextRunner .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) .isFalse()); } @Test - public void overrideRenderHiddenMarkersBeforeCheckboxes() { + void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") .run((context) -> assertThat( context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); } @Test - public void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { + void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); } @Test - public void templateLocationDoesNotExist() { + void templateLocationDoesNotExist(CapturedOutput capturedOutput) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> this.output.expect(containsString("Cannot find template location"))); + .run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); } @Test - public void templateLocationEmpty() { + void templateLocationEmpty(CapturedOutput capturedOutput) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> this.output.expect(not(containsString("Cannot find template location")))); + .run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); } @Test - public void createLayoutFromConfigClass() { + void createLayoutFromConfigClass() { this.contextRunner.run((context) -> { ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class).resolveViewName("view", Locale.UK); @@ -197,7 +194,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void useDataDialect() { + void useDataDialect() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -207,7 +204,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void useJava8TimeDialect() { + void useJava8TimeDialect() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK); @@ -217,7 +214,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void useSecurityDialect() { + void useSecurityDialect() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); WebContext attrs = new WebContext(new MockHttpServletRequest(), new MockHttpServletResponse(), @@ -235,7 +232,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void renderTemplate() { + void renderTemplate() { this.contextRunner.run((context) -> { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); @@ -245,7 +242,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void renderNonWebAppTemplate() { + void renderNonWebAppTemplate() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)) .run((context) -> { assertThat(context).doesNotHaveBean(ViewResolver.class); @@ -257,12 +254,12 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void registerResourceHandlingFilterDisabledByDefault() { + void registerResourceHandlingFilterDisabledByDefault() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); } @Test - public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { + void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class); @@ -273,7 +270,7 @@ public class ThymeleafServletAutoConfigurationTests { @Test @SuppressWarnings("rawtypes") - public void registerResourceHandlingFilterWithOtherRegistrationBean() { + void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 this.contextRunner.withUserConfiguration(FilterRegistrationOtherConfiguration.class) .withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { @@ -288,7 +285,7 @@ public class ThymeleafServletAutoConfigurationTests { @Test @SuppressWarnings("rawtypes") - public void registerResourceHandlingFilterWithResourceRegistrationBean() { + void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 this.contextRunner.withUserConfiguration(FilterRegistrationResourceConfiguration.class) .withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { @@ -302,7 +299,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void layoutDialectCanBeCustomized() { + void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) .run((context) -> assertThat( ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) @@ -310,7 +307,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Test - public void cachingCanBeDisabled() { + void cachingCanBeDisabled() { this.contextRunner.withPropertyValues("spring.thymeleaf.cache:false").run((context) -> { assertThat(context.getBean(ThymeleafViewResolver.class).isCache()).isFalse(); SpringResourceTemplateResolver templateResolver = context.getBean(SpringResourceTemplateResolver.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index af7c1706fcb..bc900721d2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ThymeleafTemplateAvailabilityProviderTests { +class ThymeleafTemplateAvailabilityProviderTests { private final TemplateAvailabilityProvider provider = new ThymeleafTemplateAvailabilityProvider(); @@ -39,26 +39,26 @@ public class ThymeleafTemplateAvailabilityProviderTests { private final MockEnvironment environment = new MockEnvironment(); @Test - public void availabilityOfTemplateInDefaultLocation() { + void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateThatDoesNotExist() { + void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test - public void availabilityOfTemplateWithCustomPrefix() { + void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test - public void availabilityOfTemplateWithCustomSuffix() { + void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), this.resourceLoader)).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index 9969859b2ee..1788eb62faf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -49,7 +49,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class TransactionAutoConfigurationTests { +class TransactionAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -61,13 +61,13 @@ public class TransactionAutoConfigurationTests { } @Test - public void noTransactionManager() { + void noTransactionManager() { load(EmptyConfiguration.class); assertThat(this.context.getBeansOfType(TransactionTemplate.class)).isEmpty(); } @Test - public void singleTransactionManager() { + void singleTransactionManager() { load(new Class[] { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class }, "spring.datasource.initialization-mode:never"); PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.class); @@ -76,13 +76,13 @@ public class TransactionAutoConfigurationTests { } @Test - public void severalTransactionManagers() { + void severalTransactionManagers() { load(SeveralTransactionManagersConfiguration.class); assertThat(this.context.getBeansOfType(TransactionTemplate.class)).isEmpty(); } @Test - public void customTransactionManager() { + void customTransactionManager() { load(CustomTransactionManagerConfiguration.class); Map beans = this.context.getBeansOfType(TransactionTemplate.class); assertThat(beans).hasSize(1); @@ -90,7 +90,7 @@ public class TransactionAutoConfigurationTests { } @Test - public void platformTransactionManagerCustomizers() { + void platformTransactionManagerCustomizers() { load(SeveralTransactionManagersConfiguration.class); TransactionManagerCustomizers customizers = this.context.getBean(TransactionManagerCustomizers.class); List field = (List) ReflectionTestUtils.getField(customizers, "customizers"); @@ -98,20 +98,20 @@ public class TransactionAutoConfigurationTests { } @Test - public void transactionNotManagedWithNoTransactionManager() { + void transactionNotManagedWithNoTransactionManager() { load(BaseConfiguration.class); assertThat(this.context.getBean(TransactionalService.class).isTransactionActive()).isFalse(); } @Test - public void transactionManagerUsesCglibByDefault() { + void transactionManagerUsesCglibByDefault() { load(TransactionManagersConfiguration.class); assertThat(this.context.getBean(AnotherServiceImpl.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(1); } @Test - public void transactionManagerCanBeConfiguredToJdkProxy() { + void transactionManagerCanBeConfiguredToJdkProxy() { load(TransactionManagersConfiguration.class, "spring.aop.proxy-target-class=false"); assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(this.context.getBeansOfType(AnotherServiceImpl.class)).hasSize(0); @@ -119,7 +119,7 @@ public class TransactionAutoConfigurationTests { } @Test - public void customEnableTransactionManagementTakesPrecedence() { + void customEnableTransactionManagementTakesPrecedence() { load(new Class[] { CustomTransactionManagementConfiguration.class, TransactionManagersConfiguration.class }, "spring.aop.proxy-target-class=true"); assertThat(this.context.getBean(AnotherService.class).isTransactionActive()).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java index 75e407df9cc..32f9c7fac05 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizersTests.java @@ -32,15 +32,15 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class TransactionManagerCustomizersTests { +class TransactionManagerCustomizersTests { @Test - public void customizeWithNullCustomizersShouldDoNothing() { + void customizeWithNullCustomizersShouldDoNothing() { new TransactionManagerCustomizers(null).customize(mock(PlatformTransactionManager.class)); } @Test - public void customizeShouldCheckGeneric() { + void customizeShouldCheckGeneric() { List> list = new ArrayList<>(); list.add(new TestCustomizer<>()); list.add(new TestJtaCustomizer()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index 8fc29762798..471259abde0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -71,7 +71,7 @@ import static org.mockito.Mockito.mock; * @author Kazuki Shimizu * @author Nishant Raut */ -public class JtaAutoConfigurationTests { +class JtaAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -83,7 +83,7 @@ public class JtaAutoConfigurationTests { } @Test - public void customPlatformTransactionManager() { + void customPlatformTransactionManager() { this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) @@ -91,7 +91,7 @@ public class JtaAutoConfigurationTests { } @Test - public void disableJtaSupport() { + void disableJtaSupport() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.jta.enabled:false").applyTo(this.context); this.context.register(JtaAutoConfiguration.class); @@ -102,7 +102,7 @@ public class JtaAutoConfigurationTests { } @Test - public void atomikosSanityCheck() { + void atomikosSanityCheck() { this.context = new AnnotationConfigApplicationContext(JtaProperties.class, AtomikosJtaConfiguration.class); this.context.getBean(AtomikosProperties.class); this.context.getBean(UserTransactionService.class); @@ -115,7 +115,7 @@ public class JtaAutoConfigurationTests { } @Test - public void bitronixSanityCheck() { + void bitronixSanityCheck() { this.context = new AnnotationConfigApplicationContext(JtaProperties.class, BitronixJtaConfiguration.class); this.context.getBean(bitronix.tm.Configuration.class); this.context.getBean(TransactionManager.class); @@ -126,14 +126,14 @@ public class JtaAutoConfigurationTests { } @Test - public void defaultBitronixServerId() throws UnknownHostException { + void defaultBitronixServerId() throws UnknownHostException { this.context = new AnnotationConfigApplicationContext(BitronixJtaConfiguration.class); String serverId = this.context.getBean(bitronix.tm.Configuration.class).getServerId(); assertThat(serverId).isEqualTo(InetAddress.getLocalHost().getHostAddress()); } @Test - public void customBitronixServerId() { + void customBitronixServerId() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.jta.transactionManagerId:custom").applyTo(this.context); this.context.register(BitronixJtaConfiguration.class); @@ -143,7 +143,7 @@ public class JtaAutoConfigurationTests { } @Test - public void defaultAtomikosTransactionManagerName(@TempDir Path dir) throws IOException { + void defaultAtomikosTransactionManagerName(@TempDir Path dir) throws IOException { this.context = new AnnotationConfigApplicationContext(); File logs = new File(dir.toFile(), "jta"); TestPropertyValues.of("spring.jta.logDir:" + logs.getAbsolutePath()).applyTo(this.context); @@ -155,7 +155,7 @@ public class JtaAutoConfigurationTests { } @Test - public void atomikosConnectionFactoryPoolConfiguration() { + void atomikosConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.jta.atomikos.connectionfactory.minPoolSize:5", "spring.jta.atomikos.connectionfactory.maxPoolSize:10").applyTo(this.context); @@ -167,7 +167,7 @@ public class JtaAutoConfigurationTests { } @Test - public void bitronixConnectionFactoryPoolConfiguration() { + void bitronixConnectionFactoryPoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("spring.jta.bitronix.connectionfactory.minPoolSize:5", "spring.jta.bitronix.connectionfactory.maxPoolSize:10").applyTo(this.context); @@ -179,7 +179,7 @@ public class JtaAutoConfigurationTests { } @Test - public void atomikosDataSourcePoolConfiguration() { + void atomikosDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.jta.atomikos.datasource.minPoolSize:5", "spring.jta.atomikos.datasource.maxPoolSize:10") @@ -192,7 +192,7 @@ public class JtaAutoConfigurationTests { } @Test - public void bitronixDataSourcePoolConfiguration() { + void bitronixDataSourcePoolConfiguration() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.jta.bitronix.datasource.minPoolSize:5", "spring.jta.bitronix.datasource.maxPoolSize:10") @@ -205,7 +205,7 @@ public class JtaAutoConfigurationTests { } @Test - public void atomikosCustomizeJtaTransactionManagerUsingProperties() { + void atomikosCustomizeJtaTransactionManagerUsingProperties() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") @@ -218,7 +218,7 @@ public class JtaAutoConfigurationTests { } @Test - public void bitronixCustomizeJtaTransactionManagerUsingProperties() { + void bitronixCustomizeJtaTransactionManagerUsingProperties() { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.transaction.default-timeout:30", "spring.transaction.rollback-on-commit-failure:true") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 0afca31c598..1ed3a532b16 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Phillip Webb */ -public class ValidationAutoConfigurationTests { +class ValidationAutoConfigurationTests { private AnnotationConfigApplicationContext context; @@ -63,7 +63,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationShouldConfigureDefaultValidator() { + void validationAutoConfigurationShouldConfigureDefaultValidator() { load(Config.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -79,7 +79,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationWhenUserProvidesValidatorShouldBackOff() { + void validationAutoConfigurationWhenUserProvidesValidatorShouldBackOff() { load(UserDefinedValidatorConfig.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -95,7 +95,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationWhenUserProvidesDefaultValidatorShouldNotEnablePrimary() { + void validationAutoConfigurationWhenUserProvidesDefaultValidatorShouldNotEnablePrimary() { load(UserDefinedDefaultValidatorConfig.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -106,7 +106,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationWhenUserProvidesJsrValidatorShouldBackOff() { + void validationAutoConfigurationWhenUserProvidesJsrValidatorShouldBackOff() { load(UserDefinedJsrValidatorConfig.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -117,7 +117,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationWhenUserProvidesSpringValidatorShouldCreateJsrValidator() { + void validationAutoConfigurationWhenUserProvidesSpringValidatorShouldCreateJsrValidator() { load(UserDefinedSpringValidatorConfig.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -134,7 +134,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationAutoConfigurationWhenUserProvidesPrimarySpringValidatorShouldRemovePrimaryFlag() { + void validationAutoConfigurationWhenUserProvidesPrimarySpringValidatorShouldRemovePrimaryFlag() { load(UserDefinedPrimarySpringValidatorConfig.class); String[] jsrValidatorNames = this.context.getBeanNamesForType(Validator.class); String[] springValidatorNames = this.context @@ -151,7 +151,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationIsEnabled() { + void validationIsEnabled() { load(SampleService.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); SampleService service = this.context.getBean(SampleService.class); @@ -160,7 +160,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationUsesCglibProxy() { + void validationUsesCglibProxy() { load(DefaultAnotherSampleService.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); DefaultAnotherSampleService service = this.context.getBean(DefaultAnotherSampleService.class); @@ -169,7 +169,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void validationCanBeConfiguredToUseJdkProxy() { + void validationCanBeConfiguredToUseJdkProxy() { load(AnotherSampleServiceConfiguration.class, "spring.aop.proxy-target-class=false"); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); assertThat(this.context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); @@ -179,7 +179,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void userDefinedMethodValidationPostProcessorTakesPrecedence() { + void userDefinedMethodValidationPostProcessorTakesPrecedence() { load(SampleConfiguration.class); assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); Object userMethodValidationPostProcessor = this.context.getBean("testMethodValidationPostProcessor"); @@ -191,7 +191,7 @@ public class ValidationAutoConfigurationTests { } @Test - public void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { + void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { load(CustomValidatorConfiguration.class); assertThat(this.context.getBean(TestBeanPostProcessor.class).postProcessed).contains("someService"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index 6bb161ee81c..502f1c1777b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.validation; import javax.validation.Validator; +import org.junit.After; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; @@ -41,7 +41,7 @@ public class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests private AnnotationConfigApplicationContext context; - @AfterEach + @After public void close() { if (this.context != null) { this.context.close(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index f7711adb541..b25bf16389c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.validation; import javax.validation.Validator; +import org.junit.After; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; @@ -40,7 +40,7 @@ public class ValidationAutoConfigurationWithoutValidatorTests { private AnnotationConfigApplicationContext context; - @AfterEach + @After public void close() { if (this.context != null) { this.context.close(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java index 6ac78a28ff8..46df5bd7a82 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java @@ -44,12 +44,12 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Madhura Bhave */ -public class ValidatorAdapterTests { +class ValidatorAdapterTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void wrapLocalValidatorFactoryBean() { + void wrapLocalValidatorFactoryBean() { this.contextRunner.withUserConfiguration(LocalValidatorFactoryBeanConfig.class).run((context) -> { ValidatorAdapter wrapper = context.getBean(ValidatorAdapter.class); assertThat(wrapper.supports(SampleData.class)).isTrue(); @@ -60,7 +60,7 @@ public class ValidatorAdapterTests { } @Test - public void wrapperInvokesCallbackOnNonManagedBean() { + void wrapperInvokesCallbackOnNonManagedBean() { this.contextRunner.withUserConfiguration(NonManagedBeanConfig.class).run((context) -> { LocalValidatorFactoryBean validator = context.getBean(NonManagedBeanConfig.class).validator; verify(validator, times(1)).setApplicationContext(any(ApplicationContext.class)); @@ -72,7 +72,7 @@ public class ValidatorAdapterTests { } @Test - public void wrapperDoesNotInvokeCallbackOnManagedBean() { + void wrapperDoesNotInvokeCallbackOnManagedBean() { this.contextRunner.withUserConfiguration(ManagedBeanConfig.class).run((context) -> { LocalValidatorFactoryBean validator = context.getBean(ManagedBeanConfig.class).validator; verify(validator, never()).setApplicationContext(any(ApplicationContext.class)); @@ -84,7 +84,7 @@ public class ValidatorAdapterTests { } @Test - public void wrapperWhenValidationProviderNotPresentShouldNotThrowException() { + void wrapperWhenValidationProviderNotPresentShouldNotThrowException() { ClassPathResource hibernateValidator = new ClassPathResource( "META-INF/services/javax.validation.spi.ValidationProvider"); this.contextRunner diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java index 5aade71595d..3be8d8cbe04 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConditionalOnEnabledResourceChainTests { +class ConditionalOnEnabledResourceChainTests { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -41,31 +41,31 @@ public class ConditionalOnEnabledResourceChainTests { } @Test - public void disabledByDefault() { + void disabledByDefault() { load(); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void disabledExplicitly() { + void disabledExplicitly() { load("spring.resources.chain.enabled:false"); assertThat(this.context.containsBean("foo")).isFalse(); } @Test - public void enabledViaMainEnabledFlag() { + void enabledViaMainEnabledFlag() { load("spring.resources.chain.enabled:true"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void enabledViaFixedStrategyFlag() { + void enabledViaFixedStrategyFlag() { load("spring.resources.chain.strategy.fixed.enabled:true"); assertThat(this.context.containsBean("foo")).isTrue(); } @Test - public void enabledViaContentStrategyFlag() { + void enabledViaContentStrategyFlag() { load("spring.resources.chain.strategy.content.enabled:true"); assertThat(this.context.containsBean("foo")).isTrue(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java index 92a0081cd4b..9ce3fdc37fe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesBindingTests.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ResourcePropertiesBindingTests { +class ResourcePropertiesBindingTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfiguration.class); @Test - public void staticLocationsExpandArray() { + void staticLocationsExpandArray() { this.contextRunner .withPropertyValues("spring.resources.static-locations[0]=classpath:/one/", "spring.resources.static-locations[1]=classpath:/two", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java index 2d5c9d358f9..da6396a3bbf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java @@ -33,53 +33,53 @@ import static org.hamcrest.Matchers.endsWith; * @author Stephane Nicoll * @author Kristine Jetzke */ -public class ResourcePropertiesTests { +class ResourcePropertiesTests { private final ResourceProperties properties = new ResourceProperties(); @Test - public void resourceChainNoCustomization() { + void resourceChainNoCustomization() { assertThat(this.properties.getChain().getEnabled()).isNull(); } @Test - public void resourceChainStrategyEnabled() { + void resourceChainStrategyEnabled() { this.properties.getChain().getStrategy().getFixed().setEnabled(true); assertThat(this.properties.getChain().getEnabled()).isTrue(); } @Test - public void resourceChainEnabled() { + void resourceChainEnabled() { this.properties.getChain().setEnabled(true); assertThat(this.properties.getChain().getEnabled()).isTrue(); } @Test - public void resourceChainDisabled() { + void resourceChainDisabled() { this.properties.getChain().setEnabled(false); assertThat(this.properties.getChain().getEnabled()).isFalse(); } @Test - public void defaultStaticLocationsAllEndWithTrailingSlash() { + void defaultStaticLocationsAllEndWithTrailingSlash() { assertThat(this.properties.getStaticLocations()).are(Matched.by(endsWith("/"))); } @Test - public void customStaticLocationsAreNormalizedToEndWithTrailingSlash() { + void customStaticLocationsAreNormalizedToEndWithTrailingSlash() { this.properties.setStaticLocations(new String[] { "/foo", "/bar", "/baz/" }); String[] actual = this.properties.getStaticLocations(); assertThat(actual).containsExactly("/foo/", "/bar/", "/baz/"); } @Test - public void emptyCacheControl() { + void emptyCacheControl() { CacheControl cacheControl = this.properties.getCache().getCachecontrol().toHttpCacheControl(); assertThat(cacheControl).isNull(); } @Test - public void cacheControlAllPropertiesSet() { + void cacheControlAllPropertiesSet() { Cache.Cachecontrol properties = this.properties.getCache().getCachecontrol(); properties.setMaxAge(Duration.ofSeconds(4)); properties.setCachePrivate(true); @@ -97,7 +97,7 @@ public class ResourcePropertiesTests { } @Test - public void invalidCacheControlCombination() { + void invalidCacheControlCombination() { Cache.Cachecontrol properties = this.properties.getCache().getCachecontrol(); properties.setMaxAge(Duration.ofSeconds(4)); properties.setNoStore(true); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index deac0ede6f9..08e5749c795 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -75,41 +75,41 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Venil Noronha * @author Andrew McGhie */ -public class ServerPropertiesTests { +class ServerPropertiesTests { private final ServerProperties properties = new ServerProperties(); @Test - public void testAddressBinding() throws Exception { + void testAddressBinding() throws Exception { bind("server.address", "127.0.0.1"); assertThat(this.properties.getAddress()).isEqualTo(InetAddress.getByName("127.0.0.1")); } @Test - public void testPortBinding() { + void testPortBinding() { bind("server.port", "9000"); assertThat(this.properties.getPort().intValue()).isEqualTo(9000); } @Test - public void testServerHeaderDefault() { + void testServerHeaderDefault() { assertThat(this.properties.getServerHeader()).isNull(); } @Test - public void testServerHeader() { + void testServerHeader() { bind("server.server-header", "Custom Server"); assertThat(this.properties.getServerHeader()).isEqualTo("Custom Server"); } @Test - public void testConnectionTimeout() { + void testConnectionTimeout() { bind("server.connection-timeout", "60s"); assertThat(this.properties.getConnectionTimeout()).isEqualTo(Duration.ofMillis(60000)); } @Test - public void testTomcatBinding() { + void testTomcatBinding() { Map map = new HashMap<>(); map.put("server.tomcat.accesslog.conditionIf", "foo"); map.put("server.tomcat.accesslog.conditionUnless", "bar"); @@ -149,73 +149,73 @@ public class ServerPropertiesTests { } @Test - public void testTrailingSlashOfContextPathIsRemoved() { + void testTrailingSlashOfContextPathIsRemoved() { bind("server.servlet.context-path", "/foo/"); assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/foo"); } @Test - public void testSlashOfContextPathIsDefaultValue() { + void testSlashOfContextPathIsDefaultValue() { bind("server.servlet.context-path", "/"); assertThat(this.properties.getServlet().getContextPath()).isEqualTo(""); } @Test - public void testContextPathWithLeadingWhitespace() { + void testContextPathWithLeadingWhitespace() { bind("server.servlet.context-path", " /assets"); assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets"); } @Test - public void testContextPathWithTrailingWhitespace() { + void testContextPathWithTrailingWhitespace() { bind("server.servlet.context-path", "/assets/copy/ "); assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets/copy"); } @Test - public void testContextPathWithLeadingAndTrailingWhitespace() { + void testContextPathWithLeadingAndTrailingWhitespace() { bind("server.servlet.context-path", " /assets "); assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets"); } @Test - public void testContextPathWithLeadingAndTrailingWhitespaceAndContextWithSpace() { + void testContextPathWithLeadingAndTrailingWhitespaceAndContextWithSpace() { bind("server.servlet.context-path", " /assets /copy/ "); assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets /copy"); } @Test - public void testCustomizeUriEncoding() { + void testCustomizeUriEncoding() { bind("server.tomcat.uri-encoding", "US-ASCII"); assertThat(this.properties.getTomcat().getUriEncoding()).isEqualTo(StandardCharsets.US_ASCII); } @Test - public void testCustomizeHeaderSize() { + void testCustomizeHeaderSize() { bind("server.max-http-header-size", "1MB"); assertThat(this.properties.getMaxHttpHeaderSize()).isEqualTo(DataSize.ofMegabytes(1)); } @Test - public void testCustomizeHeaderSizeUseBytesByDefault() { + void testCustomizeHeaderSizeUseBytesByDefault() { bind("server.max-http-header-size", "1024"); assertThat(this.properties.getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1)); } @Test - public void testCustomizeJettyAcceptors() { + void testCustomizeJettyAcceptors() { bind("server.jetty.acceptors", "10"); assertThat(this.properties.getJetty().getAcceptors()).isEqualTo(10); } @Test - public void testCustomizeJettySelectors() { + void testCustomizeJettySelectors() { bind("server.jetty.selectors", "10"); assertThat(this.properties.getJetty().getSelectors()).isEqualTo(10); } @Test - public void testCustomizeJettyAccessLog() { + void testCustomizeJettyAccessLog() { Map map = new HashMap<>(); map.put("server.jetty.accesslog.enabled", "true"); map.put("server.jetty.accesslog.filename", "foo.txt"); @@ -236,75 +236,75 @@ public class ServerPropertiesTests { } @Test - public void tomcatAcceptCountMatchesProtocolDefault() throws Exception { + void tomcatAcceptCountMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getAcceptCount()).isEqualTo(getDefaultProtocol().getAcceptCount()); } @Test - public void tomcatProcessorCacheMatchesProtocolDefault() throws Exception { + void tomcatProcessorCacheMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getProcessorCache()).isEqualTo(getDefaultProtocol().getProcessorCache()); } @Test - public void tomcatMaxConnectionsMatchesProtocolDefault() throws Exception { + void tomcatMaxConnectionsMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getMaxConnections()).isEqualTo(getDefaultProtocol().getMaxConnections()); } @Test - public void tomcatMaxThreadsMatchesProtocolDefault() throws Exception { + void tomcatMaxThreadsMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getMaxThreads()).isEqualTo(getDefaultProtocol().getMaxThreads()); } @Test - public void tomcatMinSpareThreadsMatchesProtocolDefault() throws Exception { + void tomcatMinSpareThreadsMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getMinSpareThreads()) .isEqualTo(getDefaultProtocol().getMinSpareThreads()); } @Test - public void tomcatMaxHttpPostSizeMatchesConnectorDefault() throws Exception { + void tomcatMaxHttpPostSizeMatchesConnectorDefault() throws Exception { assertThat(this.properties.getTomcat().getMaxHttpPostSize().toBytes()) .isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test - public void tomcatBackgroundProcessorDelayMatchesEngineDefault() { + void tomcatBackgroundProcessorDelayMatchesEngineDefault() { assertThat(this.properties.getTomcat().getBackgroundProcessorDelay()) .isEqualTo(Duration.ofSeconds((new StandardEngine().getBackgroundProcessorDelay()))); } @Test - public void tomcatUriEncodingMatchesConnectorDefault() throws Exception { + void tomcatUriEncodingMatchesConnectorDefault() throws Exception { assertThat(this.properties.getTomcat().getUriEncoding().name()) .isEqualTo(getDefaultConnector().getURIEncoding()); } @Test - public void tomcatRedirectContextRootMatchesDefault() { + void tomcatRedirectContextRootMatchesDefault() { assertThat(this.properties.getTomcat().getRedirectContextRoot()) .isEqualTo(new StandardContext().getMapperContextRootRedirectEnabled()); } @Test - public void tomcatAccessLogRenameOnRotateMatchesDefault() { + void tomcatAccessLogRenameOnRotateMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRenameOnRotate()) .isEqualTo(new AccessLogValve().isRenameOnRotate()); } @Test - public void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { + void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); } @Test - public void tomcatInternalProxiesMatchesDefault() { + void tomcatInternalProxiesMatchesDefault() { assertThat(this.properties.getTomcat().getInternalProxies()) .isEqualTo(new RemoteIpValve().getInternalProxies()); } @Test - public void jettyMaxHttpPostSizeMatchesDefault() throws Exception { + void jettyMaxHttpPostSizeMatchesDefault() throws Exception { JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0); JettyWebServer jetty = (JettyWebServer) jettyFactory .getWebServer((ServletContextInitializer) (servletContext) -> servletContext @@ -364,7 +364,7 @@ public class ServerPropertiesTests { } @Test - public void undertowMaxHttpPostSizeMatchesDefault() { + void undertowMaxHttpPostSizeMatchesDefault() { assertThat(this.properties.getUndertow().getMaxHttpPostSize().toBytes()) .isEqualTo(UndertowOptions.DEFAULT_MAX_ENTITY_SIZE); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index b6c6290a9a3..7fc93af5c1b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java @@ -45,13 +45,13 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Phillip Webb */ -public class RestTemplateAutoConfigurationTests { +class RestTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); @Test - public void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() { + void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .withUserConfiguration(RestTemplateConfig.class).run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); @@ -65,7 +65,7 @@ public class RestTemplateAutoConfigurationTests { } @Test - public void restTemplateWhenNoMessageConvertersDefinedShouldHaveDefaultMessageConverters() { + void restTemplateWhenNoMessageConvertersDefinedShouldHaveDefaultMessageConverters() { this.contextRunner.withUserConfiguration(RestTemplateConfig.class).run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class); @@ -76,7 +76,7 @@ public class RestTemplateAutoConfigurationTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { + void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class).run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); @@ -87,7 +87,7 @@ public class RestTemplateAutoConfigurationTests { } @Test - public void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { + void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { this.contextRunner.withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class) .run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); @@ -99,7 +99,7 @@ public class RestTemplateAutoConfigurationTests { } @Test - public void restTemplateShouldApplyCustomizer() { + void restTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(RestTemplateConfig.class, RestTemplateCustomizerConfig.class) .run((context) -> { assertThat(context).hasSingleBean(RestTemplate.class); @@ -110,19 +110,19 @@ public class RestTemplateAutoConfigurationTests { } @Test - public void builderShouldBeFreshForEachUse() { + void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyRestTemplateConfig.class) .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void whenServletWebApplicationRestTemplateBuilderIsConfigured() { + void whenServletWebApplicationRestTemplateBuilderIsConfigured() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class)); } @Test - public void whenReactiveWebApplicationRestTemplateBuilderIsNotConfigured() { + void whenReactiveWebApplicationRestTemplateBuilderIsNotConfigured() { new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java index b1cdfb3b7f1..13a2c22b6f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java @@ -50,7 +50,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Phillip Webb */ -public class JettyWebServerFactoryCustomizerTests { +class JettyWebServerFactoryCustomizerTests { private MockEnvironment environment; @@ -67,7 +67,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void deduceUseForwardHeaders() { + void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); @@ -75,14 +75,14 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void defaultUseForwardHeaders() { + void defaultUseForwardHeaders() { ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(false); } @Test - public void accessLogCanBeCustomized() throws IOException { + void accessLogCanBeCustomized() throws IOException { File logFile = File.createTempFile("jetty_log", ".log"); bind("server.jetty.accesslog.enabled=true", "server.jetty.accesslog.format=extended_ncsa", "server.jetty.accesslog.filename=" + logFile.getAbsolutePath().replace("\\", "\\\\"), @@ -101,7 +101,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void accessLogCanBeEnabled() { + void accessLogCanBeEnabled() { bind("server.jetty.accesslog.enabled=true"); JettyWebServer server = customizeAndGetServer(); CustomRequestLog requestLog = getRequestLog(server); @@ -125,7 +125,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void setUseForwardHeaders() { + void setUseForwardHeaders() { this.serverProperties.setUseForwardHeaders(true); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); this.customizer.customize(factory); @@ -133,7 +133,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void customizeMaxHttpHeaderSize() { + void customizeMaxHttpHeaderSize() { bind("server.max-http-header-size=2048"); JettyWebServer server = customizeAndGetServer(); List requestHeaderSizes = getRequestHeaderSizes(server); @@ -141,7 +141,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpHeaderSizeIgnoredIfNegative() { + void customMaxHttpHeaderSizeIgnoredIfNegative() { bind("server.max-http-header-size=-1"); JettyWebServer server = customizeAndGetServer(); List requestHeaderSizes = getRequestHeaderSizes(server); @@ -149,7 +149,7 @@ public class JettyWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpHeaderSizeIgnoredIfZero() { + void customMaxHttpHeaderSizeIgnoredIfZero() { bind("server.max-http-header-size=0"); JettyWebServer server = customizeAndGetServer(); List requestHeaderSizes = getRequestHeaderSizes(server); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java index ec7907496bc..3d16d3b74b5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizerTests.java @@ -32,7 +32,7 @@ import static org.mockito.Mockito.verify; * * @author Brian Clozel */ -public class NettyWebServerFactoryCustomizerTests { +class NettyWebServerFactoryCustomizerTests { private MockEnvironment environment; @@ -49,7 +49,7 @@ public class NettyWebServerFactoryCustomizerTests { } @Test - public void deduceUseForwardHeaders() { + void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); this.customizer.customize(factory); @@ -57,14 +57,14 @@ public class NettyWebServerFactoryCustomizerTests { } @Test - public void defaultUseForwardHeaders() { + void defaultUseForwardHeaders() { NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(false); } @Test - public void setUseForwardHeaders() { + void setUseForwardHeaders() { this.serverProperties.setUseForwardHeaders(true); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); this.customizer.customize(factory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java index a0f830fa766..9f075928962 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java @@ -53,7 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Andrew McGhie */ -public class TomcatWebServerFactoryCustomizerTests { +class TomcatWebServerFactoryCustomizerTests { private MockEnvironment environment; @@ -70,7 +70,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void defaultsAreConsistent() { + void defaultsAreConsistent() { customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) .getMaxSwallowSize()) @@ -78,7 +78,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customAcceptCount() { + void customAcceptCount() { bind("server.tomcat.accept-count=10"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getAcceptCount()) @@ -86,7 +86,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customProcessorCache() { + void customProcessorCache() { bind("server.tomcat.processor-cache=100"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) @@ -94,7 +94,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void unlimitedProcessorCache() { + void unlimitedProcessorCache() { bind("server.tomcat.processor-cache=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) @@ -102,20 +102,20 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customBackgroundProcessorDelay() { + void customBackgroundProcessorDelay() { bind("server.tomcat.background-processor-delay=5"); TomcatWebServer server = customizeAndGetServer(); assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(5); } @Test - public void customDisableMaxHttpPostSize() { + void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); } @Test - public void customMaxConnections() { + void customMaxConnections() { bind("server.tomcat.max-connections=5"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getMaxConnections()) @@ -123,14 +123,14 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpPostSize() { + void customMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=10000"); customizeAndRunServer( (server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(10000)); } @Test - public void customMaxHttpHeaderSize() { + void customMaxHttpHeaderSize() { bind("server.max-http-header-size=1KB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) @@ -138,7 +138,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpHeaderSizeIgnoredIfNegative() { + void customMaxHttpHeaderSizeIgnoredIfNegative() { bind("server.max-http-header-size=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) @@ -146,7 +146,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpHeaderSizeIgnoredIfZero() { + void customMaxHttpHeaderSizeIgnoredIfZero() { bind("server.max-http-header-size=0"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) @@ -154,7 +154,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customMaxSwallowSize() { + void customMaxSwallowSize() { bind("server.tomcat.max-swallow-size=10MB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) @@ -162,7 +162,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customRemoteIpValve() { + void customRemoteIpValve() { bind("server.tomcat.remote-ip-header=x-my-remote-ip-header", "server.tomcat.protocol-header=x-my-protocol-header", "server.tomcat.internal-proxies=192.168.0.1", "server.tomcat.port-header=x-my-forward-port", "server.tomcat.protocol-header-https-value=On"); @@ -179,7 +179,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customStaticResourceAllowCaching() { + void customStaticResourceAllowCaching() { bind("server.tomcat.resource.allow-caching=false"); customizeAndRunServer((server) -> { Tomcat tomcat = server.getTomcat(); @@ -189,7 +189,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void customStaticResourceCacheTtl() { + void customStaticResourceCacheTtl() { bind("server.tomcat.resource.cache-ttl=10000"); customizeAndRunServer((server) -> { Tomcat tomcat = server.getTomcat(); @@ -199,20 +199,20 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void deduceUseForwardHeaders() { + void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); testRemoteIpValveConfigured(); } @Test - public void defaultRemoteIpValve() { + void defaultRemoteIpValve() { // Since 1.1.7 you need to specify at least the protocol bind("server.tomcat.protocol-header=X-Forwarded-Proto", "server.tomcat.remote-ip-header=X-Forwarded-For"); testRemoteIpValveConfigured(); } @Test - public void setUseForwardHeaders() { + void setUseForwardHeaders() { // Since 1.3.0 no need to explicitly set header names if use-forward-header=true this.serverProperties.setUseForwardHeaders(true); testRemoteIpValveConfigured(); @@ -238,20 +238,20 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void defaultBackgroundProcessorDelay() { + void defaultBackgroundProcessorDelay() { TomcatWebServer server = customizeAndGetServer(); assertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(10); } @Test - public void disableRemoteIpValve() { + void disableRemoteIpValve() { bind("server.tomcat.remote-ip-header=", "server.tomcat.protocol-header="); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(factory.getEngineValves()).isEmpty(); } @Test - public void errorReportValveIsConfiguredToNotReportStackTraces() { + void errorReportValveIsConfiguredToNotReportStackTraces() { TomcatWebServer server = customizeAndGetServer(); Valve[] valves = server.getTomcat().getHost().getPipeline().getValves(); assertThat(valves).hasAtLeastOneElementOfType(ErrorReportValve.class); @@ -265,20 +265,20 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void testCustomizeMinSpareThreads() { + void testCustomizeMinSpareThreads() { bind("server.tomcat.min-spare-threads=10"); assertThat(this.serverProperties.getTomcat().getMinSpareThreads()).isEqualTo(10); } @Test - public void accessLogBufferingCanBeDisabled() { + void accessLogBufferingCanBeDisabled() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.buffered=false"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isFalse(); } @Test - public void accessLogCanBeEnabled() { + void accessLogCanBeEnabled() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(factory.getEngineValves()).hasSize(1); @@ -286,7 +286,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogFileDateFormatByDefault() { + void accessLogFileDateFormatByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) @@ -294,7 +294,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogFileDateFormatCanBeRedefined() { + void accessLogFileDateFormatCanBeRedefined() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) @@ -302,20 +302,20 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogIsBufferedByDefault() { + void accessLogIsBufferedByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isTrue(); } @Test - public void accessLogIsDisabledByDefault() { + void accessLogIsDisabledByDefault() { TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(factory.getEngineValves()).isEmpty(); } @Test - public void accessLogMaxDaysDefault() { + void accessLogMaxDaysDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()) @@ -323,7 +323,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogConditionCanBeSpecified() { + void accessLogConditionCanBeSpecified() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.conditionIf=foo", "server.tomcat.accesslog.conditionUnless=bar"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); @@ -336,21 +336,21 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogEncodingIsNullWhenNotSpecified() { + void accessLogEncodingIsNullWhenNotSpecified() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getEncoding()).isNull(); } @Test - public void accessLogEncodingCanBeSpecified() { + void accessLogEncodingCanBeSpecified() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.encoding=UTF-8"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getEncoding()).isEqualTo("UTF-8"); } @Test - public void accessLogWithDefaultLocale() { + void accessLogWithDefaultLocale() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getLocale()) @@ -358,7 +358,7 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogLocaleCanBeSpecified() { + void accessLogLocaleCanBeSpecified() { String locale = "en_AU".equals(Locale.getDefault().toString()) ? "en_US" : "en_AU"; bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.locale=" + locale); TomcatServletWebServerFactory factory = customizeAndGetFactory(); @@ -366,42 +366,42 @@ public class TomcatWebServerFactoryCustomizerTests { } @Test - public void accessLogCheckExistsDefault() { + void accessLogCheckExistsDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isCheckExists()).isFalse(); } @Test - public void accessLogCheckExistsSpecified() { + void accessLogCheckExistsSpecified() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.check-exists=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isCheckExists()).isTrue(); } @Test - public void accessLogMaxDaysCanBeRedefined() { + void accessLogMaxDaysCanBeRedefined() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.max-days=20"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()).isEqualTo(20); } @Test - public void accessLogDoesNotUseIpv6CanonicalFormatByDefault() { + void accessLogDoesNotUseIpv6CanonicalFormatByDefault() { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getIpv6Canonical()).isFalse(); } @Test - public void accessLogwithIpv6CanonicalSet() { + void accessLogwithIpv6CanonicalSet() { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.ipv6-canonical=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getIpv6Canonical()).isTrue(); } @Test - public void ajpConnectorCanBeCustomized() { + void ajpConnectorCanBeCustomized() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); factory.setProtocol("AJP/1.3"); this.customizer.customize(factory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java index 87121e32099..ee1942a70d7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java @@ -52,7 +52,7 @@ import static org.mockito.Mockito.verify; * @author Artsiom Yudovin * @author Rafiullah Hamedy */ -public class UndertowWebServerFactoryCustomizerTests { +class UndertowWebServerFactoryCustomizerTests { private MockEnvironment environment; @@ -69,7 +69,7 @@ public class UndertowWebServerFactoryCustomizerTests { } @Test - public void customizeUndertowAccessLog() { + void customizeUndertowAccessLog() { bind("server.undertow.accesslog.enabled=true", "server.undertow.accesslog.pattern=foo", "server.undertow.accesslog.prefix=test_log", "server.undertow.accesslog.suffix=txt", "server.undertow.accesslog.dir=test-logs", "server.undertow.accesslog.rotate=false"); @@ -84,79 +84,79 @@ public class UndertowWebServerFactoryCustomizerTests { } @Test - public void customMaxHttpHeaderSize() { + void customMaxHttpHeaderSize() { bind("server.max-http-header-size=2048"); assertThat(boundServerOption(UndertowOptions.MAX_HEADER_SIZE)).isEqualTo(2048); } @Test - public void customMaxHttpHeaderSizeIgnoredIfNegative() { + void customMaxHttpHeaderSizeIgnoredIfNegative() { bind("server.max-http-header-size=-1"); assertThat(boundServerOption(UndertowOptions.MAX_HEADER_SIZE)).isNull(); } @Test - public void customMaxHttpHeaderSizeIgnoredIfZero() { + void customMaxHttpHeaderSizeIgnoredIfZero() { bind("server.max-http-header-size=0"); assertThat(boundServerOption(UndertowOptions.MAX_HEADER_SIZE)).isNull(); } @Test - public void customMaxHttpPostSize() { + void customMaxHttpPostSize() { bind("server.undertow.max-http-post-size=256"); assertThat(boundServerOption(UndertowOptions.MAX_ENTITY_SIZE)).isEqualTo(256); } @Test - public void customConnectionTimeout() { + void customConnectionTimeout() { bind("server.connectionTimeout=100"); assertThat(boundServerOption(UndertowOptions.NO_REQUEST_TIMEOUT)).isEqualTo(100); } @Test - public void customMaxParameters() { + void customMaxParameters() { bind("server.undertow.max-parameters=4"); assertThat(boundServerOption(UndertowOptions.MAX_PARAMETERS)).isEqualTo(4); } @Test - public void customMaxHeaders() { + void customMaxHeaders() { bind("server.undertow.max-headers=4"); assertThat(boundServerOption(UndertowOptions.MAX_HEADERS)).isEqualTo(4); } @Test - public void customMaxCookies() { + void customMaxCookies() { bind("server.undertow.max-cookies=4"); assertThat(boundServerOption(UndertowOptions.MAX_COOKIES)).isEqualTo(4); } @Test - public void allowEncodedSlashes() { + void allowEncodedSlashes() { bind("server.undertow.allow-encoded-slash=true"); assertThat(boundServerOption(UndertowOptions.ALLOW_ENCODED_SLASH)).isTrue(); } @Test - public void disableUrlDecoding() { + void disableUrlDecoding() { bind("server.undertow.decode-url=false"); assertThat(boundServerOption(UndertowOptions.DECODE_URL)).isFalse(); } @Test - public void customUrlCharset() { + void customUrlCharset() { bind("server.undertow.url-charset=UTF-16"); assertThat(boundServerOption(UndertowOptions.URL_CHARSET)).isEqualTo(StandardCharsets.UTF_16.name()); } @Test - public void disableAlwaysSetKeepAlive() { + void disableAlwaysSetKeepAlive() { bind("server.undertow.always-set-keep-alive=false"); assertThat(boundServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE)).isFalse(); } @Test - public void deduceUseForwardHeaders() { + void deduceUseForwardHeaders() { this.environment.setProperty("DYNO", "-"); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); @@ -164,14 +164,14 @@ public class UndertowWebServerFactoryCustomizerTests { } @Test - public void defaultUseForwardHeaders() { + void defaultUseForwardHeaders() { ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); verify(factory).setUseForwardHeaders(false); } @Test - public void setUseForwardHeaders() { + void setUseForwardHeaders() { this.serverProperties.setUseForwardHeaders(true); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); this.customizer.customize(factory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java index b3c221af009..338a16569f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java @@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel * @author Madhura Bhave */ -public class WebConversionServiceTests { +class WebConversionServiceTests { @Test - public void customDateFormat() { + void customDateFormat() { WebConversionService conversionService = new WebConversionService("dd*MM*yyyy"); Date date = new DateTime(2018, 1, 1, 20, 30).toDate(); assertThat(conversionService.convert(date, String.class)).isEqualTo("01*01*2018"); @@ -44,7 +44,7 @@ public class WebConversionServiceTests { } @Test - public void convertFromStringToDate() { + void convertFromStringToDate() { WebConversionService conversionService = new WebConversionService("yyyy-MM-dd"); java.time.LocalDate date = conversionService.convert("2018-01-01", java.time.LocalDate.class); assertThat(date).isEqualTo(java.time.LocalDate.of(2018, 1, 1)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index 9948b4d20ad..71b23b7d347 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -37,13 +37,13 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r * @author Stephane Nicoll * @author Andy Wilkinson */ -public class HttpHandlerAutoConfigurationTests { +class HttpHandlerAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); @Test - public void shouldNotProcessIfExistingHttpHandler() { + void shouldNotProcessIfExistingHttpHandler() { this.contextRunner.withUserConfiguration(CustomHttpHandler.class).run((context) -> { assertThat(context).hasSingleBean(HttpHandler.class); assertThat(context).getBean(HttpHandler.class).isSameAs(context.getBean("customHttpHandler")); @@ -51,7 +51,7 @@ public class HttpHandlerAutoConfigurationTests { } @Test - public void shouldConfigureHttpHandlerAnnotation() { + void shouldConfigureHttpHandlerAnnotation() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java index dbceabeb12a..aa22a05e6ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java @@ -54,14 +54,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Raheela Aslam * @author Madhura Bhave */ -public class ReactiveWebServerFactoryAutoConfigurationTests { +class ReactiveWebServerFactoryAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class) .run((context) -> { assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); @@ -71,7 +71,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void missingHttpHandler() { + void missingHttpHandler() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class) .run((context) -> assertThat(context.getStartupFailure()) .isInstanceOf(ApplicationContextException.class) @@ -79,7 +79,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void multipleHttpHandler() { + void multipleHttpHandler() { this.contextRunner .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, TooManyHttpHandlers.class) @@ -89,7 +89,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void customizeReactiveWebServer() { + void customizeReactiveWebServer() { this.contextRunner .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, ReactiveWebServerCustomization.class) @@ -98,7 +98,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void defaultWebServerIsTomcat() { + void defaultWebServerIsTomcat() { // Tomcat should be chosen over Netty if the Tomcat library is present. this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class).withPropertyValues("server.port=0") .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) @@ -106,7 +106,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatConnectorCustomizerBeanIsAddedToFactory() { + void tomcatConnectorCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) @@ -118,7 +118,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatContextCustomizerBeanIsAddedToFactory() { + void tomcatContextCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) @@ -130,7 +130,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { + void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) @@ -142,7 +142,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void jettyServerCustomizerBeanIsAddedToFactory() { + void jettyServerCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) @@ -154,7 +154,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void undertowDeploymentInfoCustomizerBeanIsAddedToFactory() { + void undertowDeploymentInfoCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) @@ -167,7 +167,7 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void undertowBuilderCustomizerBeanIsAddedToFactory() { + void undertowBuilderCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) @@ -179,21 +179,21 @@ public class ReactiveWebServerFactoryAutoConfigurationTests { } @Test - public void forwardedHeaderTransformerShouldBeConfigured() { + void forwardedHeaderTransformerShouldBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=framework") .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Test - public void forwardedHeaderTransformerWhenStrategyNotFilterShouldNotBeConfigured() { + void forwardedHeaderTransformerWhenStrategyNotFilterShouldNotBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=native") .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); } @Test - public void forwardedHeaderTransformerWhenAlreadyRegisteredShouldBackOff() { + void forwardedHeaderTransformerWhenAlreadyRegisteredShouldBackOff() { this.contextRunner .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) .withPropertyValues("server.forward-headers-strategy=framework") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java index af1dc3ab41a..de8cffd628d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryCustomizerTests.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Yunkun Huang */ -public class ReactiveWebServerFactoryCustomizerTests { +class ReactiveWebServerFactoryCustomizerTests { private ServerProperties properties = new ServerProperties(); @@ -46,7 +46,7 @@ public class ReactiveWebServerFactoryCustomizerTests { } @Test - public void testCustomizeServerPort() { + void testCustomizeServerPort() { ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); this.properties.setPort(9000); this.customizer.customize(factory); @@ -54,7 +54,7 @@ public class ReactiveWebServerFactoryCustomizerTests { } @Test - public void testCustomizeServerAddress() { + void testCustomizeServerAddress() { ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); InetAddress address = mock(InetAddress.class); this.properties.setAddress(address); @@ -63,7 +63,7 @@ public class ReactiveWebServerFactoryCustomizerTests { } @Test - public void testCustomizeServerSsl() { + void testCustomizeServerSsl() { ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); Ssl ssl = mock(Ssl.class); this.properties.setSsl(ssl); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java index c4c108ae543..63cff395959 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java @@ -77,7 +77,7 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Artsiom Yudovin */ -public class WebFluxAutoConfigurationTests { +class WebFluxAutoConfigurationTests { private static final MockReactiveWebServerFactory mockReactiveWebServerFactory = new MockReactiveWebServerFactory(); @@ -86,7 +86,7 @@ public class WebFluxAutoConfigurationTests { .withUserConfiguration(Config.class); @Test - public void shouldNotProcessIfExistingWebReactiveConfiguration() { + void shouldNotProcessIfExistingWebReactiveConfiguration() { this.contextRunner.withUserConfiguration(WebFluxConfigurationSupport.class).run((context) -> { assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1); assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1); @@ -94,7 +94,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldCreateDefaultBeans() { + void shouldCreateDefaultBeans() { this.contextRunner.run((context) -> { assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1); assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1); @@ -105,7 +105,7 @@ public class WebFluxAutoConfigurationTests { @SuppressWarnings("unchecked") @Test - public void shouldRegisterCustomHandlerMethodArgumentResolver() { + void shouldRegisterCustomHandlerMethodArgumentResolver() { this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class).run((context) -> { RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); List customResolvers = (List) ReflectionTestUtils @@ -116,7 +116,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldCustomizeCodecs() { + void shouldCustomizeCodecs() { this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class).run((context) -> { CodecCustomizer codecCustomizer = context.getBean("firstCodecCustomizer", CodecCustomizer.class); assertThat(codecCustomizer).isNotNull(); @@ -125,7 +125,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldRegisterResourceHandlerMapping() { + void shouldRegisterResourceHandlerMapping() { this.contextRunner.run((context) -> { SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); @@ -140,7 +140,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldMapResourcesToCustomPath() { + void shouldMapResourcesToCustomPath() { this.contextRunner.withPropertyValues("spring.webflux.static-path-pattern:/static/**").run((context) -> { SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); assertThat(hm.getUrlMap().get("/static/**")).isInstanceOf(ResourceWebHandler.class); @@ -150,14 +150,14 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldNotMapResourcesWhenDisabled() { + void shouldNotMapResourcesWhenDisabled() { this.contextRunner.withPropertyValues("spring.resources.add-mappings:false") .run((context) -> assertThat(context.getBean("resourceHandlerMapping")) .isNotInstanceOf(SimpleUrlHandlerMapping.class)); } @Test - public void resourceHandlerChainEnabled() { + void resourceHandlerChainEnabled() { this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class); assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); @@ -170,7 +170,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void shouldRegisterViewResolvers() { + void shouldRegisterViewResolvers() { this.contextRunner.withUserConfiguration(ViewResolvers.class).run((context) -> { ViewResolutionResultHandler resultHandler = context.getBean(ViewResolutionResultHandler.class); assertThat(resultHandler.getViewResolvers()).containsExactly( @@ -180,7 +180,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void noDateFormat() { + void noDateFormat() { this.contextRunner.run((context) -> { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); @@ -190,7 +190,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void overrideDateFormat() { + void overrideDateFormat() { this.contextRunner.withPropertyValues("spring.webflux.date-format:dd*MM*yyyy").run((context) -> { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); @@ -199,7 +199,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWhenNoValidatorShouldUseDefault() { + void validatorWhenNoValidatorShouldUseDefault() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -208,7 +208,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWhenNoCustomizationShouldUseAutoConfigured() { + void validatorWhenNoCustomizationShouldUseAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class) @@ -226,7 +226,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWithConfigurerShouldUseSpringValidator() { + void validatorWithConfigurerShouldUseSpringValidator() { this.contextRunner.withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -237,7 +237,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWithConfigurerDoesNotExposeJsr303() { + void validatorWithConfigurerDoesNotExposeJsr303() { this.contextRunner.withUserConfiguration(ValidatorJsr303WebFluxConfigurer.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -250,7 +250,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validationCustomConfigurerTakesPrecedence() { + void validationCustomConfigurerTakesPrecedence() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); @@ -267,7 +267,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWithCustomSpringValidatorIgnored() { + void validatorWithCustomSpringValidatorIgnored() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(CustomSpringValidator.class).run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class) @@ -285,7 +285,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { + void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { this.contextRunner.withUserConfiguration(CustomJsr303Validator.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).getBeanNames(javax.validation.Validator.class).containsExactly("customValidator"); @@ -298,12 +298,12 @@ public class WebFluxAutoConfigurationTests { } @Test - public void hiddenHttpMethodFilterIsAutoConfigured() { + void hiddenHttpMethodFilterIsAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); } @Test - public void hiddenHttpMethodFilterCanBeOverridden() { + void hiddenHttpMethodFilterCanBeOverridden() { this.contextRunner.withUserConfiguration(CustomHiddenHttpMethodFilter.class).run((context) -> { assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); @@ -311,27 +311,27 @@ public class WebFluxAutoConfigurationTests { } @Test - public void hiddenHttpMethodFilterCanBeDisabled() { + void hiddenHttpMethodFilterCanBeDisabled() { this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(HiddenHttpMethodFilter.class)); } @Test - public void customRequestMappingHandlerMapping() { + void customRequestMappingHandlerMapping() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerMapping.class) .run((context) -> assertThat(context).getBean(RequestMappingHandlerMapping.class) .isInstanceOf(MyRequestMappingHandlerMapping.class)); } @Test - public void customRequestMappingHandlerAdapter() { + void customRequestMappingHandlerAdapter() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerAdapter.class) .run((context) -> assertThat(context).getBean(RequestMappingHandlerAdapter.class) .isInstanceOf(MyRequestMappingHandlerAdapter.class)); } @Test - public void multipleWebFluxRegistrations() { + void multipleWebFluxRegistrations() { this.contextRunner.withUserConfiguration(MultipleWebFluxRegistrations.class).run((context) -> { assertThat(context.getBean(RequestMappingHandlerMapping.class)) .isNotInstanceOf(MyRequestMappingHandlerMapping.class); @@ -341,7 +341,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void cachePeriod() { + void cachePeriod() { Assertions.setExtractBareNamePropertyMethods(false); this.contextRunner.withPropertyValues("spring.resources.cache.period:5").run((context) -> { Map handlerMap = getHandlerMap(context); @@ -357,7 +357,7 @@ public class WebFluxAutoConfigurationTests { } @Test - public void cacheControl() { + void cacheControl() { Assertions.setExtractBareNamePropertyMethods(false); this.contextRunner.withPropertyValues("spring.resources.cache.cachecontrol.max-age:5", "spring.resources.cache.cachecontrol.proxy-revalidate:true").run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java index 0fcc41b80e1..c58187397a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java @@ -57,7 +57,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Brian Clozel */ @ExtendWith(OutputCaptureExtension.class) -public class DefaultErrorWebExceptionHandlerIntegrationTests { +class DefaultErrorWebExceptionHandlerIntegrationTests { private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8); @@ -72,7 +72,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { .withUserConfiguration(Application.class); @Test - public void jsonError(CapturedOutput capturedOutput) { + void jsonError(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() @@ -86,7 +86,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void notFound() { + void notFound() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/notFound").exchange().expectStatus().isNotFound().expectBody().jsonPath("status") @@ -97,7 +97,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void htmlError() { + void htmlError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() @@ -108,7 +108,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void bindingResultError() { + void bindingResultError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON).syncBody("{}").exchange().expectStatus() @@ -120,7 +120,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void includeStackTraceOnParam() { + void includeStackTraceOnParam() { this.contextRunner.withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-trace-param").run((context) -> { WebTestClient client = getWebClient(context); @@ -134,7 +134,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void alwaysIncludeStackTrace() { + void alwaysIncludeStackTrace() { this.contextRunner .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") .run((context) -> { @@ -149,7 +149,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void neverIncludeStackTrace() { + void neverIncludeStackTrace() { this.contextRunner .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") .run((context) -> { @@ -164,7 +164,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void statusException() { + void statusException() { this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/badRequest").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") @@ -175,7 +175,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void defaultErrorView() { + void defaultErrorView() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-stacktrace=always").run((context) -> { WebTestClient client = getWebClient(context); @@ -189,7 +189,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void escapeHtmlInDefaultErrorView() { + void escapeHtmlInDefaultErrorView() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/html").accept(MediaType.TEXT_HTML).exchange().expectStatus() @@ -201,7 +201,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void testExceptionWithNullMessage() { + void testExceptionWithNullMessage() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/notfound").accept(MediaType.TEXT_HTML).exchange().expectStatus() @@ -213,7 +213,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void responseCommitted() { + void responseCommitted() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); assertThatExceptionOfType(RuntimeException.class) @@ -223,7 +223,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void whitelabelDisabled() { + void whitelabelDisabled() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); @@ -233,7 +233,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void exactStatusTemplateErrorPage() { + void exactStatusTemplateErrorPage() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=" + getErrorTemplatesLocation()).run((context) -> { WebTestClient client = getWebClient(context); @@ -244,7 +244,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void seriesStatusTemplateErrorPage() { + void seriesStatusTemplateErrorPage() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=" + getErrorTemplatesLocation()).run((context) -> { WebTestClient client = getWebClient(context); @@ -255,7 +255,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { } @Test - public void invalidAcceptMediaType() { + void invalidAcceptMediaType() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/notfound").header("Accept", "v=3.0").exchange().expectStatus() diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerTests.java index c6c9a2cdd49..329ed9388b3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.autoconfigure.web.reactive.error; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class DefaultErrorWebExceptionHandlerTests { +class DefaultErrorWebExceptionHandlerTests { @Test - public void disconnectedClientExceptionsMatchesFramework() { + void disconnectedClientExceptionsMatchesFramework() { Object errorHandlers = ReflectionTestUtils.getField(AbstractErrorWebExceptionHandler.class, "DISCONNECTED_CLIENT_EXCEPTIONS"); Object webHandlers = ReflectionTestUtils.getField(HttpWebHandlerAdapter.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfigurationTests.java index 213f35ad5c7..0051fb0c4db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorAutoConfigurationTests.java @@ -39,13 +39,13 @@ import static org.mockito.Mockito.verify; * * @author Brian Clozel */ -public class ClientHttpConnectorAutoConfigurationTests { +class ClientHttpConnectorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ClientHttpConnectorAutoConfiguration.class)); @Test - public void shouldCreateHttpClientBeans() { + void shouldCreateHttpClientBeans() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(ReactorResourceFactory.class); assertThat(context).hasSingleBean(ReactorClientHttpConnector.class); @@ -57,7 +57,7 @@ public class ClientHttpConnectorAutoConfigurationTests { } @Test - public void shouldNotOverrideCustomClientConnector() { + void shouldNotOverrideCustomClientConnector() { this.contextRunner.withUserConfiguration(CustomClientHttpConnectorConfig.class).run((context) -> { assertThat(context).hasSingleBean(ClientHttpConnector.class).hasBean("customConnector") .doesNotHaveBean(ReactorResourceFactory.class); @@ -69,7 +69,7 @@ public class ClientHttpConnectorAutoConfigurationTests { } @Test - public void shouldUseCustomReactorResourceFactory() { + void shouldUseCustomReactorResourceFactory() { this.contextRunner.withUserConfiguration(CustomReactorResourceConfig.class) .run((context) -> assertThat(context).hasSingleBean(ReactorClientHttpConnector.class) .hasSingleBean(ReactorResourceFactory.class).hasBean("customReactorResourceFactory")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfigurationTests.java index e67d3110564..abd0dafb69c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfigurationTests.java @@ -21,7 +21,7 @@ import java.util.concurrent.Executor; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.thread.Scheduler; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.client.reactive.JettyClientHttpConnector; import org.springframework.http.client.reactive.JettyResourceFactory; @@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ClientHttpConnectorConfigurationTests { +class ClientHttpConnectorConfigurationTests { @Test - public void jettyClientHttpConnectorAppliesJettyResourceFactory() { + void jettyClientHttpConnectorAppliesJettyResourceFactory() { Executor executor = mock(Executor.class); ByteBufferPool byteBufferPool = mock(ByteBufferPool.class); Scheduler scheduler = mock(Scheduler.class); @@ -54,7 +54,7 @@ public class ClientHttpConnectorConfigurationTests { } @Test - public void JettyResourceFactoryHasSslContextFactory() { + void JettyResourceFactoryHasSslContextFactory() { // gh-16810 JettyResourceFactory jettyResourceFactory = new JettyResourceFactory(); JettyClientHttpConnector connector = getClientHttpConnector(jettyResourceFactory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfigurationTests.java index 17a378f0723..d3f363771eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfigurationTests.java @@ -47,13 +47,13 @@ import static org.mockito.Mockito.verify; * * @author Brian Clozel */ -public class WebClientAutoConfigurationTests { +class WebClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( AutoConfigurations.of(ClientHttpConnectorAutoConfiguration.class, WebClientAutoConfiguration.class)); @Test - public void shouldCreateBuilder() { + void shouldCreateBuilder() { this.contextRunner.run((context) -> { WebClient.Builder builder = context.getBean(WebClient.Builder.class); WebClient webClient = builder.build(); @@ -62,7 +62,7 @@ public class WebClientAutoConfigurationTests { } @Test - public void shouldCustomizeClientCodecs() { + void shouldCustomizeClientCodecs() { this.contextRunner.withUserConfiguration(CodecConfiguration.class).run((context) -> { WebClient.Builder builder = context.getBean(WebClient.Builder.class); CodecCustomizer codecCustomizer = context.getBean(CodecCustomizer.class); @@ -74,7 +74,7 @@ public class WebClientAutoConfigurationTests { } @Test - public void webClientShouldApplyCustomizers() { + void webClientShouldApplyCustomizers() { this.contextRunner.withUserConfiguration(WebClientCustomizerConfig.class).run((context) -> { WebClient.Builder builder = context.getBean(WebClient.Builder.class); WebClientCustomizer customizer = context.getBean("webClientCustomizer", WebClientCustomizer.class); @@ -84,7 +84,7 @@ public class WebClientAutoConfigurationTests { } @Test - public void shouldGetPrototypeScopedBean() { + void shouldGetPrototypeScopedBean() { this.contextRunner.withUserConfiguration(WebClientCustomizerConfig.class).run((context) -> { ClientHttpResponse response = mock(ClientHttpResponse.class); ClientHttpConnector firstConnector = mock(ClientHttpConnector.class); @@ -107,7 +107,7 @@ public class WebClientAutoConfigurationTests { } @Test - public void shouldNotCreateClientBuilderIfAlreadyPresent() { + void shouldNotCreateClientBuilderIfAlreadyPresent() { this.contextRunner.withUserConfiguration(WebClientCustomizerConfig.class, CustomWebClientBuilderConfig.class) .run((context) -> { WebClient.Builder builder = context.getBean(WebClient.Builder.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ConditionalOnMissingFilterBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ConditionalOnMissingFilterBeanTests.java index cff6783f04f..27639e6907f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ConditionalOnMissingFilterBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ConditionalOnMissingFilterBeanTests.java @@ -41,58 +41,58 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConditionalOnMissingFilterBeanTests { +class ConditionalOnMissingFilterBeanTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test - public void outcomeWhenValueIsOfMissingBeanReturnsMatch() { + void outcomeWhenValueIsOfMissingBeanReturnsMatch() { this.contextRunner.withUserConfiguration(WithoutTestFilterConfig.class, OnMissingWithValueConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myOtherFilter", "testFilter"))); } @Test - public void outcomeWhenValueIsOfExistingBeanReturnsNoMatch() { + void outcomeWhenValueIsOfExistingBeanReturnsNoMatch() { this.contextRunner.withUserConfiguration(WithTestFilterConfig.class, OnMissingWithValueConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myTestFilter"))); } @Test - public void outcomeWhenValueIsOfMissingBeanRegistrationReturnsMatch() { + void outcomeWhenValueIsOfMissingBeanRegistrationReturnsMatch() { this.contextRunner .withUserConfiguration(WithoutTestFilterRegistrationConfig.class, OnMissingWithValueConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myOtherFilter", "testFilter"))); } @Test - public void outcomeWhenValueIsOfExistingBeanRegistrationReturnsNoMatch() { + void outcomeWhenValueIsOfExistingBeanRegistrationReturnsNoMatch() { this.contextRunner.withUserConfiguration(WithTestFilterRegistrationConfig.class, OnMissingWithValueConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myTestFilter"))); } @Test - public void outcomeWhenReturnTypeIsOfExistingBeanReturnsNoMatch() { + void outcomeWhenReturnTypeIsOfExistingBeanReturnsNoMatch() { this.contextRunner.withUserConfiguration(WithTestFilterConfig.class, OnMissingWithReturnTypeConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myTestFilter"))); } @Test - public void outcomeWhenReturnTypeIsOfExistingBeanRegistrationReturnsNoMatch() { + void outcomeWhenReturnTypeIsOfExistingBeanRegistrationReturnsNoMatch() { this.contextRunner .withUserConfiguration(WithTestFilterRegistrationConfig.class, OnMissingWithReturnTypeConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myTestFilter"))); } @Test - public void outcomeWhenReturnRegistrationTypeIsOfExistingBeanReturnsNoMatch() { + void outcomeWhenReturnRegistrationTypeIsOfExistingBeanReturnsNoMatch() { this.contextRunner .withUserConfiguration(WithTestFilterConfig.class, OnMissingWithReturnRegistrationTypeConfig.class) .run((context) -> assertThat(context).satisfies(filterBeanRequirement("myTestFilter"))); } @Test - public void outcomeWhenReturnRegistrationTypeIsOfExistingBeanRegistrationReturnsNoMatch() { + void outcomeWhenReturnRegistrationTypeIsOfExistingBeanRegistrationReturnsNoMatch() { this.contextRunner .withUserConfiguration(WithTestFilterRegistrationConfig.class, OnMissingWithReturnRegistrationTypeConfig.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfigurationTests.java index f8d62dce7aa..1f304c3b911 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfigurationTests.java @@ -44,13 +44,13 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Brian Clozel */ -public class DispatcherServletAutoConfigurationTests { +class DispatcherServletAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class)); @Test - public void registrationProperties() { + void registrationProperties() { this.contextRunner.run((context) -> { assertThat(context.getBean(DispatcherServlet.class)).isNotNull(); ServletRegistrationBean registration = context.getBean(ServletRegistrationBean.class); @@ -59,7 +59,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void registrationNonServletBean() { + void registrationNonServletBean() { this.contextRunner.withUserConfiguration(NonServletConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(ServletRegistrationBean.class); assertThat(context).doesNotHaveBean(DispatcherServlet.class); @@ -70,7 +70,7 @@ public class DispatcherServletAutoConfigurationTests { // If a DispatcherServlet instance is registered with a name different // from the default one, we're registering one anyway @Test - public void registrationOverrideWithDispatcherServletWrongName() { + void registrationOverrideWithDispatcherServletWrongName() { this.contextRunner .withUserConfiguration(CustomDispatcherServletDifferentName.class, CustomDispatcherServletPath.class) .run((context) -> { @@ -82,7 +82,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void registrationOverrideWithAutowiredServlet() { + void registrationOverrideWithAutowiredServlet() { this.contextRunner.withUserConfiguration(CustomAutowiredRegistration.class, CustomDispatcherServletPath.class) .run((context) -> { ServletRegistrationBean registration = context.getBean(ServletRegistrationBean.class); @@ -93,7 +93,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void servletPath() { + void servletPath() { this.contextRunner.withPropertyValues("spring.mvc.servlet.path:/spring").run((context) -> { assertThat(context.getBean(DispatcherServlet.class)).isNotNull(); ServletRegistrationBean registration = context.getBean(ServletRegistrationBean.class); @@ -104,7 +104,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void dispatcherServletPathWhenCustomDispatcherServletSameNameShouldReturnConfiguredServletPath() { + void dispatcherServletPathWhenCustomDispatcherServletSameNameShouldReturnConfiguredServletPath() { this.contextRunner.withUserConfiguration(CustomDispatcherServletSameName.class) .withPropertyValues("spring.mvc.servlet.path:/spring") .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()) @@ -112,20 +112,20 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void dispatcherServletPathNotCreatedWhenDefaultDispatcherServletNotAvailable() { + void dispatcherServletPathNotCreatedWhenDefaultDispatcherServletNotAvailable() { this.contextRunner .withUserConfiguration(CustomDispatcherServletDifferentName.class, NonServletConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(DispatcherServletPath.class)); } @Test - public void dispatcherServletPathNotCreatedWhenCustomRegistrationBeanPresent() { + void dispatcherServletPathNotCreatedWhenCustomRegistrationBeanPresent() { this.contextRunner.withUserConfiguration(CustomDispatcherServletRegistration.class) .run((context) -> assertThat(context).doesNotHaveBean(DispatcherServletPath.class)); } @Test - public void multipartConfig() { + void multipartConfig() { this.contextRunner.withUserConfiguration(MultipartConfiguration.class).run((context) -> { ServletRegistrationBean registration = context.getBean(ServletRegistrationBean.class); assertThat(registration.getMultipartConfig()).isNotNull(); @@ -133,7 +133,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void renamesMultipartResolver() { + void renamesMultipartResolver() { this.contextRunner.withUserConfiguration(MultipartResolverConfiguration.class).run((context) -> { DispatcherServlet dispatcherServlet = context.getBean(DispatcherServlet.class); dispatcherServlet.onApplicationEvent(new ContextRefreshedEvent(context)); @@ -142,7 +142,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void dispatcherServletDefaultConfig() { + void dispatcherServletDefaultConfig() { this.contextRunner.run((context) -> { DispatcherServlet dispatcherServlet = context.getBean(DispatcherServlet.class); assertThat(dispatcherServlet).extracting("throwExceptionIfNoHandlerFound").containsExactly(false); @@ -155,7 +155,7 @@ public class DispatcherServletAutoConfigurationTests { } @Test - public void dispatcherServletCustomConfig() { + void dispatcherServletCustomConfig() { this.contextRunner.withPropertyValues("spring.mvc.throw-exception-if-no-handler-found:true", "spring.mvc.dispatch-options-request:false", "spring.mvc.dispatch-trace-request:true", "spring.mvc.servlet.load-on-startup=5").run((context) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletPathTests.java index e953c3c9489..af10868b771 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletPathTests.java @@ -25,52 +25,52 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class DispatcherServletPathTests { +class DispatcherServletPathTests { @Test - public void getRelativePathReturnsRelativePath() { + void getRelativePathReturnsRelativePath() { assertThat(((DispatcherServletPath) () -> "spring").getRelativePath("boot")).isEqualTo("spring/boot"); assertThat(((DispatcherServletPath) () -> "spring/").getRelativePath("boot")).isEqualTo("spring/boot"); assertThat(((DispatcherServletPath) () -> "spring").getRelativePath("/boot")).isEqualTo("spring/boot"); } @Test - public void getPrefixWhenHasSimplePathReturnPath() { + void getPrefixWhenHasSimplePathReturnPath() { assertThat(((DispatcherServletPath) () -> "spring").getPrefix()).isEqualTo("spring"); } @Test - public void getPrefixWhenHasPatternRemovesPattern() { + void getPrefixWhenHasPatternRemovesPattern() { assertThat(((DispatcherServletPath) () -> "spring/*.do").getPrefix()).isEqualTo("spring"); } @Test - public void getPathWhenPathEndsWithSlashRemovesSlash() { + void getPathWhenPathEndsWithSlashRemovesSlash() { assertThat(((DispatcherServletPath) () -> "spring/").getPrefix()).isEqualTo("spring"); } @Test - public void getServletUrlMappingWhenPathIsEmptyReturnsSlash() { + void getServletUrlMappingWhenPathIsEmptyReturnsSlash() { assertThat(((DispatcherServletPath) () -> "").getServletUrlMapping()).isEqualTo("/"); } @Test - public void getServletUrlMappingWhenPathIsSlashReturnsSlash() { + void getServletUrlMappingWhenPathIsSlashReturnsSlash() { assertThat(((DispatcherServletPath) () -> "/").getServletUrlMapping()).isEqualTo("/"); } @Test - public void getServletUrlMappingWhenPathContainsStarReturnsPath() { + void getServletUrlMappingWhenPathContainsStarReturnsPath() { assertThat(((DispatcherServletPath) () -> "spring/*.do").getServletUrlMapping()).isEqualTo("spring/*.do"); } @Test - public void getServletUrlMappingWhenHasPathNotEndingSlashReturnsSlashStarPattern() { + void getServletUrlMappingWhenHasPathNotEndingSlashReturnsSlashStarPattern() { assertThat(((DispatcherServletPath) () -> "spring/boot").getServletUrlMapping()).isEqualTo("spring/boot/*"); } @Test - public void getServletUrlMappingWhenHasPathEndingWithSlashReturnsSlashStarPattern() { + void getServletUrlMappingWhenHasPathEndingWithSlashReturnsSlashStarPattern() { assertThat(((DispatcherServletPath) () -> "spring/boot/").getServletUrlMapping()).isEqualTo("spring/boot/*"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java index cb8c2dd38a3..65978bdc904 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java @@ -31,31 +31,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class DispatcherServletRegistrationBeanTests { +class DispatcherServletRegistrationBeanTests { @Test - public void createWhenPathIsNullThrowsException() { + void createWhenPathIsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DispatcherServletRegistrationBean(new DispatcherServlet(), null)) .withMessageContaining("Path must not be null"); } @Test - public void getPathReturnsPath() { + void getPathReturnsPath() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(new DispatcherServlet(), "/test"); assertThat(bean.getPath()).isEqualTo("/test"); } @Test - public void getUrlMappingsReturnsSinglePathMappedPattern() { + void getUrlMappingsReturnsSinglePathMappedPattern() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(new DispatcherServlet(), "/test"); assertThat(bean.getUrlMappings()).containsOnly("/test/*"); } @Test - public void setUrlMappingsCannotBeCalled() { + void setUrlMappingsCannotBeCalled() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(new DispatcherServlet(), "/test"); assertThatExceptionOfType(UnsupportedOperationException.class) @@ -63,7 +63,7 @@ public class DispatcherServletRegistrationBeanTests { } @Test - public void addUrlMappingsCannotBeCalled() { + void addUrlMappingsCannotBeCalled() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean(new DispatcherServlet(), "/test"); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> bean.addUrlMappings("/test")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/FilterOrderingIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/FilterOrderingIntegrationTests.java index ca4d9f0fd8d..70e7b1acac0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/FilterOrderingIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/FilterOrderingIntegrationTests.java @@ -54,7 +54,7 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Eddú Meléndez */ -public class FilterOrderingIntegrationTests { +class FilterOrderingIntegrationTests { private AnnotationConfigServletWebServerApplicationContext context; @@ -66,7 +66,7 @@ public class FilterOrderingIntegrationTests { } @Test - public void testFilterOrdering() { + void testFilterOrdering() { load(); List registeredFilters = this.context.getBean(MockServletWebServerFactory.class) .getWebServer().getRegisteredFilters(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java index ee83302cca1..7f9cc0f0f0e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Stephane Nicoll */ -public class HttpEncodingAutoConfigurationTests { +class HttpEncodingAutoConfigurationTests { private AnnotationConfigServletWebApplicationContext context; @@ -61,63 +61,63 @@ public class HttpEncodingAutoConfigurationTests { } @Test - public void defaultConfiguration() { + void defaultConfiguration() { load(EmptyConfiguration.class); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, false); } @Test - public void disableConfiguration() { + void disableConfiguration() { load(EmptyConfiguration.class, "spring.http.encoding.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(CharacterEncodingFilter.class)); } @Test - public void customConfiguration() { + void customConfiguration() { load(EmptyConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", "spring.http.encoding.force:false"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "ISO-8859-15", false, false); } @Test - public void customFilterConfiguration() { + void customFilterConfiguration() { load(FilterConfiguration.class, "spring.http.encoding.charset:ISO-8859-15", "spring.http.encoding.force:false"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "US-ASCII", false, false); } @Test - public void forceRequest() { + void forceRequest() { load(EmptyConfiguration.class, "spring.http.encoding.force-request:false"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", false, false); } @Test - public void forceResponse() { + void forceResponse() { load(EmptyConfiguration.class, "spring.http.encoding.force-response:true"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, true); } @Test - public void forceRequestOverridesForce() { + void forceRequestOverridesForce() { load(EmptyConfiguration.class, "spring.http.encoding.force:true", "spring.http.encoding.force-request:false"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", false, true); } @Test - public void forceResponseOverridesForce() { + void forceResponseOverridesForce() { load(EmptyConfiguration.class, "spring.http.encoding.force:true", "spring.http.encoding.force-response:false"); CharacterEncodingFilter filter = this.context.getBean(CharacterEncodingFilter.class); assertCharacterEncodingFilter(filter, "UTF-8", true, false); } @Test - public void filterIsOrderedHighest() { + void filterIsOrderedHighest() { load(OrderedConfiguration.class); List beans = new ArrayList<>(this.context.getBeansOfType(Filter.class).values()); AnnotationAwareOrderComparator.sort(beans); @@ -126,7 +126,7 @@ public class HttpEncodingAutoConfigurationTests { } @Test - public void noLocaleCharsetMapping() { + void noLocaleCharsetMapping() { load(EmptyConfiguration.class); Map> beans = getWebServerFactoryCustomizerBeans(); assertThat(beans.size()).isEqualTo(1); @@ -134,7 +134,7 @@ public class HttpEncodingAutoConfigurationTests { } @Test - public void customLocaleCharsetMappings() { + void customLocaleCharsetMappings() { load(EmptyConfiguration.class, "spring.http.encoding.mapping.en:UTF-8", "spring.http.encoding.mapping.fr_FR:UTF-8"); Map> beans = getWebServerFactoryCustomizerBeans(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JerseyApplicationPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JerseyApplicationPathTests.java index be6deb1f55f..77a8fe9f1a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JerseyApplicationPathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JerseyApplicationPathTests.java @@ -24,10 +24,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class JerseyApplicationPathTests { +class JerseyApplicationPathTests { @Test - public void getRelativePathReturnsRelativePath() { + void getRelativePathReturnsRelativePath() { assertThat(((JerseyApplicationPath) () -> "spring").getRelativePath("boot")).isEqualTo("spring/boot"); assertThat(((JerseyApplicationPath) () -> "spring/").getRelativePath("boot")).isEqualTo("spring/boot"); assertThat(((JerseyApplicationPath) () -> "spring").getRelativePath("/boot")).isEqualTo("spring/boot"); @@ -35,47 +35,47 @@ public class JerseyApplicationPathTests { } @Test - public void getPrefixWhenHasSimplePathReturnPath() { + void getPrefixWhenHasSimplePathReturnPath() { assertThat(((JerseyApplicationPath) () -> "spring").getPrefix()).isEqualTo("spring"); } @Test - public void getPrefixWhenHasPatternRemovesPattern() { + void getPrefixWhenHasPatternRemovesPattern() { assertThat(((JerseyApplicationPath) () -> "spring/*.do").getPrefix()).isEqualTo("spring"); } @Test - public void getPrefixWhenPathEndsWithSlashRemovesSlash() { + void getPrefixWhenPathEndsWithSlashRemovesSlash() { assertThat(((JerseyApplicationPath) () -> "spring/").getPrefix()).isEqualTo("spring"); } @Test - public void getUrlMappingWhenPathIsEmptyReturnsSlash() { + void getUrlMappingWhenPathIsEmptyReturnsSlash() { assertThat(((JerseyApplicationPath) () -> "").getUrlMapping()).isEqualTo("/*"); } @Test - public void getUrlMappingWhenPathIsSlashReturnsSlash() { + void getUrlMappingWhenPathIsSlashReturnsSlash() { assertThat(((JerseyApplicationPath) () -> "/").getUrlMapping()).isEqualTo("/*"); } @Test - public void getUrlMappingWhenPathContainsStarReturnsPath() { + void getUrlMappingWhenPathContainsStarReturnsPath() { assertThat(((JerseyApplicationPath) () -> "/spring/*.do").getUrlMapping()).isEqualTo("/spring/*.do"); } @Test - public void getUrlMappingWhenHasPathNotEndingSlashReturnsSlashStarPattern() { + void getUrlMappingWhenHasPathNotEndingSlashReturnsSlashStarPattern() { assertThat(((JerseyApplicationPath) () -> "/spring/boot").getUrlMapping()).isEqualTo("/spring/boot/*"); } @Test - public void getUrlMappingWhenHasPathDoesNotStartWithSlashPrependsSlash() { + void getUrlMappingWhenHasPathDoesNotStartWithSlashPrependsSlash() { assertThat(((JerseyApplicationPath) () -> "spring/boot").getUrlMapping()).isEqualTo("/spring/boot/*"); } @Test - public void getUrlMappingWhenHasPathEndingWithSlashReturnsSlashStarPattern() { + void getUrlMappingWhenHasPathEndingWithSlashReturnsSlashStarPattern() { assertThat(((JerseyApplicationPath) () -> "/spring/boot/").getUrlMapping()).isEqualTo("/spring/boot/*"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProviderTests.java index 72424a13c48..01ea06f34de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/JspTemplateAvailabilityProviderTests.java @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Yunkun Huang */ -public class JspTemplateAvailabilityProviderTests { +class JspTemplateAvailabilityProviderTests { private final JspTemplateAvailabilityProvider provider = new JspTemplateAvailabilityProvider(); @@ -38,18 +38,18 @@ public class JspTemplateAvailabilityProviderTests { private final MockEnvironment environment = new MockEnvironment(); @Test - public void availabilityOfTemplateThatDoesNotExist() { + void availabilityOfTemplateThatDoesNotExist() { assertThat(isTemplateAvailable("whatever")).isFalse(); } @Test - public void availabilityOfTemplateWithCustomPrefix() { + void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); assertThat(isTemplateAvailable("custom.jsp")).isTrue(); } @Test - public void availabilityOfTemplateWithCustomSuffix() { + void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); this.environment.setProperty("spring.mvc.view.suffix", ".jsp"); assertThat(isTemplateAvailable("suffixed")).isTrue(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfigurationTests.java index fa338171ebe..1f1d73be9ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfigurationTests.java @@ -61,7 +61,7 @@ import static org.mockito.Mockito.mock; * @author Ivan Sopov * @author Toshiaki Maki */ -public class MultipartAutoConfigurationTests { +class MultipartAutoConfigurationTests { private AnnotationConfigServletWebServerApplicationContext context; @@ -73,7 +73,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithNothing() throws Exception { + void webServerWithNothing() throws Exception { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithNothing.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); @@ -84,7 +84,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithNoMultipartJettyConfiguration() { + void webServerWithNoMultipartJettyConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithNoMultipartJetty.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); @@ -95,7 +95,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithNoMultipartUndertowConfiguration() { + void webServerWithNoMultipartUndertowConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithNoMultipartUndertow.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); @@ -106,7 +106,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithNoMultipartTomcatConfiguration() { + void webServerWithNoMultipartTomcatConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithNoMultipartTomcat.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); @@ -117,7 +117,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithAutomatedMultipartJettyConfiguration() { + void webServerWithAutomatedMultipartJettyConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithEverythingJetty.class, BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); @@ -127,7 +127,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithAutomatedMultipartTomcatConfiguration() { + void webServerWithAutomatedMultipartTomcatConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithEverythingTomcat.class, BaseConfiguration.class); new RestTemplate().getForObject("http://localhost:" + this.context.getWebServer().getPort() + "/", @@ -139,7 +139,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithAutomatedMultipartUndertowConfiguration() { + void webServerWithAutomatedMultipartUndertowConfiguration() { this.context = new AnnotationConfigServletWebServerApplicationContext(WebServerWithEverythingUndertow.class, BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); @@ -149,12 +149,12 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithMultipartConfigDisabled() { + void webServerWithMultipartConfigDisabled() { testWebServerWithCustomMultipartConfigEnabledSetting("false", 0); } @Test - public void webServerWithMultipartConfigEnabled() { + void webServerWithMultipartConfigEnabled() { testWebServerWithCustomMultipartConfigEnabledSetting("true", 1); } @@ -170,7 +170,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void webServerWithCustomMultipartResolver() { + void webServerWithCustomMultipartResolver() { this.context = new AnnotationConfigServletWebServerApplicationContext( WebServerWithCustomMultipartResolver.class, BaseConfiguration.class); MultipartResolver multipartResolver = this.context.getBean(MultipartResolver.class); @@ -179,7 +179,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void containerWithCommonsMultipartResolver() { + void containerWithCommonsMultipartResolver() { this.context = new AnnotationConfigServletWebServerApplicationContext( ContainerWithCommonsMultipartResolver.class, BaseConfiguration.class); MultipartResolver multipartResolver = this.context.getBean(MultipartResolver.class); @@ -188,7 +188,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void configureResolveLazily() { + void configureResolveLazily() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues.of("spring.servlet.multipart.resolve-lazily=true").applyTo(this.context); this.context.register(WebServerWithNothing.class, BaseConfiguration.class); @@ -199,7 +199,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void configureMultipartProperties() { + void configureMultipartProperties() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues .of("spring.servlet.multipart.max-file-size=2048KB", "spring.servlet.multipart.max-request-size=15MB") @@ -212,7 +212,7 @@ public class MultipartAutoConfigurationTests { } @Test - public void configureMultipartPropertiesWithRawLongValues() { + void configureMultipartPropertiesWithRawLongValues() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues .of("spring.servlet.multipart.max-file-size=512", "spring.servlet.multipart.max-request-size=2048") diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfigurationTests.java index 7e2ebb7cee1..01b8142f54d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfigurationTests.java @@ -70,7 +70,7 @@ import static org.mockito.Mockito.verify; * @author Raheela Aslam * @author Madhura Bhave */ -public class ServletWebServerFactoryAutoConfigurationTests { +class ServletWebServerFactoryAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) @@ -79,17 +79,17 @@ public class ServletWebServerFactoryAutoConfigurationTests { .withUserConfiguration(WebServerConfiguration.class); @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.contextRunner.run(verifyContext()); } @Test - public void contextAlreadyHasDispatcherServletWithDefaultName() { + void contextAlreadyHasDispatcherServletWithDefaultName() { this.contextRunner.withUserConfiguration(DispatcherServletConfiguration.class).run(verifyContext()); } @Test - public void contextAlreadyHasDispatcherServlet() { + void contextAlreadyHasDispatcherServlet() { this.contextRunner.withUserConfiguration(SpringServletConfiguration.class).run((context) -> { verifyContext(context); assertThat(context.getBeanNamesForType(DispatcherServlet.class)).hasSize(2); @@ -97,7 +97,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void contextAlreadyHasNonDispatcherServlet() { + void contextAlreadyHasNonDispatcherServlet() { this.contextRunner.withUserConfiguration(NonSpringServletConfiguration.class).run((context) -> { verifyContext(context); // the non default servlet is still registered assertThat(context).doesNotHaveBean(DispatcherServlet.class); @@ -105,7 +105,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void contextAlreadyHasNonServlet() { + void contextAlreadyHasNonServlet() { this.contextRunner.withUserConfiguration(NonServletConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(DispatcherServlet.class); assertThat(context).doesNotHaveBean(Servlet.class); @@ -113,7 +113,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void contextAlreadyHasDispatcherServletAndRegistration() { + void contextAlreadyHasDispatcherServletAndRegistration() { this.contextRunner.withUserConfiguration(DispatcherServletWithRegistrationConfiguration.class) .run((context) -> { verifyContext(context); @@ -122,12 +122,12 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void webServerHasNoServletContext() { + void webServerHasNoServletContext() { this.contextRunner.withUserConfiguration(EnsureWebServerHasNoServletContext.class).run(verifyContext()); } @Test - public void customizeWebServerFactoryThroughCallback() { + void customizeWebServerFactoryThroughCallback() { this.contextRunner.withUserConfiguration(CallbackEmbeddedServerFactoryCustomizer.class).run((context) -> { verifyContext(context); assertThat(context.getBean(MockServletWebServerFactory.class).getPort()).isEqualTo(9000); @@ -135,7 +135,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void initParametersAreConfiguredOnTheServletContext() { + void initParametersAreConfiguredOnTheServletContext() { this.contextRunner.withPropertyValues("server.servlet.context-parameters.a:alpha", "server.servlet.context-parameters.b:bravo").run((context) -> { ServletContext servletContext = context.getServletContext(); @@ -145,7 +145,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void jettyServerCustomizerBeanIsAddedToFactory() { + void jettyServerCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) @@ -158,7 +158,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void undertowDeploymentInfoCustomizerBeanIsAddedToFactory() { + void undertowDeploymentInfoCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) @@ -171,7 +171,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void undertowBuilderCustomizerBeanIsAddedToFactory() { + void undertowBuilderCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) @@ -184,7 +184,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatConnectorCustomizerBeanIsAddedToFactory() { + void tomcatConnectorCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class)) @@ -196,7 +196,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatContextCustomizerBeanIsAddedToFactory() { + void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class)); @@ -207,7 +207,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { + void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class)) @@ -219,7 +219,7 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void forwardedHeaderFilterShouldBeConfigured() { + void forwardedHeaderFilterShouldBeConfigured() { this.contextRunner.withPropertyValues("server.forward-headers-strategy=framework").run((context) -> { assertThat(context).hasSingleBean(FilterRegistrationBean.class); Filter filter = context.getBean(FilterRegistrationBean.class).getFilter(); @@ -228,13 +228,13 @@ public class ServletWebServerFactoryAutoConfigurationTests { } @Test - public void forwardedHeaderFilterWhenStrategyNotFilterShouldNotBeConfigured() { + void forwardedHeaderFilterWhenStrategyNotFilterShouldNotBeConfigured() { this.contextRunner.withPropertyValues("server.forward-headers-strategy=native") .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); } @Test - public void forwardedHeaderFilterWhenFilterAlreadyRegisteredShouldBackOff() { + void forwardedHeaderFilterWhenFilterAlreadyRegisteredShouldBackOff() { this.contextRunner.withUserConfiguration(ForwardedHeaderFilterConfiguration.class) .withPropertyValues("server.forward-headers-strategy=framework") .run((context) -> assertThat(context).hasSingleBean(FilterRegistrationBean.class)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizerTests.java index ccc277b0fdb..52973f1703b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryCustomizerTests.java @@ -47,7 +47,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Yunkun Huang */ -public class ServletWebServerFactoryCustomizerTests { +class ServletWebServerFactoryCustomizerTests { private final ServerProperties properties = new ServerProperties(); @@ -59,14 +59,14 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void testDefaultDisplayName() { + void testDefaultDisplayName() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); verify(factory).setDisplayName("application"); } @Test - public void testCustomizeDisplayName() { + void testCustomizeDisplayName() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.properties.getServlet().setApplicationDisplayName("TestName"); this.customizer.customize(factory); @@ -74,7 +74,7 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void testCustomizeSsl() { + void testCustomizeSsl() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); Ssl ssl = mock(Ssl.class); this.properties.setSsl(ssl); @@ -83,14 +83,14 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void testCustomizeJsp() { + void testCustomizeJsp() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); verify(factory).setJsp(any(Jsp.class)); } @Test - public void customizeSessionProperties() throws Exception { + void customizeSessionProperties() throws Exception { Map map = new HashMap<>(); map.put("server.servlet.session.timeout", "123"); map.put("server.servlet.session.tracking-modes", "cookie,url"); @@ -118,7 +118,7 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void testCustomizeTomcatPort() { + void testCustomizeTomcatPort() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.properties.setPort(8080); this.customizer.customize(factory); @@ -126,7 +126,7 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void customizeServletDisplayName() { + void customizeServletDisplayName() { Map map = new HashMap<>(); map.put("server.servlet.application-display-name", "MyBootApp"); bindProperties(map); @@ -136,7 +136,7 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void testCustomizeTomcatMinSpareThreads() { + void testCustomizeTomcatMinSpareThreads() { Map map = new HashMap<>(); map.put("server.tomcat.min-spare-threads", "10"); bindProperties(map); @@ -144,7 +144,7 @@ public class ServletWebServerFactoryCustomizerTests { } @Test - public void sessionStoreDir() { + void sessionStoreDir() { Map map = new HashMap<>(); map.put("server.servlet.session.store-dir", "myfolder"); bindProperties(map); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerServletContextListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerServletContextListenerTests.java index 920791a7264..4d345a35672 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerServletContextListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerServletContextListenerTests.java @@ -40,35 +40,35 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class ServletWebServerServletContextListenerTests { +class ServletWebServerServletContextListenerTests { @Test - public void registeredServletContextListenerBeanIsCalledByJetty() { + void registeredServletContextListenerBeanIsCalledByJetty() { registeredServletContextListenerBeanIsCalled(JettyConfiguration.class); } @Test - public void registeredServletContextListenerBeanIsCalledByTomcat() { + void registeredServletContextListenerBeanIsCalledByTomcat() { registeredServletContextListenerBeanIsCalled(TomcatConfiguration.class); } @Test - public void registeredServletContextListenerBeanIsCalledByUndertow() { + void registeredServletContextListenerBeanIsCalledByUndertow() { registeredServletContextListenerBeanIsCalled(UndertowConfiguration.class); } @Test - public void servletContextListenerBeanIsCalledByJetty() { + void servletContextListenerBeanIsCalledByJetty() { servletContextListenerBeanIsCalled(JettyConfiguration.class); } @Test - public void servletContextListenerBeanIsCalledByTomcat() { + void servletContextListenerBeanIsCalledByTomcat() { servletContextListenerBeanIsCalled(TomcatConfiguration.class); } @Test - public void servletContextListenerBeanIsCalledByUndertow() { + void servletContextListenerBeanIsCalledByUndertow() { servletContextListenerBeanIsCalled(UndertowConfiguration.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizerTests.java index 1ec2cf419f6..0636e68382f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/TomcatServletWebServerFactoryCustomizerTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class TomcatServletWebServerFactoryCustomizerTests { +class TomcatServletWebServerFactoryCustomizerTests { private TomcatServletWebServerFactoryCustomizer customizer; @@ -53,13 +53,13 @@ public class TomcatServletWebServerFactoryCustomizerTests { } @Test - public void customTldSkip() { + void customTldSkip() { bind("server.tomcat.additional-tld-skip-patterns=foo.jar,bar.jar"); testCustomTldSkip("foo.jar", "bar.jar"); } @Test - public void customTldSkipAsList() { + void customTldSkipAsList() { bind("server.tomcat.additional-tld-skip-patterns[0]=biz.jar", "server.tomcat.additional-tld-skip-patterns[1]=bah.jar"); testCustomTldSkip("biz.jar", "bah.jar"); @@ -72,7 +72,7 @@ public class TomcatServletWebServerFactoryCustomizerTests { } @Test - public void redirectContextRootCanBeConfigured() { + void redirectContextRootCanBeConfigured() { bind("server.tomcat.redirect-context-root=false"); ServerProperties.Tomcat tomcat = this.serverProperties.getTomcat(); assertThat(tomcat.getRedirectContextRoot()).isFalse(); @@ -82,7 +82,7 @@ public class TomcatServletWebServerFactoryCustomizerTests { } @Test - public void useRelativeRedirectsCanBeConfigured() { + void useRelativeRedirectsCanBeConfigured() { bind("server.tomcat.use-relative-redirects=true"); assertThat(this.serverProperties.getTomcat().getUseRelativeRedirects()).isTrue(); TomcatWebServer server = customizeAndGetServer(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java index 3cf88c3188a..ab7ee064f50 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java @@ -124,7 +124,7 @@ import static org.mockito.Mockito.mock; * @author Kristine Jetzke * @author Artsiom Yudovin */ -public class WebMvcAutoConfigurationTests { +class WebMvcAutoConfigurationTests { private static final MockServletWebServerFactory webServerFactory = new MockServletWebServerFactory(); @@ -134,7 +134,7 @@ public class WebMvcAutoConfigurationTests { .withUserConfiguration(Config.class); @Test - public void handlerAdaptersCreated() { + void handlerAdaptersCreated() { this.contextRunner.run((context) -> { assertThat(context).getBeans(HandlerAdapter.class).hasSize(4); assertThat(context.getBean(RequestMappingHandlerAdapter.class).getMessageConverters()).isNotEmpty() @@ -143,12 +143,12 @@ public class WebMvcAutoConfigurationTests { } @Test - public void handlerMappingsCreated() { + void handlerMappingsCreated() { this.contextRunner.run((context) -> assertThat(context).getBeans(HandlerMapping.class).hasSize(6)); } @Test - public void resourceHandlerMapping() { + void resourceHandlerMapping() { this.contextRunner.run((context) -> { Map> locations = getResourceMappingLocations(context); assertThat(locations.get("/**")).hasSize(5); @@ -163,7 +163,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void customResourceHandlerMapping() { + void customResourceHandlerMapping() { this.contextRunner.withPropertyValues("spring.mvc.static-path-pattern:/static/**").run((context) -> { Map> locations = getResourceMappingLocations(context); assertThat(locations.get("/static/**")).hasSize(5); @@ -172,7 +172,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerMappingOverrideWebjars() { + void resourceHandlerMappingOverrideWebjars() { this.contextRunner.withUserConfiguration(WebJars.class).run((context) -> { Map> locations = getResourceMappingLocations(context); assertThat(locations.get("/webjars/**")).hasSize(1); @@ -181,7 +181,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerMappingOverrideAll() { + void resourceHandlerMappingOverrideAll() { this.contextRunner.withUserConfiguration(AllResources.class).run((context) -> { Map> locations = getResourceMappingLocations(context); assertThat(locations.get("/**")).hasSize(1); @@ -190,13 +190,13 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerMappingDisabled() { + void resourceHandlerMappingDisabled() { this.contextRunner.withPropertyValues("spring.resources.add-mappings:false") .run((context) -> assertThat(context.getBean("resourceHandlerMapping")).isEqualTo(null)); } @Test - public void resourceHandlerChainEnabled() { + void resourceHandlerChainEnabled() { this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true").run((context) -> { assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(2); assertThat(getResourceTransformers(context, "/webjars/**")).hasSize(1); @@ -208,7 +208,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerFixedStrategyEnabled() { + void resourceHandlerFixedStrategyEnabled() { this.contextRunner.withPropertyValues("spring.resources.chain.strategy.fixed.enabled:true", "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js").run((context) -> { @@ -225,7 +225,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerContentStrategyEnabled() { + void resourceHandlerContentStrategyEnabled() { this.contextRunner.withPropertyValues("spring.resources.chain.strategy.content.enabled:true", "spring.resources.chain.strategy.content.paths:/**,/*.png").run((context) -> { assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(3); @@ -241,7 +241,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void resourceHandlerChainCustomized() { + void resourceHandlerChainCustomized() { this.contextRunner .withPropertyValues("spring.resources.chain.enabled:true", "spring.resources.chain.cache:false", "spring.resources.chain.strategy.content.enabled:true", @@ -266,12 +266,12 @@ public class WebMvcAutoConfigurationTests { } @Test - public void noLocaleResolver() { + void noLocaleResolver() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LocaleResolver.class)); } @Test - public void overrideLocale() { + void overrideLocale() { this.contextRunner.withPropertyValues("spring.mvc.locale:en_UK", "spring.mvc.locale-resolver=fixed") .run((loader) -> { // mock request and set user preferred locale @@ -288,7 +288,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void useAcceptHeaderLocale() { + void useAcceptHeaderLocale() { this.contextRunner.withPropertyValues("spring.mvc.locale:en_UK").run((loader) -> { // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); @@ -303,7 +303,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void useDefaultLocaleIfAcceptHeaderNoSet() { + void useDefaultLocaleIfAcceptHeaderNoSet() { this.contextRunner.withPropertyValues("spring.mvc.locale:en_UK").run((context) -> { // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); @@ -316,7 +316,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void noDateFormat() { + void noDateFormat() { this.contextRunner.run((context) -> { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); @@ -326,7 +326,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void overrideDateFormat() { + void overrideDateFormat() { this.contextRunner.withPropertyValues("spring.mvc.date-format:dd*MM*yyyy").run((context) -> { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); @@ -335,47 +335,47 @@ public class WebMvcAutoConfigurationTests { } @Test - public void noMessageCodesResolver() { + void noMessageCodesResolver() { this.contextRunner.run( (context) -> assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class).getMessageCodesResolver()) .isNull()); } @Test - public void overrideMessageCodesFormat() { + void overrideMessageCodesFormat() { this.contextRunner.withPropertyValues("spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE").run( (context) -> assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class).getMessageCodesResolver()) .isNotNull()); } @Test - public void ignoreDefaultModelOnRedirectIsTrue() { + void ignoreDefaultModelOnRedirectIsTrue() { this.contextRunner.run((context) -> assertThat(context.getBean(RequestMappingHandlerAdapter.class)) .extracting("ignoreDefaultModelOnRedirect").containsExactly(true)); } @Test - public void overrideIgnoreDefaultModelOnRedirect() { + void overrideIgnoreDefaultModelOnRedirect() { this.contextRunner.withPropertyValues("spring.mvc.ignore-default-model-on-redirect:false") .run((context) -> assertThat(context.getBean(RequestMappingHandlerAdapter.class)) .extracting("ignoreDefaultModelOnRedirect").containsExactly(false)); } @Test - public void customViewResolver() { + void customViewResolver() { this.contextRunner.withUserConfiguration(CustomViewResolver.class) .run((context) -> assertThat(context.getBean("viewResolver")).isInstanceOf(MyViewResolver.class)); } @Test - public void customContentNegotiatingViewResolver() { + void customContentNegotiatingViewResolver() { this.contextRunner.withUserConfiguration(CustomContentNegotiatingViewResolver.class) .run((context) -> assertThat(context).getBeanNames(ContentNegotiatingViewResolver.class) .containsOnly("myViewResolver")); } @Test - public void faviconMapping() { + void faviconMapping() { this.contextRunner.run((context) -> { assertThat(context).getBeanNames(ResourceHttpRequestHandler.class).contains("faviconRequestHandler"); assertThat(context).getBeans(SimpleUrlHandlerMapping.class).containsKey("faviconHandlerMapping"); @@ -384,13 +384,13 @@ public class WebMvcAutoConfigurationTests { } @Test - public void faviconMappingUsesStaticLocations() { + void faviconMappingUsesStaticLocations() { this.contextRunner.withPropertyValues("spring.resources.static-locations=classpath:/static") .run((context) -> assertThat(getFaviconMappingLocations(context).get("/**/favicon.ico")).hasSize(3)); } @Test - public void faviconMappingDisabled() { + void faviconMappingDisabled() { this.contextRunner.withPropertyValues("spring.mvc.favicon.enabled:false").run((context) -> { assertThat(context).getBeans(ResourceHttpRequestHandler.class).doesNotContainKey("faviconRequestHandler"); assertThat(context).getBeans(SimpleUrlHandlerMapping.class).doesNotContainKey("faviconHandlerMapping"); @@ -398,13 +398,13 @@ public class WebMvcAutoConfigurationTests { } @Test - public void defaultAsyncRequestTimeout() { + void defaultAsyncRequestTimeout() { this.contextRunner.run((context) -> assertThat(ReflectionTestUtils .getField(context.getBean(RequestMappingHandlerAdapter.class), "asyncRequestTimeout")).isNull()); } @Test - public void customAsyncRequestTimeout() { + void customAsyncRequestTimeout() { this.contextRunner.withPropertyValues("spring.mvc.async.request-timeout:12345") .run((context) -> assertThat(ReflectionTestUtils .getField(context.getBean(RequestMappingHandlerAdapter.class), "asyncRequestTimeout")) @@ -412,7 +412,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void asyncTaskExecutorWithApplicationTaskExecutor() { + void asyncTaskExecutorWithApplicationTaskExecutor() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) .run((context) -> { assertThat(context).hasSingleBean(AsyncTaskExecutor.class); @@ -422,7 +422,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void asyncTaskExecutorWithNonMatchApplicationTaskExecutorBean() { + void asyncTaskExecutorWithNonMatchApplicationTaskExecutorBean() { this.contextRunner.withUserConfiguration(CustomApplicationTaskExecutorConfig.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)).run((context) -> { assertThat(context).doesNotHaveBean(AsyncTaskExecutor.class); @@ -432,7 +432,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void asyncTaskExecutorWithMvcConfigurerCanOverrideExecutor() { + void asyncTaskExecutorWithMvcConfigurerCanOverrideExecutor() { this.contextRunner.withUserConfiguration(CustomAsyncTaskExecutorConfigurer.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) .run((context) -> assertThat(ReflectionTestUtils @@ -441,7 +441,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void asyncTaskExecutorWithCustomNonApplicationTaskExecutor() { + void asyncTaskExecutorWithCustomNonApplicationTaskExecutor() { this.contextRunner.withUserConfiguration(CustomAsyncTaskExecutorConfig.class) .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)).run((context) -> { assertThat(context).hasSingleBean(AsyncTaskExecutor.class); @@ -451,7 +451,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void customMediaTypes() { + void customMediaTypes() { this.contextRunner.withPropertyValues("spring.mvc.contentnegotiation.media-types.yaml:text/yaml", "spring.mvc.contentnegotiation.favor-path-extension:true").run((context) -> { RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); @@ -462,12 +462,12 @@ public class WebMvcAutoConfigurationTests { } @Test - public void formContentFilterIsAutoConfigured() { + void formContentFilterIsAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(OrderedFormContentFilter.class)); } @Test - public void formContentFilterCanBeOverridden() { + void formContentFilterCanBeOverridden() { this.contextRunner.withUserConfiguration(CustomFormContentFilter.class).run((context) -> { assertThat(context).doesNotHaveBean(OrderedFormContentFilter.class); assertThat(context).hasSingleBean(FormContentFilter.class); @@ -475,45 +475,45 @@ public class WebMvcAutoConfigurationTests { } @Test - public void formContentFilterCanBeDisabled() { + void formContentFilterCanBeDisabled() { this.contextRunner.withPropertyValues("spring.mvc.formcontent.filter.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(FormContentFilter.class)); } @Test - public void hiddenHttpMethodFilterCanBeDisabled() { + void hiddenHttpMethodFilterCanBeDisabled() { this.contextRunner.withPropertyValues("spring.mvc.hiddenmethod.filter.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(HiddenHttpMethodFilter.class)); } @Test - public void hiddenHttpMethodFilterEnabledByDefault() { + void hiddenHttpMethodFilterEnabledByDefault() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class)); } @Test - public void customConfigurableWebBindingInitializer() { + void customConfigurableWebBindingInitializer() { this.contextRunner.withUserConfiguration(CustomConfigurableWebBindingInitializer.class).run( (context) -> assertThat(context.getBean(RequestMappingHandlerAdapter.class).getWebBindingInitializer()) .isInstanceOf(CustomWebBindingInitializer.class)); } @Test - public void customRequestMappingHandlerMapping() { + void customRequestMappingHandlerMapping() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerMapping.class) .run((context) -> assertThat(context).getBean(RequestMappingHandlerMapping.class) .isInstanceOf(MyRequestMappingHandlerMapping.class)); } @Test - public void customRequestMappingHandlerAdapter() { + void customRequestMappingHandlerAdapter() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerAdapter.class) .run((context) -> assertThat(context).getBean(RequestMappingHandlerAdapter.class) .isInstanceOf(MyRequestMappingHandlerAdapter.class)); } @Test - public void multipleWebMvcRegistrations() { + void multipleWebMvcRegistrations() { this.contextRunner.withUserConfiguration(MultipleWebMvcRegistrations.class).run((context) -> { assertThat(context.getBean(RequestMappingHandlerMapping.class)) .isNotInstanceOf(MyRequestMappingHandlerMapping.class); @@ -523,12 +523,12 @@ public class WebMvcAutoConfigurationTests { } @Test - public void defaultLogResolvedException() { + void defaultLogResolvedException() { this.contextRunner.run(assertExceptionResolverWarnLoggers((logger) -> assertThat(logger).isNull())); } @Test - public void customLogResolvedException() { + void customLogResolvedException() { this.contextRunner.withPropertyValues("spring.mvc.log-resolved-exception:true") .run(assertExceptionResolverWarnLoggers((logger) -> assertThat(logger).isNotNull())); } @@ -550,7 +550,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void welcomePageHandlerMappingIsAutoConfigured() { + void welcomePageHandlerMappingIsAutoConfigured() { this.contextRunner.withPropertyValues("spring.resources.static-locations:classpath:/welcome-page/") .run((context) -> { assertThat(context).hasSingleBean(WelcomePageHandlerMapping.class); @@ -559,7 +559,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWhenNoValidatorShouldUseDefault() { + void validatorWhenNoValidatorShouldUseDefault() { this.contextRunner.run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -568,7 +568,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWhenNoCustomizationShouldUseAutoConfigured() { + void validatorWhenNoCustomizationShouldUseAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class).containsOnly("defaultValidator"); @@ -583,7 +583,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWithConfigurerShouldUseSpringValidator() { + void validatorWithConfigurerShouldUseSpringValidator() { this.contextRunner.withUserConfiguration(MvcValidator.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -593,7 +593,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWithConfigurerDoesNotExposeJsr303() { + void validatorWithConfigurerDoesNotExposeJsr303() { this.contextRunner.withUserConfiguration(MvcJsr303Validator.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class); @@ -606,7 +606,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWithConfigurerTakesPrecedence() { + void validatorWithConfigurerTakesPrecedence() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(MvcValidator.class).run((context) -> { assertThat(context).hasSingleBean(ValidatorFactory.class); @@ -620,7 +620,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWithCustomSpringValidatorIgnored() { + void validatorWithCustomSpringValidatorIgnored() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(CustomSpringValidator.class).run((context) -> { assertThat(context).getBeanNames(javax.validation.Validator.class).containsOnly("defaultValidator"); @@ -636,7 +636,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { + void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) .withUserConfiguration(CustomJsr303Validator.class).run((context) -> { assertThat(context).doesNotHaveBean(ValidatorFactory.class); @@ -652,13 +652,13 @@ public class WebMvcAutoConfigurationTests { } @Test - public void httpMessageConverterThatUsesConversionServiceDoesNotCreateACycle() { + void httpMessageConverterThatUsesConversionServiceDoesNotCreateACycle() { this.contextRunner.withUserConfiguration(CustomHttpMessageConverter.class) .run((context) -> assertThat(context).hasNotFailed()); } @Test - public void cachePeriod() { + void cachePeriod() { this.contextRunner.withPropertyValues("spring.resources.cache.period:5").run(this::assertCachePeriod); } @@ -674,13 +674,13 @@ public class WebMvcAutoConfigurationTests { } @Test - public void cacheControl() { + void cacheControl() { this.contextRunner.withPropertyValues("spring.resources.cache.cachecontrol.max-age:5", "spring.resources.cache.cachecontrol.proxy-revalidate:true").run(this::assertCacheControl); } @Test - public void defaultPathMatching() { + void defaultPathMatching() { this.contextRunner.run((context) -> { RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); assertThat(handlerMapping.useSuffixPatternMatch()).isFalse(); @@ -689,7 +689,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void useSuffixPatternMatch() { + void useSuffixPatternMatch() { this.contextRunner.withPropertyValues("spring.mvc.pathmatch.use-suffix-pattern:true", "spring.mvc.pathmatch.use-registered-suffix-pattern:true").run((context) -> { RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); @@ -699,7 +699,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void defaultContentNegotiation() { + void defaultContentNegotiation() { this.contextRunner.run((context) -> { RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); ContentNegotiationManager contentNegotiationManager = handlerMapping.getContentNegotiationManager(); @@ -709,7 +709,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void pathExtensionContentNegotiation() { + void pathExtensionContentNegotiation() { this.contextRunner.withPropertyValues("spring.mvc.contentnegotiation.favor-path-extension:true") .run((context) -> { RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); @@ -720,7 +720,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void queryParameterContentNegotiation() { + void queryParameterContentNegotiation() { this.contextRunner.withPropertyValues("spring.mvc.contentnegotiation.favor-parameter:true").run((context) -> { RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); ContentNegotiationManager contentNegotiationManager = handlerMapping.getContentNegotiationManager(); @@ -730,7 +730,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void customConfigurerAppliedAfterAutoConfig() { + void customConfigurerAppliedAfterAutoConfig() { this.contextRunner.withUserConfiguration(CustomConfigurer.class).run((context) -> { ContentNegotiationManager manager = context.getBean(ContentNegotiationManager.class); assertThat(manager.getStrategies()).anyMatch( @@ -740,7 +740,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void contentNegotiationStrategySkipsPathExtension() throws Exception { + void contentNegotiationStrategySkipsPathExtension() throws Exception { ContentNegotiationStrategy delegate = mock(ContentNegotiationStrategy.class); ContentNegotiationStrategy strategy = new WebMvcAutoConfiguration.OptionalPathExtensionContentNegotiationStrategy( delegate); @@ -752,12 +752,12 @@ public class WebMvcAutoConfigurationTests { } @Test - public void requestContextFilterIsAutoConfigured() { + void requestContextFilterIsAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RequestContextFilter.class)); } @Test - public void whenUserDefinesARequestContextFilterTheAutoConfiguredRegistrationBacksOff() { + void whenUserDefinesARequestContextFilterTheAutoConfiguredRegistrationBacksOff() { this.contextRunner.withUserConfiguration(RequestContextFilterConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(RequestContextFilter.class); assertThat(context).hasBean("customRequestContextFilter"); @@ -765,7 +765,7 @@ public class WebMvcAutoConfigurationTests { } @Test - public void whenUserDefinesARequestContextFilterRegistrationTheAutoConfiguredFilterBacksOff() { + void whenUserDefinesARequestContextFilterRegistrationTheAutoConfiguredFilterBacksOff() { this.contextRunner.withUserConfiguration(RequestContextFilterRegistrationConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(FilterRegistrationBean.class); assertThat(context).hasBean("customRequestContextFilterRegistration"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcPropertiesTests.java index 722c20ac02d..c501019a385 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcPropertiesTests.java @@ -36,26 +36,26 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Stephane Nicoll */ -public class WebMvcPropertiesTests { +class WebMvcPropertiesTests { private final WebMvcProperties properties = new WebMvcProperties(); @Test - public void servletPathWhenEndsWithSlashHasValidMappingAndPrefix() { + void servletPathWhenEndsWithSlashHasValidMappingAndPrefix() { bind("spring.mvc.servlet.path", "/foo/"); assertThat(this.properties.getServlet().getServletMapping()).isEqualTo("/foo/*"); assertThat(this.properties.getServlet().getServletPrefix()).isEqualTo("/foo"); } @Test - public void servletPathWhenDoesNotEndWithSlashHasValidMappingAndPrefix() { + void servletPathWhenDoesNotEndWithSlashHasValidMappingAndPrefix() { bind("spring.mvc.servlet.path", "/foo"); assertThat(this.properties.getServlet().getServletMapping()).isEqualTo("/foo/*"); assertThat(this.properties.getServlet().getServletPrefix()).isEqualTo("/foo"); } @Test - public void servletPathWhenHasWildcardThrowsException() { + void servletPathWhenHasWildcardThrowsException() { assertThatExceptionOfType(BindException.class).isThrownBy(() -> bind("spring.mvc.servlet.path", "/*")) .withRootCauseInstanceOf(IllegalArgumentException.class).satisfies( (ex) -> assertThat(Throwables.getRootCause(ex)).hasMessage("Path must not contain wildcards")); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMappingTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMappingTests.java index 5c70e206387..77eb1ccb614 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMappingTests.java @@ -56,14 +56,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class WelcomePageHandlerMappingTests { +class WelcomePageHandlerMappingTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withUserConfiguration(HandlerMappingConfiguration.class) .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)); @Test - public void isOrderedAtLowPriority() { + void isOrderedAtLowPriority() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class).run((context) -> { WelcomePageHandlerMapping handler = context.getBean(WelcomePageHandlerMapping.class); assertThat(handler.getOrder()).isEqualTo(2); @@ -71,7 +71,7 @@ public class WelcomePageHandlerMappingTests { } @Test - public void handlesRequestForStaticPageThatAcceptsTextHtml() { + void handlesRequestForStaticPageThatAcceptsTextHtml() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) @@ -79,7 +79,7 @@ public class WelcomePageHandlerMappingTests { } @Test - public void handlesRequestForStaticPageThatAcceptsAll() { + void handlesRequestForStaticPageThatAcceptsAll() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .perform(get("/").accept(MediaType.ALL)).andExpect(status().isOk()) @@ -87,21 +87,21 @@ public class WelcomePageHandlerMappingTests { } @Test - public void doesNotHandleRequestThatDoesNotAcceptTextHtml() { + void doesNotHandleRequestThatDoesNotAcceptTextHtml() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound())); } @Test - public void handlesRequestWithNoAcceptHeader() { + void handlesRequestWithNoAcceptHeader() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .run((context) -> MockMvcBuilders.webAppContextSetup(context).build().perform(get("/")) .andExpect(status().isOk()).andExpect(forwardedUrl("index.html"))); } @Test - public void handlesRequestWithEmptyAcceptHeader() { + void handlesRequestWithEmptyAcceptHeader() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .perform(get("/").header(HttpHeaders.ACCEPT, "")).andExpect(status().isOk()) @@ -110,7 +110,7 @@ public class WelcomePageHandlerMappingTests { } @Test - public void rootHandlerIsNotRegisteredWhenStaticPathPatternIsNotSlashStarStar() { + void rootHandlerIsNotRegisteredWhenStaticPathPatternIsNotSlashStarStar() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) .withPropertyValues("static-path-pattern=/foo/**") .run((context) -> assertThat(context.getBean(WelcomePageHandlerMapping.class).getRootHandler()) @@ -118,13 +118,13 @@ public class WelcomePageHandlerMappingTests { } @Test - public void producesNotFoundResponseWhenThereIsNoWelcomePage() { + void producesNotFoundResponseWhenThereIsNoWelcomePage() { this.contextRunner.run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isNotFound())); } @Test - public void handlesRequestForTemplateThatAcceptsTextHtml() { + void handlesRequestForTemplateThatAcceptsTextHtml() { this.contextRunner.withUserConfiguration(TemplateConfiguration.class).run((context) -> { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) @@ -133,7 +133,7 @@ public class WelcomePageHandlerMappingTests { } @Test - public void handlesRequestForTemplateThatAcceptsAll() { + void handlesRequestForTemplateThatAcceptsAll() { this.contextRunner.withUserConfiguration(TemplateConfiguration.class).run((context) -> { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc.perform(get("/").accept(MediaType.ALL)).andExpect(status().isOk()) @@ -142,7 +142,7 @@ public class WelcomePageHandlerMappingTests { } @Test - public void prefersAStaticResourceToATemplate() { + void prefersAStaticResourceToATemplate() { this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class, TemplateConfiguration.class) .run((context) -> { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java index d9c8af96727..8776f3cb812 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java @@ -61,7 +61,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Dave Syer * @author Sebastien Deleuze */ -public class BasicErrorControllerDirectMockMvcTests { +class BasicErrorControllerDirectMockMvcTests { private ConfigurableWebApplicationContext wac; @@ -78,7 +78,7 @@ public class BasicErrorControllerDirectMockMvcTests { } @Test - public void errorPageAvailableWithParentContext() throws Exception { + void errorPageAvailableWithParentContext() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(ParentConfiguration.class) .child(ChildConfiguration.class).run("--server.port=0")); MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) @@ -88,7 +88,7 @@ public class BasicErrorControllerDirectMockMvcTests { } @Test - public void errorPageAvailableWithMvcIncluded() throws Exception { + void errorPageAvailableWithMvcIncluded() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication(WebMvcIncludedConfiguration.class) .run("--server.port=0")); MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) @@ -98,7 +98,7 @@ public class BasicErrorControllerDirectMockMvcTests { } @Test - public void errorPageNotAvailableWithWhitelabelDisabled() throws Exception { + void errorPageNotAvailableWithWhitelabelDisabled() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication(WebMvcIncludedConfiguration.class) .run("--server.port=0", "--server.error.whitelabel.enabled=false")); assertThatExceptionOfType(ServletException.class) @@ -106,7 +106,7 @@ public class BasicErrorControllerDirectMockMvcTests { } @Test - public void errorControllerWithAop() throws Exception { + void errorControllerWithAop() throws Exception { setup((ConfigurableWebApplicationContext) new SpringApplication(WithAopConfiguration.class) .run("--server.port=0")); MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerIntegrationTests.java index 4bac1b03b1b..8460c70c8f2 100755 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerIntegrationTests.java @@ -71,7 +71,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Stephane Nicoll */ -public class BasicErrorControllerIntegrationTests { +class BasicErrorControllerIntegrationTests { private ConfigurableApplicationContext context; @@ -84,7 +84,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testErrorForMachineClient() { + void testErrorForMachineClient() { load(); ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=true"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", null, "Expected!", "/"); @@ -92,17 +92,17 @@ public class BasicErrorControllerIntegrationTests { } @Test - public void testErrorForMachineClientTraceParamTrue() { + void testErrorForMachineClientTraceParamTrue() { errorForMachineClientOnTraceParam("?trace=true", true); } @Test - public void testErrorForMachineClientTraceParamFalse() { + void testErrorForMachineClientTraceParamFalse() { errorForMachineClientOnTraceParam("?trace=false", false); } @Test - public void testErrorForMachineClientTraceParamAbsent() { + void testErrorForMachineClientTraceParamAbsent() { errorForMachineClientOnTraceParam("", false); } @@ -117,7 +117,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testErrorForMachineClientNoStacktrace() { + void testErrorForMachineClientNoStacktrace() { load("--server.error.include-stacktrace=never"); ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=true"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", null, "Expected!", "/"); @@ -126,7 +126,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testErrorForMachineClientAlwaysStacktrace() { + void testErrorForMachineClientAlwaysStacktrace() { load("--server.error.include-stacktrace=always"); ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("?trace=false"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", null, "Expected!", "/"); @@ -135,7 +135,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testErrorForAnnotatedException() { + void testErrorForAnnotatedException() { load("--server.error.include-exception=true"); ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("/annotated"), Map.class); assertErrorAttributes(entity.getBody(), "400", "Bad Request", TestConfiguration.Errors.ExpectedException.class, @@ -144,7 +144,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testErrorForAnnotatedNoReasonException() { + void testErrorForAnnotatedNoReasonException() { load("--server.error.include-exception=true"); ResponseEntity entity = new TestRestTemplate().getForEntity(createUrl("/annotatedNoReason"), Map.class); assertErrorAttributes(entity.getBody(), "406", "Not Acceptable", @@ -153,7 +153,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testBindingExceptionForMachineClient() { + void testBindingExceptionForMachineClient() { load("--server.error.include-exception=true"); RequestEntity request = RequestEntity.get(URI.create(createUrl("/bind"))).accept(MediaType.APPLICATION_JSON) .build(); @@ -167,7 +167,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testRequestBodyValidationForMachineClient() { + void testRequestBodyValidationForMachineClient() { load("--server.error.include-exception=true"); RequestEntity request = RequestEntity.post(URI.create(createUrl("/bodyValidation"))) .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body("{}"); @@ -181,7 +181,7 @@ public class BasicErrorControllerIntegrationTests { @Test @SuppressWarnings("rawtypes") - public void testNoExceptionByDefaultForMachineClient() { + void testNoExceptionByDefaultForMachineClient() { load(); RequestEntity request = RequestEntity.get(URI.create(createUrl("/bind"))).accept(MediaType.APPLICATION_JSON) .build(); @@ -191,7 +191,7 @@ public class BasicErrorControllerIntegrationTests { } @Test - public void testConventionTemplateMapping() { + void testConventionTemplateMapping() { load(); RequestEntity request = RequestEntity.get(URI.create(createUrl("/noStorage"))).accept(MediaType.TEXT_HTML) .build(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerMockMvcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerMockMvcTests.java index a08c4db6fe2..1c2d3dc5014 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerMockMvcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerMockMvcTests.java @@ -70,7 +70,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @SpringBootTest @DirtiesContext -public class BasicErrorControllerMockMvcTests { +class BasicErrorControllerMockMvcTests { @Autowired private WebApplicationContext wac; @@ -83,14 +83,14 @@ public class BasicErrorControllerMockMvcTests { } @Test - public void testDirectAccessForMachineClient() throws Exception { + void testDirectAccessForMachineClient() throws Exception { MvcResult response = this.mockMvc.perform(get("/error")).andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("999"); } @Test - public void testErrorWithResponseStatus() throws Exception { + void testErrorWithResponseStatus() throws Exception { MvcResult result = this.mockMvc.perform(get("/bang")).andExpect(status().isNotFound()).andReturn(); MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")).andReturn(); String content = response.getResponse().getContentAsString(); @@ -98,7 +98,7 @@ public class BasicErrorControllerMockMvcTests { } @Test - public void testBindingExceptionForMachineClient() throws Exception { + void testBindingExceptionForMachineClient() throws Exception { // In a real server the response is carried over into the error dispatcher, but // in the mock a new one is created so we have to assert the status at this // intermediate point @@ -111,7 +111,7 @@ public class BasicErrorControllerMockMvcTests { } @Test - public void testDirectAccessForBrowserClient() throws Exception { + void testDirectAccessForBrowserClient() throws Exception { MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewIntegrationTests.java index 9a514d74198..e996ac961c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewIntegrationTests.java @@ -53,7 +53,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @SpringBootTest @DirtiesContext -public class DefaultErrorViewIntegrationTests { +class DefaultErrorViewIntegrationTests { @Autowired private WebApplicationContext wac; @@ -66,7 +66,7 @@ public class DefaultErrorViewIntegrationTests { } @Test - public void testErrorForBrowserClient() throws Exception { + void testErrorForBrowserClient() throws Exception { MvcResult response = this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); @@ -75,7 +75,7 @@ public class DefaultErrorViewIntegrationTests { } @Test - public void testErrorWithHtmlEscape() throws Exception { + void testErrorWithHtmlEscape() throws Exception { MvcResult response = this.mockMvc .perform(get("/error") .requestAttr("javax.servlet.error.exception", @@ -89,7 +89,7 @@ public class DefaultErrorViewIntegrationTests { } @Test - public void testErrorWithSpelEscape() throws Exception { + void testErrorWithSpelEscape() throws Exception { String spel = "${T(" + getClass().getName() + ").injectCall()}"; MvcResult response = this.mockMvc.perform(get("/error") .requestAttr("javax.servlet.error.exception", new RuntimeException(spel)).accept(MediaType.TEXT_HTML)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java index f930a619c95..d63d8c03f02 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java @@ -56,7 +56,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * @author Phillip Webb * @author Andy Wilkinson */ -public class DefaultErrorViewResolverTests { +class DefaultErrorViewResolverTests { private DefaultErrorViewResolver resolver; @@ -82,27 +82,27 @@ public class DefaultErrorViewResolverTests { } @Test - public void createWhenApplicationContextIsNullShouldThrowException() { + void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultErrorViewResolver(null, new ResourceProperties())) .withMessageContaining("ApplicationContext must not be null"); } @Test - public void createWhenResourcePropertiesIsNullShouldThrowException() { + void createWhenResourcePropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), null)) .withMessageContaining("ResourceProperties must not be null"); } @Test - public void resolveWhenNoMatchShouldReturnNull() { + void resolveWhenNoMatchShouldReturnNull() { ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNull(); } @Test - public void resolveWhenExactTemplateMatchShouldReturnTemplate() { + void resolveWhenExactTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); @@ -114,7 +114,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { + void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.class), any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, @@ -123,7 +123,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { + void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); @@ -131,7 +131,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenExactResourceMatchShouldReturnResource() throws Exception { + void resolveWhenExactResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/exact"); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); @@ -140,7 +140,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenSeries4xxResourceMatchShouldReturnResource() throws Exception { + void resolveWhenSeries4xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/4xx"); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); MockHttpServletResponse response = render(resolved); @@ -149,7 +149,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenSeries5xxResourceMatchShouldReturnResource() throws Exception { + void resolveWhenSeries5xxResourceMatchShouldReturnResource() throws Exception { setResourceLocation("/5xx"); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.INTERNAL_SERVER_ERROR, this.model); @@ -159,7 +159,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() { + void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); @@ -168,7 +168,7 @@ public class DefaultErrorViewResolverTests { } @Test - public void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { + void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); @@ -179,12 +179,12 @@ public class DefaultErrorViewResolverTests { } @Test - public void orderShouldBeLowest() { + void orderShouldBeLowest() { assertThat(this.resolver.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); } @Test - public void setOrderShouldChangeOrder() { + void setOrderShouldChangeOrder() { this.resolver.setOrder(123); assertThat(this.resolver.getOrder()).isEqualTo(123); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java index 355f213336f..3c2940ad96b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java @@ -39,13 +39,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel */ @ExtendWith(OutputCaptureExtension.class) -public class ErrorMvcAutoConfigurationTests { +class ErrorMvcAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration( AutoConfigurations.of(DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class)); @Test - public void renderContainsViewWithExceptionDetails() throws Exception { + void renderContainsViewWithExceptionDetails() throws Exception { this.contextRunner.run((context) -> { View errorView = context.getBean("error", View.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); @@ -63,7 +63,7 @@ public class ErrorMvcAutoConfigurationTests { } @Test - public void renderWhenAlreadyCommittedLogsMessage(CapturedOutput capturedOutput) { + void renderWhenAlreadyCommittedLogsMessage(CapturedOutput capturedOutput) { this.contextRunner.run((context) -> { View errorView = context.getBean("error", View.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java index 4b176324f11..43fab7125bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.mvc.servlet.path:/spring/") @DirtiesContext -public class RemappedErrorViewIntegrationTests { +class RemappedErrorViewIntegrationTests { @LocalServerPort private int port; @@ -54,14 +54,14 @@ public class RemappedErrorViewIntegrationTests { private TestRestTemplate template = new TestRestTemplate(); @Test - public void directAccessToErrorPage() { + void directAccessToErrorPage() { String content = this.template.getForObject("http://localhost:" + this.port + "/spring/error", String.class); assertThat(content).contains("error"); assertThat(content).contains("999"); } @Test - public void forwardToErrorPage() { + void forwardToErrorPage() { String content = this.template.getForObject("http://localhost:" + this.port + "/spring/", String.class); assertThat(content).contains("error"); assertThat(content).contains("500"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java index c9135e22fa7..44b8dc8ca8c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java @@ -31,24 +31,24 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eneias Silva * @author Stephane Nicoll */ -public class OnWsdlLocationsConditionTests { +class OnWsdlLocationsConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestConfig.class); @Test - public void wsdlLocationsNotDefined() { + void wsdlLocationsNotDefined() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test - public void wsdlLocationsDefinedAsCommaSeparated() { + void wsdlLocationsDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=value1") .run((context) -> assertThat(context).hasBean("foo")); } @Test - public void wsdlLocationsDefinedAsList() { + void wsdlLocationsDefinedAsList() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=value1") .run((context) -> assertThat(context).hasBean("foo")); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index 242e3c6321c..bf426aa0e58 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -39,37 +39,37 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Eneias Silva */ -public class WebServicesAutoConfigurationTests { +class WebServicesAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); @Test - public void defaultConfiguration() { + void defaultConfiguration() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletRegistrationBean.class)); } @Test - public void customPathMustBeginWithASlash() { + void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.webservices.path=invalid") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("Failed to bind properties under 'spring.webservices'")); } @Test - public void customPath() { + void customPath() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid") .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test - public void customPathWithTrailingSlash() { + void customPathWithTrailingSlash() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid/") .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test - public void customLoadOnStartup() { + void customLoadOnStartup() { this.contextRunner.withPropertyValues("spring.webservices.servlet.load-on-startup=1").run((context) -> { ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")).isEqualTo(1); @@ -77,7 +77,7 @@ public class WebServicesAutoConfigurationTests { } @Test - public void customInitParameters() { + void customInitParameters() { this.contextRunner .withPropertyValues("spring.webservices.servlet.init.key1=value1", "spring.webservices.servlet.init.key2=value2") @@ -86,7 +86,7 @@ public class WebServicesAutoConfigurationTests { } @Test - public void withWsdlBeans() { + void withWsdlBeans() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=classpath:/wsdl").run((context) -> { assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).containsOnlyKeys("service"); assertThat(context.getBeansOfType(SimpleXsdSchema.class)).containsOnlyKeys("types"); @@ -94,7 +94,7 @@ public class WebServicesAutoConfigurationTests { } @Test - public void withWsdlBeansAsList() { + void withWsdlBeansAsList() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=classpath:/wsdl").run((context) -> { assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).containsOnlyKeys("service"); assertThat(context.getBeansOfType(SimpleXsdSchema.class)).containsOnlyKeys("types"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java index 5871bb9b297..6cf838fef00 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java @@ -25,26 +25,26 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Madhura Bhave */ -public class WebServicesPropertiesTests { +class WebServicesPropertiesTests { private WebServicesProperties properties; @Test - public void pathMustNotBeEmpty() { + void pathMustNotBeEmpty() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) .withMessageContaining("Path must have length greater than 1"); } @Test - public void pathMustHaveLengthGreaterThanOne() { + void pathMustHaveLengthGreaterThanOne() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) .withMessageContaining("Path must have length greater than 1"); } @Test - public void customPathMustBeginWithASlash() { + void customPathMustBeginWithASlash() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) .withMessageContaining("Path must start with '/'"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java index 65b4708d3e5..e26ce2ac834 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java @@ -43,13 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Dmytro Nosan */ -public class WebServiceTemplateAutoConfigurationTests { +class WebServiceTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); @Test - public void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() { + void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() { this.contextRunner.run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); assertThat(webServiceTemplate.getUnmarshaller()).isNull(); @@ -58,7 +58,7 @@ public class WebServiceTemplateAutoConfigurationTests { } @Test - public void autoConfiguredBuilderShouldHaveHttpMessageSenderByDefault() { + void autoConfiguredBuilderShouldHaveHttpMessageSenderByDefault() { this.contextRunner.run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); assertThat(webServiceTemplate.getMessageSenders()).hasSize(1); @@ -68,7 +68,7 @@ public class WebServiceTemplateAutoConfigurationTests { } @Test - public void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { + void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { this.contextRunner.withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class) .run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); @@ -78,7 +78,7 @@ public class WebServiceTemplateAutoConfigurationTests { } @Test - public void webServiceTemplateShouldApplyCustomizer() { + void webServiceTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(WebServiceTemplateCustomizerConfig.class) .run(assertWebServiceTemplateBuilder((builder) -> { WebServiceTemplate webServiceTemplate = builder.build(); @@ -88,7 +88,7 @@ public class WebServiceTemplateAutoConfigurationTests { } @Test - public void builderShouldBeFreshForEachUse() { + void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyWebServiceTemplateConfig.class) .run((context) -> assertThat(context).hasNotFailed()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java index ceeb2609897..2d81cd82a36 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java @@ -69,14 +69,14 @@ import org.springframework.web.socket.sockjs.client.Transport; import org.springframework.web.socket.sockjs.client.WebSocketTransport; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link WebSocketMessagingAutoConfiguration}. * * @author Andy Wilkinson */ -public class WebSocketMessagingAutoConfigurationTests { +class WebSocketMessagingAutoConfigurationTests { private AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); @@ -97,19 +97,19 @@ public class WebSocketMessagingAutoConfigurationTests { } @Test - public void basicMessagingWithJsonResponse() throws Throwable { + void basicMessagingWithJsonResponse() throws Throwable { Object result = performStompSubscription("/app/json"); assertThat(new String((byte[]) result)).isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); } @Test - public void basicMessagingWithStringResponse() throws Throwable { + void basicMessagingWithStringResponse() throws Throwable { Object result = performStompSubscription("/app/string"); assertThat(new String((byte[]) result)).isEqualTo("string data"); } @Test - public void customizedConverterTypesMatchDefaultConverterTypes() { + void customizedConverterTypesMatchDefaultConverterTypes() { List customizedConverters = getCustomizedConverters(); List defaultConverters = getDefaultConverters(); assertThat(customizedConverters.size()).isEqualTo(defaultConverters.size()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java index 19c14af9a91..7052e25cb53 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class WebSocketServletAutoConfigurationTests { +class WebSocketServletAutoConfigurationTests { private AnnotationConfigServletWebServerApplicationContext context; @@ -54,13 +54,13 @@ public class WebSocketServletAutoConfigurationTests { } @Test - public void tomcatServerContainerIsAvailableFromTheServletContext() { + void tomcatServerContainerIsAvailableFromTheServletContext() { serverContainerIsAvailableFromTheServletContext(TomcatConfiguration.class, WebSocketServletAutoConfiguration.TomcatWebSocketConfiguration.class); } @Test - public void jettyServerContainerIsAvailableFromTheServletContext() { + void jettyServerContainerIsAvailableFromTheServletContext() { serverContainerIsAvailableFromTheServletContext(JettyConfiguration.class, WebSocketServletAutoConfiguration.JettyWebSocketConfiguration.class); } diff --git a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/CommandLineIT.java b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/CommandLineIT.java index 1a46b7de182..8f17a7a5d27 100644 --- a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/CommandLineIT.java +++ b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/CommandLineIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,17 @@ package org.springframework.boot.cli; +import java.io.File; import java.io.IOException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.cli.infrastructure.CommandLineInvoker; import org.springframework.boot.cli.infrastructure.CommandLineInvoker.Invocation; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for the command line application. @@ -36,56 +34,52 @@ import static org.junit.Assert.assertThat; * @author Andy Wilkinson * @author Phillip Webb */ -public class CommandLineIT { +class CommandLineIT { - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + private CommandLineInvoker cli; - private final CommandLineInvoker cli = new CommandLineInvoker(this.temp); + @BeforeEach + public void setup(@TempDir File tempDir) { + this.cli = new CommandLineInvoker(tempDir); + } - @Test - public void hintProducesListOfValidCommands() + @Test void hintProducesListOfValidCommands() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("hint"); - assertThat(cli.await(), equalTo(0)); - assertThat("Unexpected error: \n" + cli.getErrorOutput(), - cli.getErrorOutput().length(), equalTo(0)); - assertThat(cli.getStandardOutputLines().size(), equalTo(11)); + assertThat(cli.await()).isEqualTo(0); + assertThat(cli.getErrorOutput()).isEmpty(); + assertThat(cli.getStandardOutputLines()).hasSize(11); } - @Test - public void invokingWithNoArgumentsDisplaysHelp() + @Test void invokingWithNoArgumentsDisplaysHelp() throws IOException, InterruptedException { Invocation cli = this.cli.invoke(); - assertThat(cli.await(), equalTo(1)); - assertThat(cli.getErrorOutput().length(), equalTo(0)); - assertThat(cli.getStandardOutput(), startsWith("usage:")); + assertThat(cli.await()).isEqualTo(1); + assertThat(cli.getErrorOutput()).isEmpty(); + assertThat(cli.getStandardOutput()).startsWith("usage:"); } - @Test - public void unrecognizedCommandsAreHandledGracefully() + @Test void unrecognizedCommandsAreHandledGracefully() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("not-a-real-command"); - assertThat(cli.await(), equalTo(1)); - assertThat(cli.getErrorOutput(), - containsString("'not-a-real-command' is not a valid command")); - assertThat(cli.getStandardOutput().length(), equalTo(0)); + assertThat(cli.await()).isEqualTo(1); + assertThat(cli.getErrorOutput()) + .contains("'not-a-real-command' is not a valid command"); + assertThat(cli.getStandardOutput()).isEmpty(); } - @Test - public void version() throws IOException, InterruptedException { + @Test void version() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("version"); - assertThat(cli.await(), equalTo(0)); - assertThat(cli.getErrorOutput().length(), equalTo(0)); - assertThat(cli.getStandardOutput(), startsWith("Spring CLI v")); + assertThat(cli.await()).isEqualTo(0); + assertThat(cli.getErrorOutput()).isEmpty(); + assertThat(cli.getStandardOutput()).startsWith("Spring CLI v"); } - @Test - public void help() throws IOException, InterruptedException { + @Test void help() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("help"); - assertThat(cli.await(), equalTo(1)); - assertThat(cli.getErrorOutput().length(), equalTo(0)); - assertThat(cli.getStandardOutput(), startsWith("usage:")); + assertThat(cli.await()).isEqualTo(1); + assertThat(cli.getErrorOutput()).isEmpty(); + assertThat(cli.getStandardOutput()).startsWith("usage:"); } } diff --git a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/JarCommandIT.java b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/JarCommandIT.java index 705d7813465..6c2d4b5f2e9 100644 --- a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/JarCommandIT.java +++ b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/JarCommandIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,21 +18,16 @@ package org.springframework.boot.cli; import java.io.File; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.cli.command.archive.JarCommand; import org.springframework.boot.cli.infrastructure.CommandLineInvoker; import org.springframework.boot.cli.infrastructure.CommandLineInvoker.Invocation; import org.springframework.boot.loader.tools.JavaExecutable; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test for {@link JarCommand}. @@ -40,51 +35,52 @@ import static org.junit.Assert.assertTrue; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class JarCommandIT { +class JarCommandIT { private static final boolean JAVA_9_OR_LATER = isClassPresent( "java.security.cert.URICertStoreParameters"); - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + private CommandLineInvoker cli; - private final CommandLineInvoker cli = new CommandLineInvoker( - new File("src/it/resources/jar-command"), this.temp); + private File tempDir; - @Test - public void noArguments() throws Exception { + @BeforeEach + public void setup(@TempDir File tempDir) { + this.cli = new CommandLineInvoker(new File("src/it/resources/jar-command"), + tempDir); + this.tempDir = tempDir; + } + + @Test void noArguments() throws Exception { Invocation invocation = this.cli.invoke("jar"); invocation.await(); - assertThat(invocation.getStandardOutput(), equalTo("")); - assertThat(invocation.getErrorOutput(), containsString("The name of the " - + "resulting jar and at least one source file must be specified")); + assertThat(invocation.getStandardOutput()).isEqualTo(""); + assertThat(invocation.getErrorOutput()).contains("The name of the " + + "resulting jar and at least one source file must be specified"); } - @Test - public void noSources() throws Exception { + @Test void noSources() throws Exception { Invocation invocation = this.cli.invoke("jar", "test-app.jar"); invocation.await(); - assertThat(invocation.getStandardOutput(), equalTo("")); - assertThat(invocation.getErrorOutput(), containsString("The name of the " - + "resulting jar and at least one source file must be specified")); + assertThat(invocation.getStandardOutput()).isEqualTo(""); + assertThat(invocation.getErrorOutput()).contains("The name of the " + + "resulting jar and at least one source file must be specified"); } - @Test - public void jarCreationWithGrabResolver() throws Exception { - File jar = new File(this.temp.getRoot(), "test-app.jar"); + @Test void jarCreationWithGrabResolver() throws Exception { + File jar = new File(this.tempDir, "test-app.jar"); Invocation invocation = this.cli.invoke("run", jar.getAbsolutePath(), "bad.groovy"); invocation.await(); if (!JAVA_9_OR_LATER) { - assertThat(invocation.getErrorOutput(), equalTo("")); + assertThat(invocation.getErrorOutput()).isEqualTo(""); } invocation = this.cli.invoke("jar", jar.getAbsolutePath(), "bad.groovy"); invocation.await(); if (!JAVA_9_OR_LATER) { - assertEquals(invocation.getErrorOutput(), 0, - invocation.getErrorOutput().length()); + assertThat(invocation.getErrorOutput()).isEmpty(); } - assertTrue(jar.exists()); + assertThat(jar).exists(); Process process = new JavaExecutable() .processBuilder("-jar", jar.getAbsolutePath()).start(); @@ -92,21 +88,19 @@ public class JarCommandIT { invocation.await(); if (!JAVA_9_OR_LATER) { - assertThat(invocation.getErrorOutput(), equalTo("")); + assertThat(invocation.getErrorOutput()).isEqualTo(""); } } - @Test - public void jarCreation() throws Exception { - File jar = new File(this.temp.getRoot(), "test-app.jar"); + @Test void jarCreation() throws Exception { + File jar = new File(this.tempDir, "test-app.jar"); Invocation invocation = this.cli.invoke("jar", jar.getAbsolutePath(), "jar.groovy"); invocation.await(); if (!JAVA_9_OR_LATER) { - assertEquals(invocation.getErrorOutput(), 0, - invocation.getErrorOutput().length()); + assertThat(invocation.getErrorOutput()).isEmpty(); } - assertTrue(jar.exists()); + assertThat(jar).exists(); Process process = new JavaExecutable() .processBuilder("-jar", jar.getAbsolutePath()).start(); @@ -114,33 +108,25 @@ public class JarCommandIT { invocation.await(); if (!JAVA_9_OR_LATER) { - assertThat(invocation.getErrorOutput(), equalTo("")); + assertThat(invocation.getErrorOutput()).isEqualTo(""); } - assertThat(invocation.getStandardOutput(), containsString("Hello World!")); - assertThat(invocation.getStandardOutput(), - containsString("/BOOT-INF/classes!/public/public.txt")); - assertThat(invocation.getStandardOutput(), - containsString("/BOOT-INF/classes!/resources/resource.txt")); - assertThat(invocation.getStandardOutput(), - containsString("/BOOT-INF/classes!/static/static.txt")); - assertThat(invocation.getStandardOutput(), - containsString("/BOOT-INF/classes!/templates/template.txt")); - assertThat(invocation.getStandardOutput(), - containsString("/BOOT-INF/classes!/root.properties")); - assertThat(invocation.getStandardOutput(), containsString("Goodbye Mama")); + assertThat(invocation.getStandardOutput()).contains("Hello World!") + .contains("/BOOT-INF/classes!/public/public.txt") + .contains("/BOOT-INF/classes!/resources/resource.txt") + .contains("/BOOT-INF/classes!/static/static.txt") + .contains("/BOOT-INF/classes!/templates/template.txt") + .contains("/BOOT-INF/classes!/root.properties").contains("Goodbye Mama"); } - @Test - public void jarCreationWithIncludes() throws Exception { - File jar = new File(this.temp.getRoot(), "test-app.jar"); + @Test void jarCreationWithIncludes() throws Exception { + File jar = new File(this.tempDir, "test-app.jar"); Invocation invocation = this.cli.invoke("jar", jar.getAbsolutePath(), "--include", "-public/**,-resources/**", "jar.groovy"); invocation.await(); if (!JAVA_9_OR_LATER) { - assertEquals(invocation.getErrorOutput(), 0, - invocation.getErrorOutput().length()); + assertThat(invocation.getErrorOutput()).isEmpty(); } - assertTrue(jar.exists()); + assertThat(jar).exists(); Process process = new JavaExecutable() .processBuilder("-jar", jar.getAbsolutePath()).start(); @@ -148,17 +134,12 @@ public class JarCommandIT { invocation.await(); if (!JAVA_9_OR_LATER) { - assertThat(invocation.getErrorOutput(), equalTo("")); + assertThat(invocation.getErrorOutput()).isEqualTo(""); } - assertThat(invocation.getStandardOutput(), containsString("Hello World!")); - assertThat(invocation.getStandardOutput(), - not(containsString("/public/public.txt"))); - assertThat(invocation.getStandardOutput(), - not(containsString("/resources/resource.txt"))); - assertThat(invocation.getStandardOutput(), containsString("/static/static.txt")); - assertThat(invocation.getStandardOutput(), - containsString("/templates/template.txt")); - assertThat(invocation.getStandardOutput(), containsString("Goodbye Mama")); + assertThat(invocation.getStandardOutput()).contains("Hello World!") + .doesNotContain("/public/public.txt") + .doesNotContain("/resources/resource.txt").contains("/static/static.txt") + .contains("/templates/template.txt").contains("Goodbye Mama"); } private static boolean isClassPresent(String name) { diff --git a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/WarCommandIT.java b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/WarCommandIT.java index 49952533706..7ae9e238dab 100644 --- a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/WarCommandIT.java +++ b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/WarCommandIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,9 @@ package org.springframework.boot.cli; import java.io.File; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.cli.command.archive.WarCommand; import org.springframework.boot.cli.infrastructure.CommandLineInvoker; @@ -35,17 +35,21 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andrey Stolyarov * @author Henri Kerola */ -public class WarCommandIT { +class WarCommandIT { - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + private CommandLineInvoker cli; - private final CommandLineInvoker cli = new CommandLineInvoker( - new File("src/it/resources/war-command"), this.temp); + private File tempDir; - @Test - public void warCreation() throws Exception { - File war = new File(this.temp.getRoot(), "test-app.war"); + @BeforeEach + public void setup(@TempDir File tempDir) { + this.cli = new CommandLineInvoker(new File("src/it/resources/war-command"), + tempDir); + this.tempDir = tempDir; + } + + @Test void warCreation() throws Exception { + File war = new File(this.tempDir, "test-app.war"); Invocation invocation = this.cli.invoke("war", war.getAbsolutePath(), "war.groovy"); invocation.await(); diff --git a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java index c489b17c4ad..b1e1c0cd78c 100644 --- a/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java +++ b/spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,6 @@ import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import org.junit.rules.TemporaryFolder; - import org.springframework.boot.testsupport.BuildOutput; import org.springframework.util.Assert; import org.springframework.util.StreamUtils; @@ -49,13 +47,13 @@ public final class CommandLineInvoker { private final File workingDirectory; - private final TemporaryFolder temp; + private final File temp; - public CommandLineInvoker(TemporaryFolder temp) { + public CommandLineInvoker(File temp) { this(new File("."), temp); } - public CommandLineInvoker(File workingDirectory, TemporaryFolder temp) { + public CommandLineInvoker(File workingDirectory, File temp) { this.workingDirectory = workingDirectory; this.temp = temp; } @@ -75,7 +73,7 @@ public final class CommandLineInvoker { } private File findLaunchScript() throws IOException { - File unpacked = new File(this.temp.getRoot(), "unpacked-cli"); + File unpacked = new File(this.temp, "unpacked-cli"); if (!unpacked.isDirectory()) { File zip = new BuildOutput(getClass()).getRootLocation() .listFiles((pathname) -> pathname.getName().endsWith("-bin.zip"))[0]; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java index 293c54c9dc1..41be85a4114 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java @@ -16,8 +16,12 @@ package org.springframework.boot.cli; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; + +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -26,13 +30,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ClassLoaderIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class ClassLoaderIntegrationTests { - @Rule - public CliTester cli = new CliTester("src/test/resources/"); + @RegisterExtension + private CliTester cli; + + ClassLoaderIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("src/test/resources/", capturedOutput); + } @Test - public void runWithIsolatedClassLoader() throws Exception { + void runWithIsolatedClassLoader() throws Exception { // CLI classes or dependencies should not be exposed to the app String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName()); assertThat(output).contains("HasClasses-false-true-false"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index 47b31a2de0f..4ca08aa7788 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java @@ -19,11 +19,13 @@ package org.springframework.boot.cli; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.net.URI; import java.net.URL; +import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; @@ -31,36 +33,37 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import org.junit.Assume; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.boot.cli.command.AbstractCommand; import org.springframework.boot.cli.command.OptionParsingCommand; import org.springframework.boot.cli.command.archive.JarCommand; import org.springframework.boot.cli.command.grab.GrabCommand; import org.springframework.boot.cli.command.run.RunCommand; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.util.FileCopyUtils; +import org.springframework.util.FileSystemUtils; import org.springframework.util.StringUtils; /** - * {@link TestRule} that can be used to invoke CLI commands. + * JUnit 5 {@link Extension} that can be used to invoke CLI commands. * * @author Phillip Webb * @author Dave Syer * @author Andy Wilkinson */ -public class CliTester implements TestRule { +public class CliTester implements BeforeEachCallback, AfterEachCallback { - private final TemporaryFolder temp = new TemporaryFolder(); + private final File temp; private final BuildOutput buildOutput = new BuildOutput(getClass()); - private final OutputCaptureRule outputCapture = new OutputCaptureRule(); + private final CapturedOutput capturedOutput; private String previousOutput = ""; @@ -72,8 +75,15 @@ public class CliTester implements TestRule { private File serverPortFile; - public CliTester(String prefix) { + public CliTester(String prefix, CapturedOutput capturedOutput) { this.prefix = prefix; + try { + this.temp = Files.createTempDirectory("cli-tester").toFile(); + } + catch (IOException ex) { + throw new IllegalStateException("Failed to create temp directory"); + } + this.capturedOutput = capturedOutput; } public void setTimeout(long timeout) { @@ -110,6 +120,10 @@ public class CliTester implements TestRule { return getOutput(); } + public File getTemp() { + return this.temp; + } + private Future submitCommand(T command, String... args) { clearUrlHandler(); final String[] sources = getSources(args); @@ -118,7 +132,7 @@ public class CliTester implements TestRule { System.setProperty("server.port", "0"); System.setProperty("spring.application.class.name", "org.springframework.boot.cli.CliTesterSpringApplication"); - this.serverPortFile = new File(this.temp.newFolder(), "server.port"); + this.serverPortFile = new File(this.temp, "server.port"); System.setProperty("portfile", this.serverPortFile.getAbsolutePath()); try { command.run(sources); @@ -168,25 +182,27 @@ public class CliTester implements TestRule { } private String getOutput() { - String output = this.outputCapture.toString().substring(this.previousOutput.length()); + String output = this.capturedOutput.toString().substring(this.previousOutput.length()); this.previousOutput = output; return output; } @Override - public Statement apply(Statement base, Description description) { - final Statement statement = this.temp - .apply(this.outputCapture.apply(new RunLauncherStatement(base), description), description); - return new Statement() { + public void beforeEach(ExtensionContext extensionContext) { + Assumptions.assumeTrue(System.getProperty("spring.profiles.active", "integration").contains("integration"), + "Not running sample integration tests because integration profile not active"); + System.setProperty("disableSpringSnapshotRepos", "false"); + } - @Override - public void evaluate() throws Throwable { - Assume.assumeTrue("Not running sample integration tests because integration profile not active", - System.getProperty("spring.profiles.active", "integration").contains("integration")); - statement.evaluate(); + @Override + public void afterEach(ExtensionContext extensionContext) { + for (AbstractCommand command : this.commands) { + if (command != null && command instanceof RunCommand) { + ((RunCommand) command).stop(); } - - }; + } + System.clearProperty("disableSpringSnapshotRepos"); + FileSystemUtils.deleteRecursively(this.temp); } public String getHttpOutput() { @@ -205,35 +221,4 @@ public class CliTester implements TestRule { } } - private final class RunLauncherStatement extends Statement { - - private final Statement base; - - private RunLauncherStatement(Statement base) { - this.base = base; - } - - @Override - public void evaluate() throws Throwable { - System.setProperty("disableSpringSnapshotRepos", "false"); - try { - try { - this.base.evaluate(); - } - finally { - for (AbstractCommand command : CliTester.this.commands) { - if (command != null && command instanceof RunCommand) { - ((RunCommand) command).stop(); - } - } - System.clearProperty("disableSpringSnapshotRepos"); - } - } - catch (Exception ex) { - throw new IllegalStateException(ex); - } - } - - } - } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java index 259f2c21953..2a4252cfb38 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,12 @@ package org.springframework.boot.cli; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; + +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -26,23 +30,28 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class DirectorySourcesIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class DirectorySourcesIntegrationTests { - @Rule - public CliTester cli = new CliTester("src/test/resources/dir-sample/"); + @RegisterExtension + private CliTester cli; + + DirectorySourcesIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("src/test/resources/dir-sample/", capturedOutput); + } @Test - public void runDirectory() throws Exception { + void runDirectory() throws Exception { assertThat(this.cli.run("code")).contains("Hello World"); } @Test - public void runDirectoryRecursive() throws Exception { + void runDirectoryRecursive() throws Exception { assertThat(this.cli.run("")).contains("Hello World"); } @Test - public void runPathPattern() throws Exception { + void runPathPattern() throws Exception { assertThat(this.cli.run("**/*.groovy")).contains("Hello World"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index 8035902e6bc..6fc83e47552 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -18,13 +18,15 @@ package org.springframework.boot.cli; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.boot.cli.command.grab.GrabCommand; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -36,45 +38,47 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Andy Wilkinson * @author Dave Syer */ -public class GrabCommandIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class GrabCommandIntegrationTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @RegisterExtension + private CliTester cli; - @Rule - public CliTester cli = new CliTester("src/test/resources/grab-samples/"); + GrabCommandIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("src/test/resources/grab-samples/", capturedOutput); + } - @Before - @After + @BeforeEach + @AfterEach public void deleteLocalRepository() { System.clearProperty("grape.root"); System.clearProperty("groovy.grape.report.downloads"); } @Test - public void grab() throws Exception { + void grab() throws Exception { - System.setProperty("grape.root", this.temp.getRoot().getAbsolutePath()); + System.setProperty("grape.root", this.cli.getTemp().getAbsolutePath()); System.setProperty("groovy.grape.report.downloads", "true"); // Use --autoconfigure=false to limit the amount of downloaded dependencies String output = this.cli.grab("grab.groovy", "--autoconfigure=false"); - assertThat(new File(this.temp.getRoot(), "repository/joda-time/joda-time")).isDirectory(); + assertThat(new File(this.cli.getTemp(), "repository/joda-time/joda-time")).isDirectory(); // Should be resolved from local repository cache assertThat(output.contains("Downloading: file:")).isTrue(); } @Test - public void duplicateDependencyManagementBomAnnotationsProducesAnError() { + void duplicateDependencyManagementBomAnnotationsProducesAnError() { assertThatExceptionOfType(Exception.class) .isThrownBy(() -> this.cli.grab("duplicateDependencyManagementBom.groovy")) .withMessageContaining("Duplicate @DependencyManagementBom annotation"); } @Test - public void customMetadata() throws Exception { - System.setProperty("grape.root", this.temp.getRoot().getAbsolutePath()); - File repository = new File(this.temp.getRoot().getAbsolutePath(), "repository"); + void customMetadata() throws Exception { + System.setProperty("grape.root", this.cli.getTemp().getAbsolutePath()); + File repository = new File(this.cli.getTemp().getAbsolutePath(), "repository"); FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"), repository); this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false"); assertThat(new File(repository, "javax/ejb/ejb-api/3.0")).isDirectory(); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java index b6980827c7f..a202bb8c259 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,12 @@ package org.springframework.boot.cli; import java.util.concurrent.ExecutionException; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; + +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -31,13 +35,18 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class ReproIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class ReproIntegrationTests { - @Rule - public CliTester cli = new CliTester("src/test/resources/repro-samples/"); + @RegisterExtension + private CliTester cli; + + ReproIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("src/test/resources/repro-samples/", capturedOutput); + } @Test - public void grabAntBuilder() throws Exception { + void grabAntBuilder() throws Exception { this.cli.run("grab-ant-builder.groovy"); assertThat(this.cli.getHttpOutput()).contains("{\"message\":\"Hello World\"}"); } @@ -45,17 +54,17 @@ public class ReproIntegrationTests { // Security depends on old versions of Spring so if the dependencies aren't pinned // this will fail @Test - public void securityDependencies() throws Exception { + void securityDependencies() throws Exception { assertThat(this.cli.run("secure.groovy")).contains("Hello World"); } @Test - public void dataJpaDependencies() throws Exception { + void dataJpaDependencies() throws Exception { assertThat(this.cli.run("data-jpa.groovy")).contains("Hello World"); } @Test - public void jarFileExtensionNeeded() throws Exception { + void jarFileExtensionNeeded() throws Exception { assertThatExceptionOfType(ExecutionException.class) .isThrownBy(() -> this.cli.jar("secure.groovy", "data-jpa.groovy")) .withMessageContaining("is not a JAR file"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/RunCommandIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/RunCommandIntegrationTests.java index 1cff0fe7a7f..951368553db 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/RunCommandIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/RunCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,15 @@ package org.springframework.boot.cli; import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.boot.cli.command.run.RunCommand; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -32,25 +35,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class RunCommandIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class RunCommandIntegrationTests { - @Rule - public CliTester cli = new CliTester("src/it/resources/run-command/"); + @RegisterExtension + private CliTester cli; + + RunCommandIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("src/it/resources/run-command/", capturedOutput); + } private Properties systemProperties = new Properties(); - @Before + @BeforeEach public void captureSystemProperties() { this.systemProperties.putAll(System.getProperties()); } - @After + @AfterEach public void restoreSystemProperties() { System.setProperties(this.systemProperties); } @Test - public void bannerAndLoggingIsOutputByDefault() throws Exception { + void bannerAndLoggingIsOutputByDefault() throws Exception { String output = this.cli.run("quiet.groovy"); assertThat(output).contains(" :: Spring Boot ::"); assertThat(output).contains("Starting application"); @@ -58,7 +66,7 @@ public class RunCommandIntegrationTests { } @Test - public void quietModeSuppressesAllCliOutput() throws Exception { + void quietModeSuppressesAllCliOutput() throws Exception { this.cli.run("quiet.groovy"); String output = this.cli.run("quiet.groovy", "-q"); assertThat(output).isEqualTo("Ssshh"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java index b1b765fb6a4..920e150e6e6 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java @@ -19,9 +19,13 @@ package org.springframework.boot.cli; import java.io.File; import java.net.URI; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; + +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -33,46 +37,44 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Roy Clarkson * @author Phillip Webb */ -public class SampleIntegrationTests { +@ExtendWith(OutputCaptureExtension.class) +class SampleIntegrationTests { - @Rule - public CliTester cli = new CliTester("samples/"); + @RegisterExtension + private CliTester cli; - @Test - public void appSample() throws Exception { - String output = this.cli.run("app.groovy"); - URI scriptUri = new File("samples/app.groovy").toURI(); - assertThat(output).contains("Hello World! From " + scriptUri); + SampleIntegrationTests(CapturedOutput capturedOutput) { + this.cli = new CliTester("samples/", capturedOutput); } @Test - public void retrySample() throws Exception { + void retrySample() throws Exception { String output = this.cli.run("retry.groovy"); URI scriptUri = new File("samples/retry.groovy").toURI(); assertThat(output).contains("Hello World! From " + scriptUri); } @Test - public void beansSample() throws Exception { + void beansSample() throws Exception { this.cli.run("beans.groovy"); String output = this.cli.getHttpOutput(); assertThat(output).contains("Hello World!"); } @Test - public void templateSample() throws Exception { + void templateSample() throws Exception { String output = this.cli.run("template.groovy"); assertThat(output).contains("Hello World!"); } @Test - public void jobSample() throws Exception { + void jobSample() throws Exception { String output = this.cli.run("job.groovy", "foo=bar"); assertThat(output).contains("completed with the following parameters"); } @Test - public void jobWebSample() throws Exception { + void jobWebSample() throws Exception { String output = this.cli.run("job.groovy", "web.groovy", "foo=bar"); assertThat(output).contains("completed with the following parameters"); String result = this.cli.getHttpOutput(); @@ -80,13 +82,13 @@ public class SampleIntegrationTests { } @Test - public void webSample() throws Exception { + void webSample() throws Exception { this.cli.run("web.groovy"); assertThat(this.cli.getHttpOutput()).isEqualTo("World!"); } @Test - public void uiSample() throws Exception { + void uiSample() throws Exception { this.cli.run("ui.groovy", "--classpath=.:src/test/resources"); String result = this.cli.getHttpOutput(); assertThat(result).contains("Hello World"); @@ -95,37 +97,37 @@ public class SampleIntegrationTests { } @Test - public void actuatorSample() throws Exception { + void actuatorSample() throws Exception { this.cli.run("actuator.groovy"); assertThat(this.cli.getHttpOutput()).isEqualTo("{\"message\":\"Hello World!\"}"); } @Test - public void httpSample() throws Exception { + void httpSample() throws Exception { String output = this.cli.run("http.groovy"); assertThat(output).contains("Hello World"); } @Test - public void integrationSample() throws Exception { + void integrationSample() throws Exception { String output = this.cli.run("integration.groovy"); assertThat(output).contains("Hello, World"); } @Test - public void xmlSample() throws Exception { + void xmlSample() throws Exception { String output = this.cli.run("runner.xml", "runner.groovy"); assertThat(output).contains("Hello World"); } @Test - public void txSample() throws Exception { + void txSample() throws Exception { String output = this.cli.run("tx.groovy"); assertThat(output).contains("Foo count="); } @Test - public void jmsSample() throws Exception { + void jmsSample() throws Exception { System.setProperty("spring.artemis.embedded.queues", "spring-boot"); try { String output = this.cli.run("jms.groovy"); @@ -137,14 +139,14 @@ public class SampleIntegrationTests { } @Test - @Ignore("Requires RabbitMQ to be run, so disable it be default") - public void rabbitSample() throws Exception { + @Disabled("Requires RabbitMQ to be run, so disable it by default") + void rabbitSample() throws Exception { String output = this.cli.run("rabbit.groovy"); assertThat(output).contains("Received Greetings from Spring Boot via RabbitMQ"); } @Test - public void caching() throws Exception { + void caching() throws Exception { assertThat(this.cli.run("caching.groovy")).contains("Hello World"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java index c963f644c75..14b22e9cbd6 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java @@ -21,8 +21,8 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -31,34 +31,34 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SpringApplicationLauncherTests { +class SpringApplicationLauncherTests { private Map env = new HashMap<>(); - @After + @AfterEach public void cleanUp() { System.clearProperty("spring.application.class.name"); } @Test - public void defaultLaunch() { + void defaultLaunch() { assertThat(launch()).contains("org.springframework.boot.SpringApplication"); } @Test - public void launchWithClassConfiguredBySystemProperty() { + void launchWithClassConfiguredBySystemProperty() { System.setProperty("spring.application.class.name", "system.property.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); } @Test - public void launchWithClassConfiguredByEnvironmentVariable() { + void launchWithClassConfiguredByEnvironmentVariable() { this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("environment.variable.SpringApplication"); } @Test - public void systemPropertyOverridesEnvironmentVariable() { + void systemPropertyOverridesEnvironmentVariable() { System.setProperty("spring.application.class.name", "system.property.SpringApplication"); this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); assertThat(launch()).contains("system.property.SpringApplication"); @@ -66,7 +66,7 @@ public class SpringApplicationLauncherTests { } @Test - public void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception { + void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception { System.setProperty("spring.application.class.name", TestSpringApplication.class.getName()); Class[] sources = new Class[0]; String[] args = new String[0]; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java index ec03be289e5..b069fad5eda 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java @@ -16,38 +16,39 @@ package org.springframework.boot.cli.command; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.cli.command.run.RunCommand; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; /** + * Integration tests for {@link CommandRunner}. + * * @author Dave Syer */ -public class CommandRunnerIntegrationTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class CommandRunnerIntegrationTests { @Test - public void debugAddsAutoconfigReport() { + void debugAddsAutoconfigReport(CapturedOutput capturedOutput) { CommandRunner runner = new CommandRunner("spring"); runner.addCommand(new RunCommand()); // -d counts as "debug" for the spring command, but not for the // LoggingApplicationListener runner.runAndHandleErrors("run", "samples/app.groovy", "-d"); - assertThat(this.output.toString()).contains("Negative matches:"); + assertThat(capturedOutput).contains("Negative matches:"); } @Test - public void debugSwitchedOffForAppArgs() { + void debugSwitchedOffForAppArgs(CapturedOutput capturedOutput) { CommandRunner runner = new CommandRunner("spring"); runner.addCommand(new RunCommand()); runner.runAndHandleErrors("run", "samples/app.groovy", "--", "-d"); - assertThat(this.output.toString()).doesNotContain("Negative matches:"); + assertThat(capturedOutput).doesNotContain("Negative matches:"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index b3ea82bcc00..2651ebc44bc 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -19,9 +19,9 @@ package org.springframework.boot.cli.command; import java.util.EnumSet; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -40,7 +40,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Dave Syer */ -public class CommandRunnerTests { +class CommandRunnerTests { private CommandRunner commandRunner; @@ -54,13 +54,13 @@ public class CommandRunnerTests { private ClassLoader loader; - @After + @AfterEach public void close() { Thread.currentThread().setContextClassLoader(this.loader); System.clearProperty("debug"); } - @Before + @BeforeEach public void setup() { this.loader = Thread.currentThread().getContextClassLoader(); MockitoAnnotations.initMocks(this); @@ -93,23 +93,23 @@ public class CommandRunnerTests { } @Test - public void runWithoutArguments() throws Exception { + void runWithoutArguments() throws Exception { assertThatExceptionOfType(NoArgumentsException.class).isThrownBy(this.commandRunner::run); } @Test - public void runCommand() throws Exception { + void runCommand() throws Exception { this.commandRunner.run("command", "--arg1", "arg2"); verify(this.regularCommand).run("--arg1", "arg2"); } @Test - public void missingCommand() throws Exception { + void missingCommand() throws Exception { assertThatExceptionOfType(NoSuchCommandException.class).isThrownBy(() -> this.commandRunner.run("missing")); } @Test - public void appArguments() throws Exception { + void appArguments() throws Exception { this.commandRunner.runAndHandleErrors("command", "--", "--debug", "bar"); verify(this.regularCommand).run("--", "--debug", "bar"); // When handled by the command itself it shouldn't cause the system property to be @@ -118,21 +118,21 @@ public class CommandRunnerTests { } @Test - public void handlesSuccess() { + void handlesSuccess() { int status = this.commandRunner.runAndHandleErrors("command"); assertThat(status).isEqualTo(0); assertThat(this.calls).isEmpty(); } @Test - public void handlesNoSuchCommand() { + void handlesNoSuchCommand() { int status = this.commandRunner.runAndHandleErrors("missing"); assertThat(status).isEqualTo(1); assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE); } @Test - public void handlesRegularExceptionWithMessage() throws Exception { + void handlesRegularExceptionWithMessage() throws Exception { willThrow(new RuntimeException("With Message")).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command"); assertThat(status).isEqualTo(1); @@ -140,7 +140,7 @@ public class CommandRunnerTests { } @Test - public void handlesRegularExceptionWithoutMessage() throws Exception { + void handlesRegularExceptionWithoutMessage() throws Exception { willThrow(new NullPointerException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command"); assertThat(status).isEqualTo(1); @@ -148,7 +148,7 @@ public class CommandRunnerTests { } @Test - public void handlesExceptionWithDashD() throws Exception { + void handlesExceptionWithDashD() throws Exception { willThrow(new RuntimeException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command", "-d"); assertThat(System.getProperty("debug")).isEqualTo("true"); @@ -157,7 +157,7 @@ public class CommandRunnerTests { } @Test - public void handlesExceptionWithDashDashDebug() throws Exception { + void handlesExceptionWithDashDashDebug() throws Exception { willThrow(new RuntimeException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command", "--debug"); assertThat(System.getProperty("debug")).isEqualTo("true"); @@ -166,25 +166,25 @@ public class CommandRunnerTests { } @Test - public void exceptionMessages() { + void exceptionMessages() { assertThat(new NoSuchCommandException("name").getMessage()) .isEqualTo("'name' is not a valid command. See 'help'."); } @Test - public void help() throws Exception { + void help() throws Exception { this.commandRunner.run("help", "command"); verify(this.regularCommand).getHelp(); } @Test - public void helpNoCommand() throws Exception { + void helpNoCommand() throws Exception { assertThatExceptionOfType(NoHelpCommandArgumentsException.class) .isThrownBy(() -> this.commandRunner.run("help")); } @Test - public void helpUnknownCommand() throws Exception { + void helpUnknownCommand() throws Exception { assertThatExceptionOfType(NoSuchCommandException.class) .isThrownBy(() -> this.commandRunner.run("help", "missing")); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java index 84227a65b42..1b74a30adc1 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.cli.command; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.command.options.OptionHandler; @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class OptionParsingCommandTests { +class OptionParsingCommandTests { @Test - public void optionHelp() { + void optionHelp() { OptionHandler handler = new OptionHandler(); handler.option("bar", "Bar"); OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", handler); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java index 05303d12614..3b53eb236af 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java @@ -24,7 +24,7 @@ import java.util.Collection; import java.util.List; import org.assertj.core.api.Condition; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.command.archive.ResourceMatcher.MatchedResource; import org.springframework.test.util.ReflectionTestUtils; @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ResourceMatcherTests { +class ResourceMatcherTests { @Test - public void nonExistentRoot() throws IOException { + void nonExistentRoot() throws IOException { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist"))); @@ -48,7 +48,7 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test - public void defaults() { + void defaults() { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("")); Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); @@ -57,7 +57,7 @@ public class ResourceMatcherTests { } @Test - public void excludedWins() throws Exception { + void excludedWins() throws Exception { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); List found = resourceMatcher.find(Arrays.asList(new File("src/test/resources"))); assertThat(found).areNot(new Condition() { @@ -72,7 +72,7 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test - public void includedDeltas() { + void includedDeltas() { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), Arrays.asList("")); Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); assertThat(includes).contains("templates/**"); @@ -81,7 +81,7 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test - public void includedDeltasAndNewEntries() { + void includedDeltasAndNewEntries() { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar")); Collection includes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "includes"); @@ -94,14 +94,14 @@ public class ResourceMatcherTests { @SuppressWarnings("unchecked") @Test - public void excludedDeltas() { + void excludedDeltas() { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar")); Collection excludes = (Collection) ReflectionTestUtils.getField(resourceMatcher, "excludes"); assertThat(excludes).doesNotContain("**/*.jar"); } @Test - public void jarFileAlwaysMatches() throws Exception { + void jarFileAlwaysMatches() throws Exception { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar")); List found = resourceMatcher .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); @@ -116,7 +116,7 @@ public class ResourceMatcherTests { } @Test - public void resourceMatching() throws IOException { + void resourceMatching() throws IOException { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"), Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java index e34fea45f13..c634b801b98 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.cli.command.encodepassword; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; @@ -37,26 +37,26 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class EncodePasswordCommandTests { +class EncodePasswordCommandTests { private MockLog log; @Captor private ArgumentCaptor message; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.log = MockLog.attach(); } - @After + @AfterEach public void cleanup() { MockLog.clear(); } @Test - public void encodeWithNoAlgorithmShouldUseBcrypt() throws Exception { + void encodeWithNoAlgorithmShouldUseBcrypt() throws Exception { EncodePasswordCommand command = new EncodePasswordCommand(); ExitStatus status = command.run("boot"); verify(this.log).info(this.message.capture()); @@ -67,7 +67,7 @@ public class EncodePasswordCommandTests { } @Test - public void encodeWithBCryptShouldUseBCrypt() throws Exception { + void encodeWithBCryptShouldUseBCrypt() throws Exception { EncodePasswordCommand command = new EncodePasswordCommand(); ExitStatus status = command.run("-a", "bcrypt", "boot"); verify(this.log).info(this.message.capture()); @@ -77,7 +77,7 @@ public class EncodePasswordCommandTests { } @Test - public void encodeWithPbkdf2ShouldUsePbkdf2() throws Exception { + void encodeWithPbkdf2ShouldUsePbkdf2() throws Exception { EncodePasswordCommand command = new EncodePasswordCommand(); ExitStatus status = command.run("-a", "pbkdf2", "boot"); verify(this.log).info(this.message.capture()); @@ -87,7 +87,7 @@ public class EncodePasswordCommandTests { } @Test - public void encodeWithUnknownAlgorithmShouldExitWithError() throws Exception { + void encodeWithUnknownAlgorithmShouldExitWithError() throws Exception { EncodePasswordCommand command = new EncodePasswordCommand(); ExitStatus status = command.run("--algorithm", "bad", "boot"); verify(this.log).error("Unknown algorithm, valid options are: default,bcrypt,pbkdf2"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java index fdfcbde0191..67eb369cbb1 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java @@ -27,10 +27,9 @@ import java.util.zip.ZipOutputStream; import joptsimple.OptionSet; import org.apache.http.Header; import org.apache.http.client.methods.HttpUriRequest; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; @@ -46,10 +45,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Eddú Meléndez */ -public class InitCommandTests extends AbstractHttpClientMockTests { - - @Rule - public final TemporaryFolder temporaryFolder = new TemporaryFolder(); +class InitCommandTests extends AbstractHttpClientMockTests { private final TestableInitCommandOptionHandler handler; @@ -58,7 +54,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { @Captor private ArgumentCaptor requestCaptor; - @Before + @BeforeEach public void setupMocks() { MockitoAnnotations.initMocks(this); } @@ -70,25 +66,25 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void listServiceCapabilitiesText() throws Exception { + void listServiceCapabilitiesText() throws Exception { mockSuccessfulMetadataTextGet(); this.command.run("--list", "--target=https://fake-service"); } @Test - public void listServiceCapabilities() throws Exception { + void listServiceCapabilities() throws Exception { mockSuccessfulMetadataGet(true); this.command.run("--list", "--target=https://fake-service"); } @Test - public void listServiceCapabilitiesV2() throws Exception { + void listServiceCapabilitiesV2() throws Exception { mockSuccessfulMetadataGetV2(true); this.command.run("--list", "--target=https://fake-service"); } @Test - public void generateProject() throws Exception { + void generateProject() throws Exception { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); assertThat(file.exists()).as("file should not exist").isFalse(); @@ -104,50 +100,47 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectNoFileNameAvailable() throws Exception { + void generateProjectNoFileNameAvailable() throws Exception { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", null); mockSuccessfulProjectGeneration(request); assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR); } @Test - public void generateProjectAndExtract() throws Exception { - File folder = this.temporaryFolder.newFolder(); + void generateProjectAndExtract(@TempDir File tempDir) throws Exception { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); - File archiveFile = new File(folder, "test.txt"); + assertThat(this.command.run("--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.OK); + File archiveFile = new File(tempDir, "test.txt"); assertThat(archiveFile).exists(); } @Test - public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() throws Exception { - File folder = this.temporaryFolder.newFolder(); + void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation(@TempDir File tempDir) throws Exception { byte[] archive = createFakeZipArchive("../outside.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); - File archiveFile = new File(folder.getParentFile(), "outside.txt"); + assertThat(this.command.run("--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); + File archiveFile = new File(tempDir.getParentFile(), "outside.txt"); assertThat(archiveFile).doesNotExist(); } @Test - public void generateProjectAndExtractWithConvention() throws Exception { - File folder = this.temporaryFolder.newFolder(); + void generateProjectAndExtractWithConvention(@TempDir File tempDir) throws Exception { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run(folder.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK); - File archiveFile = new File(folder, "test.txt"); + assertThat(this.command.run(tempDir.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK); + File archiveFile = new File(tempDir, "test.txt"); assertThat(archiveFile).exists(); } @Test - public void generateProjectArchiveExtractedByDefault() throws Exception { + void generateProjectArchiveExtractedByDefault() throws Exception { String fileName = UUID.randomUUID().toString(); assertThat(fileName.contains(".")).as("No dot in filename").isFalse(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); @@ -167,7 +160,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectFileSavedAsFileByDefault() throws Exception { + void generateProjectFileSavedAsFileByDefault() throws Exception { String fileName = UUID.randomUUID().toString(); String content = "Fake Content"; byte[] archive = content.getBytes(); @@ -186,8 +179,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectAndExtractUnsupportedArchive() throws Exception { - File folder = this.temporaryFolder.newFolder(); + void generateProjectAndExtractUnsupportedArchive(@TempDir File tempDir) throws Exception { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); assertThat(file.exists()).as("file should not exist").isFalse(); @@ -196,7 +188,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/foobar", fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -205,8 +197,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectAndExtractUnknownContentType() throws Exception { - File folder = this.temporaryFolder.newFolder(); + void generateProjectAndExtractUnknownContentType(@TempDir File tempDir) throws Exception { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); assertThat(file.exists()).as("file should not exist").isFalse(); @@ -214,7 +205,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(null, fileName, archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { @@ -223,8 +214,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void fileNotOverwrittenByDefault() throws Exception { - File file = this.temporaryFolder.newFile(); + void fileNotOverwrittenByDefault(@TempDir File tempDir) throws Exception { + File file = new File(tempDir, "test.file"); + file.createNewFile(); long fileLength = file.length(); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", file.getAbsolutePath()); @@ -234,8 +226,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void overwriteFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void overwriteFile(@TempDir File tempDir) throws Exception { + File file = new File(tempDir, "test.file"); + file.createNewFile(); long fileLength = file.length(); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", file.getAbsolutePath()); @@ -245,9 +238,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void fileInArchiveNotOverwrittenByDefault() throws Exception { - File folder = this.temporaryFolder.newFolder(); - File conflict = new File(folder, "test.txt"); + void fileInArchiveNotOverwrittenByDefault(@TempDir File tempDir) throws Exception { + File conflict = new File(tempDir, "test.txt"); assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt @@ -255,12 +247,12 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); + assertThat(this.command.run("--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.ERROR); assertThat(conflict.length()).as("File should not have changed").isEqualTo(fileLength); } @Test - public void parseProjectOptions() throws Exception { + void parseProjectOptions() throws Exception { this.handler.disableProjectGeneration(); this.command.run("-g=org.demo", "-a=acme", "-v=1.2.3-SNAPSHOT", "-n=acme-sample", "--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt", @@ -285,9 +277,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void overwriteFileInArchive() throws Exception { - File folder = this.temporaryFolder.newFolder(); - File conflict = new File(folder, "test.txt"); + void overwriteFileInArchive(@TempDir File tempDir) throws Exception { + File conflict = new File(tempDir, "test.txt"); assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue(); long fileLength = conflict.length(); // also contains test.txt @@ -295,12 +286,12 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK); + assertThat(this.command.run("--force", "--extract", tempDir.getAbsolutePath())).isEqualTo(ExitStatus.OK); assertThat(fileLength != conflict.length()).as("File should have changed").isTrue(); } @Test - public void parseTypeOnly() throws Exception { + void parseTypeOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("-t=ant-project"); assertThat(this.handler.lastRequest.getBuild()).isEqualTo("maven"); @@ -310,7 +301,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void parseBuildOnly() throws Exception { + void parseBuildOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("--build=ant"); assertThat(this.handler.lastRequest.getBuild()).isEqualTo("ant"); @@ -320,7 +311,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void parseFormatOnly() throws Exception { + void parseFormatOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("--format=web"); assertThat(this.handler.lastRequest.getBuild()).isEqualTo("maven"); @@ -330,14 +321,14 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void parseLocation() throws Exception { + void parseLocation() throws Exception { this.handler.disableProjectGeneration(); this.command.run("foobar.zip"); assertThat(this.handler.lastRequest.getOutput()).isEqualTo("foobar.zip"); } @Test - public void parseLocationWithSlash() throws Exception { + void parseLocationWithSlash() throws Exception { this.handler.disableProjectGeneration(); this.command.run("foobar/"); assertThat(this.handler.lastRequest.getOutput()).isEqualTo("foobar"); @@ -345,13 +336,13 @@ public class InitCommandTests extends AbstractHttpClientMockTests { } @Test - public void parseMoreThanOneArg() throws Exception { + void parseMoreThanOneArg() throws Exception { this.handler.disableProjectGeneration(); assertThat(this.command.run("foobar", "barfoo")).isEqualTo(ExitStatus.ERROR); } @Test - public void userAgent() throws Exception { + void userAgent() throws Exception { this.command.run("--list", "--target=https://fake-service"); verify(this.http).execute(this.requestCaptor.capture()); Header agent = this.requestCaptor.getValue().getHeaders("User-Agent")[0]; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java index cf7180b6437..c647b3580f0 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java @@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets; import org.json.JSONException; import org.json.JSONObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class InitializrServiceMetadataTests { +class InitializrServiceMetadataTests { @Test - public void parseDefaults() throws Exception { + void parseDefaults() throws Exception { InitializrServiceMetadata metadata = createInstance("2.0.0"); assertThat(metadata.getDefaults().get("bootVersion")).isEqualTo("1.1.8.RELEASE"); assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7"); @@ -55,7 +55,7 @@ public class InitializrServiceMetadataTests { } @Test - public void parseDependencies() throws Exception { + void parseDependencies() throws Exception { InitializrServiceMetadata metadata = createInstance("2.0.0"); assertThat(metadata.getDependencies()).hasSize(5); @@ -69,7 +69,7 @@ public class InitializrServiceMetadataTests { } @Test - public void parseTypes() throws Exception { + void parseTypes() throws Exception { InitializrServiceMetadata metadata = createInstance("2.0.0"); ProjectType projectType = metadata.getProjectTypes().get("maven-project"); assertThat(projectType).isNotNull(); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index 1daeef24be5..4006c15602d 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.cli.command.init; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -31,19 +31,19 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class InitializrServiceTests extends AbstractHttpClientMockTests { +class InitializrServiceTests extends AbstractHttpClientMockTests { private final InitializrService invoker = new InitializrService(this.http); @Test - public void loadMetadata() throws Exception { + void loadMetadata() throws Exception { mockSuccessfulMetadataGet(false); InitializrServiceMetadata metadata = this.invoker.loadMetadata("https://foo/bar"); assertThat(metadata).isNotNull(); } @Test - public void generateSimpleProject() throws Exception { + void generateSimpleProject() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", "foo.zip"); @@ -52,7 +52,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectCustomTargetFilename() throws Exception { + void generateProjectCustomTargetFilename() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); request.setOutput("bar.zip"); MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", @@ -62,7 +62,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectNoDefaultFileName() throws Exception { + void generateProjectNoDefaultFileName() throws Exception { ProjectGenerationRequest request = new ProjectGenerationRequest(); MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml", null); @@ -71,7 +71,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectBadRequest() throws Exception { + void generateProjectBadRequest() throws Exception { String jsonMessage = "Unknown dependency foo:bar"; mockProjectGenerationError(400, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); @@ -81,7 +81,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectBadRequestNoExtraMessage() throws Exception { + void generateProjectBadRequestNoExtraMessage() throws Exception { mockProjectGenerationError(400, null); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) @@ -89,7 +89,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void generateProjectNoContent() throws Exception { + void generateProjectNoContent() throws Exception { mockSuccessfulMetadataGet(false); CloseableHttpResponse response = mock(CloseableHttpResponse.class); mockStatus(response, 500); @@ -100,7 +100,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void loadMetadataBadRequest() throws Exception { + void loadMetadataBadRequest() throws Exception { String jsonMessage = "whatever error on the server"; mockMetadataGetError(500, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); @@ -109,7 +109,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void loadMetadataInvalidJson() throws Exception { + void loadMetadataInvalidJson() throws Exception { CloseableHttpResponse response = mock(CloseableHttpResponse.class); mockHttpEntity(response, "Foo-Bar-Not-JSON".getBytes(), "application/json"); mockStatus(response, 200); @@ -120,7 +120,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { } @Test - public void loadMetadataNoContent() throws Exception { + void loadMetadataNoContent() throws Exception { CloseableHttpResponse response = mock(CloseableHttpResponse.class); mockStatus(response, 500); given(this.http.execute(isA(HttpGet.class))).willReturn(response); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index 0c34eaee764..947606b64ce 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -25,7 +25,7 @@ import java.util.Map; import org.json.JSONException; import org.json.JSONObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -40,19 +40,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Stephane Nicoll * @author Eddú Meléndez */ -public class ProjectGenerationRequestTests { +class ProjectGenerationRequestTests { public static final Map EMPTY_TAGS = Collections.emptyMap(); private final ProjectGenerationRequest request = new ProjectGenerationRequest(); @Test - public void defaultSettings() { + void defaultSettings() { assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(createDefaultUrl("?type=test-type")); } @Test - public void customServer() throws URISyntaxException { + void customServer() throws URISyntaxException { String customServerUrl = "https://foo:8080/initializr"; this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); @@ -61,21 +61,21 @@ public class ProjectGenerationRequestTests { } @Test - public void customBootVersion() { + void customBootVersion() { this.request.setBootVersion("1.2.0.RELEASE"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); } @Test - public void singleDependency() { + void singleDependency() { this.request.getDependencies().add("web"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); } @Test - public void multipleDependencies() { + void multipleDependencies() { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); assertThat(this.request.generateUrl(createDefaultMetadata())) @@ -83,21 +83,21 @@ public class ProjectGenerationRequestTests { } @Test - public void customJavaVersion() { + void customJavaVersion() { this.request.setJavaVersion("1.8"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); } @Test - public void customPackageName() { + void customPackageName() { this.request.setPackageName("demo.foo"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); } @Test - public void customType() throws URISyntaxException { + void customType() throws URISyntaxException { ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, EMPTY_TAGS); InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType); this.request.setType("custom"); @@ -107,21 +107,21 @@ public class ProjectGenerationRequestTests { } @Test - public void customPackaging() { + void customPackaging() { this.request.setPackaging("war"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); } @Test - public void customLanguage() { + void customLanguage() { this.request.setLanguage("groovy"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); } @Test - public void customProjectInfo() { + void customProjectInfo() { this.request.setGroupId("org.acme"); this.request.setArtifactId("sample"); this.request.setVersion("1.0.1-SNAPSHOT"); @@ -132,28 +132,28 @@ public class ProjectGenerationRequestTests { } @Test - public void outputCustomizeArtifactId() { + void outputCustomizeArtifactId() { this.request.setOutput("my-project"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test - public void outputArchiveCustomizeArtifactId() { + void outputArchiveCustomizeArtifactId() { this.request.setOutput("my-project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test - public void outputArchiveWithDotsCustomizeArtifactId() { + void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test - public void outputDoesNotOverrideCustomArtifactId() { + void outputDoesNotOverrideCustomArtifactId() { this.request.setOutput("my-project"); this.request.setArtifactId("my-id"); assertThat(this.request.generateUrl(createDefaultMetadata())) @@ -161,7 +161,7 @@ public class ProjectGenerationRequestTests { } @Test - public void buildNoMatch() throws Exception { + void buildNoMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("does-not-exist", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) @@ -169,7 +169,7 @@ public class ProjectGenerationRequestTests { } @Test - public void buildMultipleMatch() throws Exception { + void buildMultipleMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata("types-conflict"); setBuildAndFormat("gradle", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) @@ -177,14 +177,14 @@ public class ProjectGenerationRequestTests { } @Test - public void buildOneMatch() throws Exception { + void buildOneMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", null); assertThat(this.request.generateUrl(metadata)).isEqualTo(createDefaultUrl("?type=gradle-project")); } @Test - public void typeAndBuildAndFormat() throws Exception { + void typeAndBuildAndFormat() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", "project"); this.request.setType("maven-build"); @@ -192,14 +192,14 @@ public class ProjectGenerationRequestTests { } @Test - public void invalidType() { + void invalidType() { this.request.setType("does-not-exist"); assertThatExceptionOfType(ReportableException.class) .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); } @Test - public void noTypeAndNoDefault() throws Exception { + void noTypeAndNoDefault() throws Exception { assertThatExceptionOfType(ReportableException.class) .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) .withMessageContaining("no default is defined"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java index 1ce44a082bb..5511b287310 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.cli.command.init; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,13 +27,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientMockTests { +class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientMockTests { private final ServiceCapabilitiesReportGenerator command = new ServiceCapabilitiesReportGenerator( new InitializrService(this.http)); @Test - public void listMetadataFromServer() throws IOException { + void listMetadataFromServer() throws IOException { mockSuccessfulMetadataTextGet(); String expected = new String(readClasspathResource("metadata/service-metadata-2.1.0.txt")); String content = this.command.generate("http://localhost"); @@ -41,13 +41,13 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM } @Test - public void listMetadata() throws IOException { + void listMetadata() throws IOException { mockSuccessfulMetadataGet(true); doTestGenerateCapabilitiesFromJson(); } @Test - public void listMetadataV2() throws IOException { + void listMetadataV2() throws IOException { mockSuccessfulMetadataGetV2(true); doTestGenerateCapabilitiesFromJson(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java index 391f23a9734..42f22a7be48 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java @@ -24,8 +24,8 @@ import java.util.List; import java.util.Set; import org.assertj.core.api.Condition; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration; import org.springframework.boot.cli.compiler.GroovyCompilerScope; @@ -42,11 +42,11 @@ import static org.hamcrest.Matchers.startsWith; * * @author Andy Wilkinson */ -public class GroovyGrabDependencyResolverTests { +class GroovyGrabDependencyResolverTests { private DependencyResolver resolver; - @Before + @BeforeEach public void setupResolver() { GroovyCompilerConfiguration configuration = new GroovyCompilerConfiguration() { @@ -90,14 +90,14 @@ public class GroovyGrabDependencyResolverTests { } @Test - public void resolveArtifactWithNoDependencies() throws Exception { + void resolveArtifactWithNoDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(1); assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar"); } @Test - public void resolveArtifactWithDependencies() throws Exception { + void resolveArtifactWithDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); assertThat(resolved).hasSize(2); assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", "spring-core-4.1.1.RELEASE.jar"); @@ -105,7 +105,7 @@ public class GroovyGrabDependencyResolverTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void resolveShorthandArtifactWithDependencies() throws Exception { + void resolveShorthandArtifactWithDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("spring-beans")); assertThat(resolved).hasSize(3); assertThat(getNames(resolved)).has((Condition) Matched @@ -113,7 +113,7 @@ public class GroovyGrabDependencyResolverTests { } @Test - public void resolveMultipleArtifacts() throws Exception { + void resolveMultipleArtifacts() throws Exception { List resolved = this.resolver .resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); assertThat(resolved).hasSize(4); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java index 0d60c8b877d..c47ba964001 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java @@ -22,11 +22,10 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -37,28 +36,28 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class InstallerTests { +class InstallerTests { - public DependencyResolver resolver = mock(DependencyResolver.class); + private final DependencyResolver resolver = mock(DependencyResolver.class); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + File tempDir; private Installer installer; - @Before + @BeforeEach public void setUp() throws IOException { - System.setProperty("spring.home", this.tempFolder.getRoot().getAbsolutePath()); + System.setProperty("spring.home", this.tempDir.getAbsolutePath()); this.installer = new Installer(this.resolver); } - @After + @AfterEach public void cleanUp() { System.clearProperty("spring.home"); } @Test - public void installNewDependency() throws Exception { + void installNewDependency() throws Exception { File foo = createTemporaryFile("foo.jar"); given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo)); this.installer.install(Arrays.asList("foo")); @@ -66,7 +65,7 @@ public class InstallerTests { } @Test - public void installAndUninstall() throws Exception { + void installAndUninstall() throws Exception { File foo = createTemporaryFile("foo.jar"); given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo)); this.installer.install(Arrays.asList("foo")); @@ -75,7 +74,7 @@ public class InstallerTests { } @Test - public void installAndUninstallWithCommonDependencies() throws Exception { + void installAndUninstallWithCommonDependencies() throws Exception { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); @@ -92,7 +91,7 @@ public class InstallerTests { } @Test - public void uninstallAll() throws Exception { + void uninstallAll() throws Exception { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); @@ -107,15 +106,15 @@ public class InstallerTests { private Set getNamesOfFilesInLibExt() { Set names = new HashSet<>(); - for (File file : new File(this.tempFolder.getRoot(), "lib/ext").listFiles()) { + for (File file : new File(this.tempDir, "lib/ext").listFiles()) { names.add(file.getName()); } return names; } private File createTemporaryFile(String name) throws IOException { - File temporaryFile = this.tempFolder.newFile(name); - temporaryFile.deleteOnExit(); + File temporaryFile = new File(this.tempDir, name); + temporaryFile.createNewFile(); return temporaryFile; } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java index 3ad83fb2a6e..c00b3d86bdd 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.cli.command.run; import java.util.logging.Level; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class SpringApplicationRunnerTests { +class SpringApplicationRunnerTests { @Test - public void exceptionMessageWhenSourcesContainsNoClasses() throws Exception { + void exceptionMessageWhenSourcesContainsNoClasses() throws Exception { SpringApplicationRunnerConfiguration configuration = mock(SpringApplicationRunnerConfiguration.class); given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" }); given(configuration.getLogLevel()).willReturn(Level.INFO); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java index ad4b2849da6..5d58440e734 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java @@ -17,7 +17,7 @@ package org.springframework.boot.cli.command.shell; import jline.console.completer.ArgumentCompleter.ArgumentList; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,12 +26,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class EscapeAwareWhiteSpaceArgumentDelimiterTests { +class EscapeAwareWhiteSpaceArgumentDelimiterTests { private final EscapeAwareWhiteSpaceArgumentDelimiter delimiter = new EscapeAwareWhiteSpaceArgumentDelimiter(); @Test - public void simple() { + void simple() { String s = "one two"; assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("one", "two"); @@ -41,7 +41,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { } @Test - public void escaped() { + void escaped() { String s = "o\\ ne two"; assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", "two"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "two"); @@ -52,28 +52,28 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { } @Test - public void quoted() { + void quoted() { String s = "'o ne' 't w o'"; assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", "'t w o'"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test - public void doubleQuoted() { + void doubleQuoted() { String s = "\"o ne\" \"t w o\""; assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o ne\"", "\"t w o\""); assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test - public void nestedQuotes() { + void nestedQuotes() { String s = "\"o 'n''e\" 't \"w o'"; assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o 'n''e\"", "'t \"w o'"); assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", "t \"w o"); } @Test - public void escapedQuotes() { + void escapedQuotes() { String s = "\\'a b"; ArgumentList argumentList = this.delimiter.delimit(s, 0); assertThat(argumentList.getArguments()).isEqualTo(new String[] { "\\'a", "b" }); @@ -81,7 +81,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { } @Test - public void escapes() { + void escapes() { String s = "\\ \\\\.\\\\\\t"; assertThat(this.delimiter.parseArguments(s)).containsExactly(" \\.\\\t"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java index cd1cdc9c7d0..fae77e6994e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java @@ -25,8 +25,8 @@ import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.control.SourceUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -41,7 +41,7 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ -public class DependencyCustomizerTests { +class DependencyCustomizerTests { private final ModuleNode moduleNode = new ModuleNode((SourceUnit) null); @@ -52,7 +52,7 @@ public class DependencyCustomizerTests { private DependencyCustomizer dependencyCustomizer; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); @@ -70,7 +70,7 @@ public class DependencyCustomizerTests { } @Test - public void basicAdd() { + void basicAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging"); List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); @@ -80,7 +80,7 @@ public class DependencyCustomizerTests { } @Test - public void nonTransitiveAdd() { + void nonTransitiveAdd() { this.dependencyCustomizer.add("spring-boot-starter-logging", false); List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); @@ -90,7 +90,7 @@ public class DependencyCustomizerTests { } @Test - public void fullyCustomized() { + void fullyCustomized() { this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", "my-type", false); List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); @@ -100,39 +100,39 @@ public class DependencyCustomizerTests { } @Test - public void anyMissingClassesWithMissingClassesPerformsAdd() { + void anyMissingClassesWithMissingClassesPerformsAdd() { this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist").add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test - public void anyMissingClassesWithMixtureOfClassesPerformsAdd() { + void anyMissingClassesWithMixtureOfClassesPerformsAdd() { this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test - public void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() { + void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test - public void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() { + void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()).add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test - public void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() { + void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test - public void allMissingClassesWithAllClassesMissingPerformsAdd() { + void allMissingClassesWithAllClassesMissingPerformsAdd() { this.dependencyCustomizer.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") .add("spring-boot-starter-logging"); assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java index 2f2f0d9cea2..0ff98234a0a 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.cli.compiler; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -27,39 +26,34 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -public class ExtendedGroovyClassLoaderTests { +class ExtendedGroovyClassLoaderTests { - private ClassLoader contextClassLoader; + private final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - private ExtendedGroovyClassLoader defaultScopeGroovyClassLoader; - - @Before - public void setup() { - this.contextClassLoader = Thread.currentThread().getContextClassLoader(); - this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(GroovyCompilerScope.DEFAULT); - } + private final ExtendedGroovyClassLoader defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader( + GroovyCompilerScope.DEFAULT); @Test - public void loadsGroovyFromSameClassLoader() throws Exception { + void loadsGroovyFromSameClassLoader() throws Exception { Class c1 = this.contextClassLoader.loadClass("groovy.lang.Script"); Class c2 = this.defaultScopeGroovyClassLoader.loadClass("groovy.lang.Script"); assertThat(c1.getClassLoader()).isSameAs(c2.getClassLoader()); } @Test - public void filtersNonGroovy() throws Exception { + void filtersNonGroovy() throws Exception { this.contextClassLoader.loadClass("org.springframework.util.StringUtils"); assertThatExceptionOfType(ClassNotFoundException.class) .isThrownBy(() -> this.defaultScopeGroovyClassLoader.loadClass("org.springframework.util.StringUtils")); } @Test - public void loadsJavaTypes() throws Exception { + void loadsJavaTypes() throws Exception { this.defaultScopeGroovyClassLoader.loadClass("java.lang.Boolean"); } @Test - public void loadsSqlTypes() throws Exception { + void loadsSqlTypes() throws Exception { this.contextClassLoader.loadClass("java.sql.SQLException"); this.defaultScopeGroovyClassLoader.loadClass("java.sql.SQLException"); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java index e788f657916..7f80939c89f 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java @@ -31,7 +31,7 @@ import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.transform.ASTTransformation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.groovy.DependencyManagementBom; @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Dave Syer */ -public final class GenericBomAstTransformationTests { +final class GenericBomAstTransformationTests { private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); @@ -64,21 +64,21 @@ public final class GenericBomAstTransformationTests { }; @Test - public void transformationOfEmptyPackage() { + void transformationOfEmptyPackage() { this.moduleNode.setPackage(new PackageNode("foo")); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]"); } @Test - public void transformationOfClass() { + void transformationOfClass() { this.moduleNode.addClass(ClassHelper.make("MyClass")); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]"); } @Test - public void transformationOfClassWithExistingManagedDependencies() { + void transformationOfClassWithExistingManagedDependencies() { this.moduleNode.setPackage(new PackageNode("foo")); ClassNode cls = ClassHelper.make("MyClass"); this.moduleNode.addClass(cls); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index fa7116d6b2e..b784f3d422c 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -20,7 +20,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; import org.springframework.boot.test.util.TestPropertyValues; @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class RepositoryConfigurationFactoryTests { +class RepositoryConfigurationFactoryTests { @Test - public void defaultRepositories() { + void defaultRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic").applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory .createDefaultRepositoryConfiguration(); @@ -46,7 +46,7 @@ public class RepositoryConfigurationFactoryTests { } @Test - public void snapshotRepositoriesDisabled() { + void snapshotRepositoriesDisabled() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true") .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory @@ -57,7 +57,7 @@ public class RepositoryConfigurationFactoryTests { } @Test - public void activeByDefaultProfileRepositories() { + void activeByDefaultProfileRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories") .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory @@ -69,7 +69,7 @@ public class RepositoryConfigurationFactoryTests { } @Test - public void activeByPropertyProfileRepositories() { + void activeByPropertyProfileRepositories() { TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar") .applyToSystemProperties(() -> { List repositoryConfiguration = RepositoryConfigurationFactory @@ -81,7 +81,7 @@ public class RepositoryConfigurationFactoryTests { } @Test - public void interpolationProfileRepositories() { + void interpolationProfileRepositories() { TestPropertyValues .of("user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true") .applyToSystemProperties(() -> { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java index 26ceeaf0e91..7fb6e1d9597 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java @@ -39,8 +39,8 @@ import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.transform.ASTTransformation; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver; import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement; @@ -55,7 +55,7 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public final class ResolveDependencyCoordinatesTransformationTests { +final class ResolveDependencyCoordinatesTransformationTests { private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null); @@ -81,40 +81,40 @@ public final class ResolveDependencyCoordinatesTransformationTests { private final ASTTransformation transformation = new ResolveDependencyCoordinatesTransformation( this.resolutionContext); - @Before - public void setupExpectations() { + @BeforeEach + public void setUpExpectations() { given(this.coordinatesResolver.getGroupId("spring-core")).willReturn("org.springframework"); } @Test - public void transformationOfAnnotationOnImport() { + void transformationOfAnnotationOnImport() { this.moduleNode.addImport(null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test - public void transformationOfAnnotationOnStarImport() { + void transformationOfAnnotationOnStarImport() { this.moduleNode.addStarImport("org.springframework.util", Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test - public void transformationOfAnnotationOnStaticImport() { + void transformationOfAnnotationOnStaticImport() { this.moduleNode.addStaticImport(null, null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test - public void transformationOfAnnotationOnStaticStarImport() { + void transformationOfAnnotationOnStaticStarImport() { this.moduleNode.addStaticStarImport(null, null, Arrays.asList(this.grabAnnotation)); assertGrabAnnotationHasBeenTransformed(); } @Test - public void transformationOfAnnotationOnPackage() { + void transformationOfAnnotationOnPackage() { PackageNode packageNode = new PackageNode("test"); packageNode.addAnnotation(this.grabAnnotation); this.moduleNode.setPackage(packageNode); @@ -123,7 +123,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnClass() { + void transformationOfAnnotationOnClass() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); classNode.addAnnotation(this.grabAnnotation); this.moduleNode.addClass(classNode); @@ -132,11 +132,11 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnAnnotation() { + void transformationOfAnnotationOnAnnotation() { } @Test - public void transformationOfAnnotationOnField() { + void transformationOfAnnotationOnField() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); @@ -149,7 +149,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnConstructor() { + void transformationOfAnnotationOnConstructor() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); @@ -161,7 +161,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnMethod() { + void transformationOfAnnotationOnMethod() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); @@ -174,7 +174,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnMethodParameter() { + void transformationOfAnnotationOnMethodParameter() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); @@ -189,7 +189,7 @@ public final class ResolveDependencyCoordinatesTransformationTests { } @Test - public void transformationOfAnnotationOnLocalVariable() { + void transformationOfAnnotationOnLocalVariable() { ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class)); this.moduleNode.addClass(classNode); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java index 95defdad293..4b57f7647cc 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.cli.compiler.dependencies; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -31,7 +31,7 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ -public class CompositeDependencyManagementTests { +class CompositeDependencyManagementTests { @Mock private DependencyManagement dependencyManagement1; @@ -39,13 +39,13 @@ public class CompositeDependencyManagementTests { @Mock private DependencyManagement dependencyManagement2; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void unknownSpringBootVersion() { + void unknownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) @@ -53,7 +53,7 @@ public class CompositeDependencyManagementTests { } @Test - public void knownSpringBootVersion() { + void knownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3"); given(this.dependencyManagement2.getSpringBootVersion()).willReturn("1.2.4"); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) @@ -61,7 +61,7 @@ public class CompositeDependencyManagementTests { } @Test - public void unknownDependency() { + void unknownDependency() { given(this.dependencyManagement1.find("artifact")).willReturn(null); given(this.dependencyManagement2.find("artifact")).willReturn(null); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) @@ -69,7 +69,7 @@ public class CompositeDependencyManagementTests { } @Test - public void knownDependency() { + void knownDependency() { given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3")); given(this.dependencyManagement2.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.4")); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2) @@ -77,7 +77,7 @@ public class CompositeDependencyManagementTests { } @Test - public void getDependencies() { + void getDependencies() { given(this.dependencyManagement1.getDependencies()) .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); given(this.dependencyManagement2.getDependencies()) diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java index ea3dfe2349e..c4bc9f5b99a 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.cli.compiler.dependencies; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; @@ -32,13 +32,13 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Andy Wilkinson */ -public class DependencyManagementArtifactCoordinatesResolverTests { +class DependencyManagementArtifactCoordinatesResolverTests { private DependencyManagement dependencyManagement; private DependencyManagementArtifactCoordinatesResolver resolver; - @Before + @BeforeEach public void setup() { this.dependencyManagement = mock(DependencyManagement.class); given(this.dependencyManagement.find("a1")).willReturn(new Dependency("g1", "a1", "0")); @@ -47,18 +47,18 @@ public class DependencyManagementArtifactCoordinatesResolverTests { } @Test - public void getGroupIdForBootArtifact() { + void getGroupIdForBootArtifact() { assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot"); verify(this.dependencyManagement, never()).find(anyString()); } @Test - public void getGroupIdFound() { + void getGroupIdFound() { assertThat(this.resolver.getGroupId("a1")).isEqualTo("g1"); } @Test - public void getGroupIdNotFound() { + void getGroupIdNotFound() { assertThat(this.resolver.getGroupId("a2")).isNull(); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java index e18dabec89b..16ef75265fe 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.cli.compiler.dependencies; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.empty; @@ -26,17 +26,17 @@ import static org.hamcrest.Matchers.empty; * * @author Andy Wilkinson */ -public class SpringBootDependenciesDependencyManagementTests { +class SpringBootDependenciesDependencyManagementTests { private final DependencyManagement dependencyManagement = new SpringBootDependenciesDependencyManagement(); @Test - public void springBootVersion() { + void springBootVersion() { assertThat(this.dependencyManagement.getSpringBootVersion()).isNotNull(); } @Test - public void find() { + void find() { Dependency dependency = this.dependencyManagement.find("spring-boot"); assertThat(dependency).isNotNull(); assertThat(dependency.getGroupId()).isEqualTo("org.springframework.boot"); @@ -44,7 +44,7 @@ public class SpringBootDependenciesDependencyManagementTests { } @Test - public void getDependencies() { + void getDependencies() { assertThat(this.dependencyManagement.getDependencies()).isNotEqualTo(empty()); } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java index e7f3ae02c8b..2acd6b1c4f4 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java @@ -30,7 +30,7 @@ import groovy.lang.GroovyClassLoader; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.RemoteRepository; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement; import org.springframework.test.util.ReflectionTestUtils; @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Andy Wilkinson */ -public class AetherGrapeEngineTests { +class AetherGrapeEngineTests { private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); @@ -62,7 +62,7 @@ public class AetherGrapeEngineTests { } @Test - public void dependencyResolution() { + void dependencyResolution() { Map args = new HashMap<>(); createGrapeEngine(this.springMilestones).grab(args, createDependency("org.springframework", "spring-jdbc", null)); @@ -70,7 +70,7 @@ public class AetherGrapeEngineTests { } @Test - public void proxySelector() { + void proxySelector() { doWithCustomUserHome(() -> { AetherGrapeEngine grapeEngine = createGrapeEngine(); DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils @@ -81,7 +81,7 @@ public class AetherGrapeEngineTests { } @Test - public void repositoryMirrors() { + void repositoryMirrors() { doWithCustomUserHome(() -> { List repositories = getRepositories(); assertThat(repositories).hasSize(1); @@ -90,7 +90,7 @@ public class AetherGrapeEngineTests { } @Test - public void repositoryAuthentication() { + void repositoryAuthentication() { doWithCustomUserHome(() -> { List repositories = getRepositories(); assertThat(repositories).hasSize(1); @@ -100,7 +100,7 @@ public class AetherGrapeEngineTests { } @Test - public void dependencyResolutionWithExclusions() { + void dependencyResolutionWithExclusions() { Map args = new HashMap<>(); args.put("excludes", Arrays.asList(createExclusion("org.springframework", "spring-core"))); @@ -112,7 +112,7 @@ public class AetherGrapeEngineTests { } @Test - public void nonTransitiveDependencyResolution() { + void nonTransitiveDependencyResolution() { Map args = new HashMap<>(); createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false)); @@ -121,7 +121,7 @@ public class AetherGrapeEngineTests { } @Test - public void dependencyResolutionWithCustomClassLoader() { + void dependencyResolutionWithCustomClassLoader() { Map args = new HashMap<>(); GroovyClassLoader customClassLoader = new GroovyClassLoader(); args.put("classLoader", customClassLoader); @@ -134,7 +134,7 @@ public class AetherGrapeEngineTests { } @Test - public void resolutionWithCustomResolver() { + void resolutionWithCustomResolver() { Map args = new HashMap<>(); AetherGrapeEngine grapeEngine = this.createGrapeEngine(); grapeEngine.addResolver(createResolver("spring-releases", "https://repo.spring.io/release")); @@ -146,7 +146,7 @@ public class AetherGrapeEngineTests { } @Test - public void differingTypeAndExt() { + void differingTypeAndExt() { Map dependency = createDependency("org.grails", "grails-dependencies", "2.4.0"); dependency.put("type", "foo"); dependency.put("ext", "bar"); @@ -155,7 +155,7 @@ public class AetherGrapeEngineTests { } @Test - public void pomDependencyResolutionViaType() { + void pomDependencyResolutionViaType() { Map args = new HashMap<>(); Map dependency = createDependency("org.springframework", "spring-framework-bom", "4.0.5.RELEASE"); @@ -167,7 +167,7 @@ public class AetherGrapeEngineTests { } @Test - public void pomDependencyResolutionViaExt() { + void pomDependencyResolutionViaExt() { Map args = new HashMap<>(); Map dependency = createDependency("org.springframework", "spring-framework-bom", "4.0.5.RELEASE"); @@ -179,7 +179,7 @@ public class AetherGrapeEngineTests { } @Test - public void resolutionWithClassifier() { + void resolutionWithClassifier() { Map args = new HashMap<>(); Map dependency = createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java index f5e51663658..fa4bbc37599 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DependencyResolutionContextTests.java @@ -16,25 +16,26 @@ package org.springframework.boot.cli.compiler.grape; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement; import static org.assertj.core.api.Assertions.assertThat; /** - * @author Dave Syer + * Tests for {@link DependencyResolutionContext}. * + * @author Dave Syer */ -public class DependencyResolutionContextTests { +class DependencyResolutionContextTests { @Test - public void defaultDependenciesEmpty() { + void defaultDependenciesEmpty() { assertThat(new DependencyResolutionContext().getManagedDependencies()).isEmpty(); } @Test - public void canAddSpringBootDependencies() { + void canAddSpringBootDependencies() { DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext(); dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement()); assertThat(dependencyResolutionContext.getManagedDependencies()).isNotEmpty(); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java index 1b4746b9640..c3b2c08ce0e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java @@ -23,8 +23,8 @@ import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.transfer.TransferCancelledException; import org.eclipse.aether.transfer.TransferEvent; import org.eclipse.aether.transfer.TransferResource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public final class DetailedProgressReporterTests { +final class DetailedProgressReporterTests { private static final String REPOSITORY = "https://repo.example.com/"; @@ -47,13 +47,13 @@ public final class DetailedProgressReporterTests { private final DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - @Before + @BeforeEach public void initialize() { new DetailedProgressReporter(this.session, this.out); } @Test - public void downloading() throws TransferCancelledException { + void downloading() throws TransferCancelledException { TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build(); this.session.getTransferListener().transferStarted(startedEvent); assertThat(new String(this.baos.toByteArray())) @@ -61,7 +61,7 @@ public final class DetailedProgressReporterTests { } @Test - public void downloaded() throws InterruptedException { + void downloaded() throws InterruptedException { // Ensure some transfer time Thread.sleep(100); TransferEvent completedEvent = new TransferEvent.Builder(this.session, this.resource).addTransferredBytes(4096) diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index acdca4f64c9..f7ca1d939ac 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -24,8 +24,8 @@ import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; @@ -44,20 +44,20 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class GrapeRootRepositorySystemSessionAutoConfigurationTests { +class GrapeRootRepositorySystemSessionAutoConfigurationTests { private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); @Mock private RepositorySystem repositorySystem; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void noLocalRepositoryWhenNoGrapeRoot() { + void noLocalRepositoryWhenNoGrapeRoot() { given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) .willAnswer((invocation) -> { LocalRepository localRepository = invocation.getArgument(1); @@ -70,7 +70,7 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { } @Test - public void grapeRootConfiguresLocalRepositoryLocation() { + void grapeRootConfiguresLocalRepositoryLocation() { given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) .willAnswer(new LocalRepositoryManagerAnswer()); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index db060b33fc6..3b644dc2f9c 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -27,8 +27,8 @@ import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.Proxy; import org.eclipse.aether.repository.RemoteRepository; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -44,28 +44,28 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ -public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { +class SettingsXmlRepositorySystemSessionAutoConfigurationTests { @Mock private RepositorySystem repositorySystem; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void basicSessionCustomization() { + void basicSessionCustomization() { assertSessionCustomization("src/test/resources/maven-settings/basic"); } @Test - public void encryptedSettingsSessionCustomization() { + void encryptedSettingsSessionCustomization() { assertSessionCustomization("src/test/resources/maven-settings/encrypted"); } @Test - public void propertyInterpolation() { + void propertyInterpolation() { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class))) .willAnswer((invocation) -> { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java index dea6fdba79a..12ab21f012b 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java @@ -21,7 +21,7 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.ClassUtils; @@ -32,17 +32,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class ResourceUtilsTests { +class ResourceUtilsTests { @Test - public void explicitClasspathResource() { + void explicitClasspathResource() { List urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void duplicateResource() throws Exception { + void duplicateResource() throws Exception { URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:./src/test/resources/"), new File("src/test/resources/").getAbsoluteFile().toURI().toURL() }); List urls = ResourceUtils.getUrls("classpath:init.groovy", loader); @@ -51,34 +51,34 @@ public class ResourceUtilsTests { } @Test - public void explicitClasspathResourceWithSlash() { + void explicitClasspathResourceWithSlash() { List urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void implicitClasspathResource() { + void implicitClasspathResource() { List urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void implicitClasspathResourceWithSlash() { + void implicitClasspathResourceWithSlash() { List urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void nonexistentClasspathResource() { + void nonexistentClasspathResource() { List urls = ResourceUtils.getUrls("classpath:nonexistent.groovy", null); assertThat(urls).isEmpty(); } @Test - public void explicitFile() { + void explicitFile() { List urls = ResourceUtils.getUrls("file:src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); @@ -86,27 +86,27 @@ public class ResourceUtilsTests { } @Test - public void implicitFile() { + void implicitFile() { List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void nonexistentFile() { + void nonexistentFile() { List urls = ResourceUtils.getUrls("file:nonexistent.groovy", null); assertThat(urls).isEmpty(); } @Test - public void recursiveFiles() { + void recursiveFiles() { List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test - public void recursiveFilesByPatternWithPrefix() { + void recursiveFilesByPatternWithPrefix() { List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); @@ -114,7 +114,7 @@ public class ResourceUtilsTests { } @Test - public void recursiveFilesByPattern() { + void recursiveFilesByPattern() { List urls = ResourceUtils.getUrls("src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); @@ -122,7 +122,7 @@ public class ResourceUtilsTests { } @Test - public void directoryOfFilesWithPrefix() { + void directoryOfFilesWithPrefix() { List urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); @@ -130,7 +130,7 @@ public class ResourceUtilsTests { } @Test - public void directoryOfFiles() { + void directoryOfFiles() { List urls = ResourceUtils.getUrls("src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); assertThat(urls).hasSize(1); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index de4bb1b8820..c2a9407de85 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -17,8 +17,8 @@ package org.springframework.boot.devtools; import ch.qos.logback.classic.Logger; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; @@ -34,41 +34,41 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class RemoteUrlPropertyExtractorTests { +class RemoteUrlPropertyExtractorTests { - @After + @AfterEach public void preventRunFailuresFromPollutingLoggerContext() { ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() .getTurboFilterList().clear(); } @Test - public void missingUrl() { + void missingUrl() { assertThatIllegalStateException().isThrownBy(this::doTest).withMessageContaining("No remote URL specified"); } @Test - public void malformedUrl() { + void malformedUrl() { assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble")) .withMessageContaining("Malformed URL '::://wibble'"); } @Test - public void multipleUrls() { + void multipleUrls() { assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090")) .withMessageContaining("Multiple URLs specified"); } @Test - public void validUrl() { + void validUrl() { ApplicationContext context = doTest("http://localhost:8080"); assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")).isNull(); } @Test - public void cleanValidUrl() { + void cleanValidUrl() { ApplicationContext context = doTest("http://localhost:8080/"); assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java index 37f6b2ea79b..c38ec1e7039 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/AbstractDevToolsDataSourceAutoConfigurationTests.java @@ -25,7 +25,7 @@ import java.util.function.Supplier; import javax.sql.DataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; @@ -48,10 +48,10 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { +abstract class AbstractDevToolsDataSourceAutoConfigurationTests { @Test - public void singleManuallyConfiguredDataSourceIsNotClosed() throws Exception { + void singleManuallyConfiguredDataSourceIsNotClosed() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext(SingleDataSourceConfiguration.class)); DataSource dataSource = context.getBean(DataSource.class); Statement statement = configureDataSourceBehavior(dataSource); @@ -59,7 +59,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { } @Test - public void multipleDataSourcesAreIgnored() throws Exception { + void multipleDataSourcesAreIgnored() throws Exception { ConfigurableApplicationContext context = getContext( () -> createContext(MultipleDataSourcesConfiguration.class)); Collection dataSources = context.getBeansOfType(DataSource.class).values(); @@ -70,7 +70,7 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { } @Test - public void emptyFactoryMethodMetadataIgnored() { + void emptyFactoryMethodMetadataIgnored() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); DataSource dataSource = mock(DataSource.class); AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(dataSource.getClass()); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java index 150c49b1f04..8fbe54a1647 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java @@ -16,16 +16,16 @@ package org.springframework.boot.devtools.autoconfigure; +import java.io.File; import java.io.IOException; import java.sql.Statement; import javax.sql.DataSource; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.ConfigurableApplicationContext; @@ -39,23 +39,20 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { +class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); - - @Before - public void before() throws IOException { - System.setProperty("derby.stream.error.file", this.temp.newFile("derby.log").getAbsolutePath()); + @BeforeEach + public void before(@TempDir File tempDir) throws IOException { + System.setProperty("derby.stream.error.file", new File(tempDir, "derby.log").getAbsolutePath()); } - @After + @AfterEach public void after() { System.clearProperty("derby.stream.error.file"); } @Test - public void autoConfiguredInMemoryDataSourceIsShutdown() throws Exception { + void autoConfiguredInMemoryDataSourceIsShutdown() throws Exception { ConfigurableApplicationContext context = getContext( () -> createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -64,7 +61,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void autoConfiguredExternalDataSourceIsNotShutdown() throws Exception { + void autoConfiguredExternalDataSourceIsNotShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.postgresql.Driver", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -73,7 +70,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void h2ServerIsNotShutdown() throws Exception { + void h2ServerIsNotShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver", "jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -82,7 +79,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void inMemoryH2IsShutdown() throws Exception { + void inMemoryH2IsShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.h2.Driver", "jdbc:h2:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -91,7 +88,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void hsqlServerIsNotShutdown() throws Exception { + void hsqlServerIsNotShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver", "jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -100,7 +97,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void inMemoryHsqlIsShutdown() throws Exception { + void inMemoryHsqlIsShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -109,7 +106,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void derbyClientIsNotShutdown() throws Exception { + void derbyClientIsNotShutdown() throws Exception { ConfigurableApplicationContext context = getContext(() -> createContext("org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); @@ -118,7 +115,7 @@ public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevT } @Test - public void inMemoryDerbyIsShutdown() throws Exception { + void inMemoryDerbyIsShutdown() throws Exception { ConfigurableApplicationContext configurableApplicationContext = getContext( () -> createContext("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java index b7f0b054df6..f0136459382 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.autoconfigure; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,12 +25,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class DevToolsPropertiesTests { +class DevToolsPropertiesTests { private final DevToolsProperties devToolsProperties = new DevToolsProperties(); @Test - public void additionalExcludeKeepsDefaults() { + void additionalExcludeKeepsDefaults() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setAdditionalExclude("foo/**,bar/**"); assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", "META-INF/resources/**", "resources/**", @@ -39,7 +39,7 @@ public class DevToolsPropertiesTests { } @Test - public void additionalExcludeNoDefault() { + void additionalExcludeNoDefault() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setExclude(""); restart.setAdditionalExclude("foo/**,bar/**"); @@ -47,7 +47,7 @@ public class DevToolsPropertiesTests { } @Test - public void additionalExcludeCustomDefault() { + void additionalExcludeCustomDefault() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setExclude("biz/**"); restart.setAdditionalExclude("foo/**,bar/**"); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index 8ab5d61d3e4..bd289bb678c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -27,9 +27,9 @@ import java.util.function.Supplier; import org.apache.catalina.Container; import org.apache.catalina.core.StandardWrapper; import org.apache.jasper.EmbeddedServletOptions; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -71,14 +71,12 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Vladimir Tsanev */ -public class LocalDevToolsAutoConfigurationTests { - - @Rule - public MockRestarter mockRestarter = new MockRestarter(); +@ExtendWith(MockRestarter.class) +class LocalDevToolsAutoConfigurationTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanup() { if (this.context != null) { this.context.close(); @@ -86,21 +84,21 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void thymeleafCacheIsFalse() throws Exception { + void thymeleafCacheIsFalse() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isFalse(); } @Test - public void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception { + void defaultPropertyCanBeOverriddenFromCommandLine() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class, "--spring.thymeleaf.cache=true")); SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } @Test - public void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception { + void defaultPropertyCanBeOverriddenFromUserHomeProperties() throws Exception { String userHome = System.getProperty("user.home"); System.setProperty("user.home", new File("src/test/resources/user-home").getAbsolutePath()); try { @@ -114,21 +112,21 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void resourceCachePeriodIsZero() throws Exception { + void resourceCachePeriodIsZero() throws Exception { this.context = getContext(() -> initializeAndRun(WebResourcesConfig.class)); ResourceProperties properties = this.context.getBean(ResourceProperties.class); assertThat(properties.getCache().getPeriod()).isEqualTo(Duration.ZERO); } @Test - public void liveReloadServer() throws Exception { + void liveReloadServer() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); assertThat(server.isStarted()).isTrue(); } @Test - public void liveReloadTriggeredOnContextRefresh() throws Exception { + void liveReloadTriggeredOnContextRefresh() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); @@ -137,7 +135,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void liveReloadTriggeredOnClassPathChangeWithoutRestart() throws Exception { + void liveReloadTriggeredOnClassPathChangeWithoutRestart() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); @@ -147,7 +145,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void liveReloadNotTriggeredOnClassPathChangeWithRestart() throws Exception { + void liveReloadNotTriggeredOnClassPathChangeWithRestart() throws Exception { this.context = getContext(() -> initializeAndRun(ConfigWithMockLiveReload.class)); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); reset(server); @@ -157,7 +155,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void liveReloadDisabled() throws Exception { + void liveReloadDisabled() throws Exception { Map properties = new HashMap<>(); properties.put("spring.devtools.livereload.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); @@ -166,30 +164,30 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void restartTriggeredOnClassPathChangeWithRestart() throws Exception { + void restartTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); this.context.publishEvent(event); - verify(this.mockRestarter.getMock()).restart(any(FailureHandler.class)); + verify(restarter).restart(any(FailureHandler.class)); } @Test - public void restartNotTriggeredOnClassPathChangeWithRestart() throws Exception { + void restartNotTriggeredOnClassPathChangeWithRestart(Restarter restarter) throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); this.context.publishEvent(event); - verify(this.mockRestarter.getMock(), never()).restart(); + verify(restarter, never()).restart(); } @Test - public void restartWatchingClassPath() throws Exception { + void restartWatchingClassPath() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class); assertThat(watcher).isNotNull(); } @Test - public void restartDisabled() throws Exception { + void restartDisabled() throws Exception { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); @@ -198,7 +196,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void restartWithTriggerFile() throws Exception { + void restartWithTriggerFile() throws Exception { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.trigger-file", "somefile.txt"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); @@ -209,7 +207,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void watchingAdditionalPaths() throws Exception { + void watchingAdditionalPaths() throws Exception { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.additional-paths", "src/main/java,src/test/java"); this.context = getContext(() -> initializeAndRun(Config.class, properties)); @@ -222,7 +220,7 @@ public class LocalDevToolsAutoConfigurationTests { } @Test - public void devToolsSwitchesJspServletToDevelopmentMode() throws Exception { + void devToolsSwitchesJspServletToDevelopmentMode() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); TomcatWebServer tomcatContainer = (TomcatWebServer) ((ServletWebServerApplicationContext) this.context) .getWebServer(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java index feed1538c8b..f4905c99627 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsConditionTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.devtools.autoconfigure; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -33,18 +33,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class OnEnabledDevToolsConditionTests { +class OnEnabledDevToolsConditionTests { private AnnotationConfigApplicationContext context; - @Before + @BeforeEach public void setup() { this.context = new AnnotationConfigApplicationContext(); this.context.register(TestConfiguration.class); } @Test - public void outcomeWhenDevtoolsShouldBeEnabledIsTrueShouldMatch() throws Exception { + void outcomeWhenDevtoolsShouldBeEnabledIsTrueShouldMatch() throws Exception { AtomicBoolean containsBean = new AtomicBoolean(); Thread thread = new Thread(() -> { OnEnabledDevToolsConditionTests.this.context.refresh(); @@ -56,7 +56,7 @@ public class OnEnabledDevToolsConditionTests { } @Test - public void outcomeWhenDevtoolsShouldBeEnabledIsFalseShouldNotMatch() { + void outcomeWhenDevtoolsShouldBeEnabledIsFalseShouldNotMatch() { OnEnabledDevToolsConditionTests.this.context.refresh(); assertThat(OnEnabledDevToolsConditionTests.this.context.containsBean("test")).isFalse(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServerTests.java index d2fad752b80..d9fa321b118 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.autoconfigure; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.devtools.livereload.LiveReloadServer; @@ -30,17 +30,17 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class OptionalLiveReloadServerTests { +class OptionalLiveReloadServerTests { @Test - public void nullServer() throws Exception { + void nullServer() throws Exception { OptionalLiveReloadServer server = new OptionalLiveReloadServer(null); server.startServer(); server.triggerReload(); } @Test - public void serverWontStart() throws Exception { + void serverWontStart() throws Exception { LiveReloadServer delegate = mock(LiveReloadServer.class); OptionalLiveReloadServer server = new OptionalLiveReloadServer(delegate); willThrow(new RuntimeException("Error")).given(delegate).start(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index 199e8460af7..0232f943e65 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -19,10 +19,10 @@ package org.springframework.boot.devtools.autoconfigure; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -52,15 +52,13 @@ import static org.mockito.Mockito.mock; * @author Rob Winch * @author Phillip Webb */ -public class RemoteDevToolsAutoConfigurationTests { +@ExtendWith(MockRestarter.class) +class RemoteDevToolsAutoConfigurationTests { private static final String DEFAULT_CONTEXT_PATH = RemoteDevToolsProperties.DEFAULT_CONTEXT_PATH; private static final String DEFAULT_SECRET_HEADER_NAME = RemoteDevToolsProperties.DEFAULT_SECRET_HEADER_NAME; - @Rule - public MockRestarter mockRestarter = new MockRestarter(); - private AnnotationConfigServletWebApplicationContext context; private MockHttpServletRequest request; @@ -69,14 +67,14 @@ public class RemoteDevToolsAutoConfigurationTests { private MockFilterChain chain; - @Before + @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.chain = new MockFilterChain(); } - @After + @AfterEach public void close() { if (this.context != null) { this.context.close(); @@ -84,14 +82,14 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void disabledIfRemoteSecretIsMissing() throws Exception { + void disabledIfRemoteSecretIsMissing() throws Exception { this.context = getContext(() -> loadContext("a:b")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); } @Test - public void ignoresUnmappedUrl() throws Exception { + void ignoresUnmappedUrl() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI("/restart"); @@ -101,7 +99,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void ignoresIfMissingSecretFromRequest() throws Exception { + void ignoresIfMissingSecretFromRequest() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); @@ -110,7 +108,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void ignoresInvalidSecretInRequest() throws Exception { + void ignoresInvalidSecretInRequest() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); @@ -120,7 +118,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void invokeRestartWithDefaultSetup() throws Exception { + void invokeRestartWithDefaultSetup() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH + "/restart"); @@ -130,7 +128,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void invokeRestartWithCustomServerContextPath() throws Exception { + void invokeRestartWithCustomServerContextPath() throws Exception { this.context = getContext( () -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); @@ -141,7 +139,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void disableRestart() throws Exception { + void disableRestart() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) @@ -149,7 +147,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void devToolsHealthReturns200() throws Exception { + void devToolsHealthReturns200() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); this.request.setRequestURI(DEFAULT_CONTEXT_PATH); @@ -160,7 +158,7 @@ public class RemoteDevToolsAutoConfigurationTests { } @Test - public void devToolsHealthWithCustomServerContextPathReturns200() throws Exception { + void devToolsHealthWithCustomServerContextPathReturns200() throws Exception { this.context = getContext( () -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java index 55b91675839..ae16db4bab8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java @@ -18,9 +18,8 @@ package org.springframework.boot.devtools.autoconfigure; import java.io.File; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -30,32 +29,35 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class TriggerFileFilterTests { +class TriggerFileFilterTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void nameMustNotBeNull() { + void nameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null)) .withMessageContaining("Name must not be null"); } @Test - public void acceptNameMatch() throws Exception { - File file = this.temp.newFile("thefile.txt"); + void acceptNameMatch() throws Exception { + File file = new File(this.tempDir, "thefile.txt"); + file.createNewFile(); assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isTrue(); } @Test - public void doesNotAcceptNameMismatch() throws Exception { - File file = this.temp.newFile("notthefile.txt"); + void doesNotAcceptNameMismatch() throws Exception { + File file = new File(this.tempDir, "notthefile.txt"); + file.createNewFile(); assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isFalse(); } @Test - public void testName() throws Exception { - File file = this.temp.newFile(".triggerfile").getAbsoluteFile(); + void testName() throws Exception { + File file = new File(this.tempDir, ".triggerfile"); + file.createNewFile(); assertThat(new TriggerFileFilter(".triggerfile").accept(file)).isTrue(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index e9597941b37..0b2641a98d6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.devtools.classpath; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.devtools.filewatch.ChangedFiles; @@ -31,25 +31,25 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ClassPathChangedEventTests { +class ClassPathChangedEventTests { private Object source = new Object(); @Test - public void changeSetMustNotBeNull() { + void changeSetMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) .withMessageContaining("ChangeSet must not be null"); } @Test - public void getChangeSet() { + void getChangeSet() { Set changeSet = new LinkedHashSet<>(); ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false); assertThat(event.getChangeSet()).isSameAs(changeSet); } @Test - public void getRestartRequired() { + void getRestartRequired() { Set changeSet = new LinkedHashSet<>(); ClassPathChangedEvent event; event = new ClassPathChangedEvent(this.source, changeSet, false); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index b6280d9d7f8..48d492c739e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -21,8 +21,8 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ClassPathFileChangeListenerTests { +class ClassPathFileChangeListenerTests { @Mock private ApplicationEventPublisher eventPublisher; @@ -59,33 +59,33 @@ public class ClassPathFileChangeListenerTests { @Captor private ArgumentCaptor eventCaptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void eventPublisherMustNotBeNull() { + void eventPublisherMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) .withMessageContaining("EventPublisher must not be null"); } @Test - public void restartStrategyMustNotBeNull() { + void restartStrategyMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) .withMessageContaining("RestartStrategy must not be null"); } @Test - public void sendsEventWithoutRestart() { + void sendsEventWithoutRestart() { testSendsEvent(false); verify(this.fileSystemWatcher, never()).stop(); } @Test - public void sendsEventWithRestart() { + void sendsEventWithRestart() { testSendsEvent(true); verify(this.fileSystemWatcher).stop(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index 7b24c9396be..a04d1c37aab 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -24,9 +24,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.filewatch.FileSystemWatcher; import org.springframework.boot.devtools.filewatch.FileSystemWatcherFactory; @@ -47,13 +46,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ClassPathFileSystemWatcherTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class ClassPathFileSystemWatcherTests { @Test - public void urlsMustNotBeNull() { + void urlsMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), mock(ClassPathRestartStrategy.class), (URL[]) null)) @@ -61,10 +57,9 @@ public class ClassPathFileSystemWatcherTests { } @Test - public void configuredWithRestartStrategy() throws Exception { + void configuredWithRestartStrategy(@TempDir File folder) throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); Map properties = new HashMap<>(); - File folder = this.temp.newFolder(); List urls = new ArrayList<>(); urls.add(new URL("https://spring.io")); urls.add(folder.toURI().toURL()); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java index bb397c40d37..1f15a5bc6bc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.devtools.classpath; import java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.devtools.filewatch.ChangedFile; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; @@ -31,22 +31,22 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andrew Landsverk */ -public class PatternClassPathRestartStrategyTests { +class PatternClassPathRestartStrategyTests { @Test - public void nullPattern() { + void nullPattern() { ClassPathRestartStrategy strategy = createStrategy(null); assertRestartRequired(strategy, "a/b.txt", true); } @Test - public void emptyPattern() { + void emptyPattern() { ClassPathRestartStrategy strategy = createStrategy(""); assertRestartRequired(strategy, "a/b.txt", true); } @Test - public void singlePattern() { + void singlePattern() { ClassPathRestartStrategy strategy = createStrategy("static/**"); assertRestartRequired(strategy, "static/file.txt", false); assertRestartRequired(strategy, "static/folder/file.txt", false); @@ -55,7 +55,7 @@ public class PatternClassPathRestartStrategyTests { } @Test - public void multiplePatterns() { + void multiplePatterns() { ClassPathRestartStrategy strategy = createStrategy("static/**,public/**"); assertRestartRequired(strategy, "static/file.txt", false); assertRestartRequired(strategy, "static/folder/file.txt", false); @@ -66,7 +66,7 @@ public class PatternClassPathRestartStrategyTests { } @Test - public void pomChange() { + void pomChange() { ClassPathRestartStrategy strategy = createStrategy("META-INF/maven/**"); assertRestartRequired(strategy, "pom.xml", true); String mavenFolder = "META-INF/maven/org.springframework.boot/spring-boot-devtools"; @@ -75,7 +75,7 @@ public class PatternClassPathRestartStrategyTests { } @Test - public void testChange() { + void testChange() { ClassPathRestartStrategy strategy = createStrategy("**/*Test.class,**/*Tests.class"); assertRestartRequired(strategy, "com/example/ExampleTests.class", false); assertRestartRequired(strategy, "com/example/ExampleTest.class", false); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index e994737793e..f932950303d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -21,9 +21,9 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.SpringApplication; @@ -45,16 +45,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Andy Wilkinson */ -public class DevToolPropertiesIntegrationTests { +class DevToolPropertiesIntegrationTests { private ConfigurableApplicationContext context; - @Before + @BeforeEach public void setup() { Restarter.initialize(new String[] {}, false, new MockInitializer(), false); } - @After + @AfterEach public void cleanup() { if (this.context != null) { this.context.close(); @@ -63,7 +63,7 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void classPropertyConditionIsAffectedByDevToolProperties() throws Exception { + void classPropertyConditionIsAffectedByDevToolProperties() throws Exception { SpringApplication application = new SpringApplication(ClassConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); @@ -71,7 +71,7 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception { + void beanMethodPropertyConditionIsAffectedByDevToolProperties() throws Exception { SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); @@ -79,7 +79,7 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception { + void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); @@ -90,7 +90,7 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception { + void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() throws Exception { Restarter.clearInstance(); Restarter.disable(); SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); @@ -101,7 +101,7 @@ public class DevToolPropertiesIntegrationTests { } @Test - public void postProcessEnablesIncludeStackTraceProperty() throws Exception { + void postProcessEnablesIncludeStackTraceProperty() throws Exception { SpringApplication application = new SpringApplication(TestConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java index ea98786c393..75b13648e66 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java @@ -22,10 +22,9 @@ import java.io.IOException; import java.io.OutputStream; import java.util.Properties; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; @@ -38,20 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class DevToolsHomePropertiesPostProcessorTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class DevToolsHomePropertiesPostProcessorTests { private File home; - @Before - public void setup() throws IOException { - this.home = this.temp.newFolder(); + @BeforeEach + public void setup(@TempDir File tempDir) throws IOException { + this.home = tempDir; } @Test - public void loadsHomeProperties() throws Exception { + void loadsHomeProperties() throws Exception { Properties properties = new Properties(); properties.put("abc", "def"); OutputStream out = new FileOutputStream(new File(this.home, ".spring-boot-devtools.properties")); @@ -64,7 +60,7 @@ public class DevToolsHomePropertiesPostProcessorTests { } @Test - public void ignoresMissingHomeProperties() throws Exception { + void ignoresMissingHomeProperties() throws Exception { ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null)); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index c772f9748d6..add7e2ceb3a 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -18,9 +18,8 @@ package org.springframework.boot.devtools.filewatch; import java.io.File; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; @@ -32,49 +31,52 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ChangedFileTests { +class ChangedFileTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void sourceFolderMustNotBeNull() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(null, this.temp.newFile(), Type.ADD)) + void sourceFolderMustNotBeNull() throws Exception { + assertThatIllegalArgumentException() + .isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD)) .withMessageContaining("SourceFolder must not be null"); } @Test - public void fileMustNotBeNull() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> new ChangedFile(this.temp.newFolder(), null, Type.ADD)) + void fileMustNotBeNull() throws Exception { + assertThatIllegalArgumentException() + .isThrownBy(() -> new ChangedFile(new File(this.tempDir, "folder"), null, Type.ADD)) .withMessageContaining("File must not be null"); } @Test - public void typeMustNotBeNull() throws Exception { + void typeMustNotBeNull() throws Exception { assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null)) + .isThrownBy( + () -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "folder"), null)) .withMessageContaining("Type must not be null"); } @Test - public void getFile() throws Exception { - File file = this.temp.newFile(); - ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), file, Type.ADD); + void getFile() throws Exception { + File file = new File(this.tempDir, "file"); + ChangedFile changedFile = new ChangedFile(new File(this.tempDir, "folder"), file, Type.ADD); assertThat(changedFile.getFile()).isEqualTo(file); } @Test - public void getType() throws Exception { - ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), this.temp.newFile(), Type.DELETE); + void getType() throws Exception { + ChangedFile changedFile = new ChangedFile(new File(this.tempDir, "folder"), new File(this.tempDir, "file"), + Type.DELETE); assertThat(changedFile.getType()).isEqualTo(Type.DELETE); } @Test - public void getRelativeName() throws Exception { - File folder = this.temp.newFolder(); - File subFolder = new File(folder, "A"); + void getRelativeName() throws Exception { + File subFolder = new File(this.tempDir, "A"); File file = new File(subFolder, "B.txt"); - ChangedFile changedFile = new ChangedFile(folder, file, Type.ADD); + ChangedFile changedFile = new ChangedFile(this.tempDir, file, Type.ADD); assertThat(changedFile.getRelativeName()).isEqualTo("A/B.txt"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index 0c427ed94ee..36affb7666c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -19,11 +19,11 @@ package org.springframework.boot.devtools.filewatch; import java.io.File; import java.io.IOException; import java.util.Date; +import java.util.UUID; import java.util.concurrent.TimeUnit; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.FileCopyUtils; @@ -35,29 +35,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class FileSnapshotTests { +class FileSnapshotTests { private static final long TWO_MINS = TimeUnit.MINUTES.toMillis(2); private static final long MODIFIED = new Date().getTime() - TimeUnit.DAYS.toMillis(10); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void fileMustNotBeNull() { + void fileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(null)) .withMessageContaining("File must not be null"); } @Test - public void fileMustNotBeAFolder() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(this.temporaryFolder.newFolder())) + void fileMustNotBeAFolder() throws Exception { + File file = new File(this.tempDir, "file"); + file.mkdir(); + assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(file)) .withMessageContaining("File must not be a folder"); } @Test - public void equalsIfTheSame() throws Exception { + void equalsIfTheSame() throws Exception { File file = createNewFile("abc", MODIFIED); File fileCopy = new File(file, "x").getParentFile(); FileSnapshot snapshot1 = new FileSnapshot(file); @@ -67,7 +69,7 @@ public class FileSnapshotTests { } @Test - public void notEqualsIfDeleted() throws Exception { + void notEqualsIfDeleted() throws Exception { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); file.delete(); @@ -75,7 +77,7 @@ public class FileSnapshotTests { } @Test - public void notEqualsIfLengthChanges() throws Exception { + void notEqualsIfLengthChanges() throws Exception { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); setupFile(file, "abcd", MODIFIED); @@ -83,7 +85,7 @@ public class FileSnapshotTests { } @Test - public void notEqualsIfLastModifiedChanges() throws Exception { + void notEqualsIfLastModifiedChanges() throws Exception { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); setupFile(file, "abc", MODIFIED + TWO_MINS); @@ -91,7 +93,7 @@ public class FileSnapshotTests { } private File createNewFile(String content, long lastModified) throws IOException { - File file = this.temporaryFolder.newFile(); + File file = new File(this.tempDir, UUID.randomUUID().toString()); setupFile(file, content, lastModified); return file; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index c08bc9baf15..bce652e6f49 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -26,11 +26,11 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.UUID; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; @@ -45,62 +45,62 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class FileSystemWatcherTests { +class FileSystemWatcherTests { private FileSystemWatcher watcher; private List> changes = Collections.synchronizedList(new ArrayList<>()); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; - @Before + @BeforeEach public void setup() { setupWatcher(20, 10); } @Test - public void pollIntervalMustBePositive() { + void pollIntervalMustBePositive() { assertThatIllegalArgumentException() .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) .withMessageContaining("PollInterval must be positive"); } @Test - public void quietPeriodMustBePositive() { + void quietPeriodMustBePositive() { assertThatIllegalArgumentException() .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) .withMessageContaining("QuietPeriod must be positive"); } @Test - public void pollIntervalMustBeGreaterThanQuietPeriod() { + void pollIntervalMustBeGreaterThanQuietPeriod() { assertThatIllegalArgumentException() .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) .withMessageContaining("PollInterval must be greater than QuietPeriod"); } @Test - public void listenerMustNotBeNull() { + void listenerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addListener(null)) .withMessageContaining("FileChangeListener must not be null"); } @Test - public void cannotAddListenerToStartedListener() { + void cannotAddListenerToStartedListener() { this.watcher.start(); assertThatIllegalStateException().isThrownBy(() -> this.watcher.addListener(mock(FileChangeListener.class))) .withMessageContaining("FileSystemWatcher already started"); } @Test - public void sourceFolderMustNotBeNull() { + void sourceFolderMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(null)) .withMessageContaining("Folder must not be null"); } @Test - public void sourceFolderMustNotBeAFile() { + void sourceFolderMustNotBeAFile() { File folder = new File("pom.xml"); assertThat(folder.isFile()).isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceFolder(new File("pom.xml"))) @@ -108,14 +108,14 @@ public class FileSystemWatcherTests { } @Test - public void cannotAddSourceFolderToStartedListener() throws Exception { + void cannotAddSourceFolderToStartedListener() throws Exception { this.watcher.start(); - assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceFolder(this.temp.newFolder())) + assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceFolder(this.tempDir)) .withMessageContaining("FileSystemWatcher already started"); } @Test - public void addFile() throws Exception { + void addFile() throws Exception { File folder = startWithNewFolder(); File file = touch(new File(folder, "test.txt")); this.watcher.stopAfter(1); @@ -125,7 +125,7 @@ public class FileSystemWatcherTests { } @Test - public void addNestedFile() throws Exception { + void addNestedFile() throws Exception { File folder = startWithNewFolder(); File file = touch(new File(new File(folder, "sub"), "text.txt")); this.watcher.stopAfter(1); @@ -135,8 +135,8 @@ public class FileSystemWatcherTests { } @Test - public void createSourceFolderAndAddFile() throws IOException { - File folder = new File(this.temp.getRoot(), "does/not/exist"); + void createSourceFolderAndAddFile() throws IOException { + File folder = new File(this.tempDir, "does/not/exist"); assertThat(folder.exists()).isFalse(); this.watcher.addSourceFolder(folder); this.watcher.start(); @@ -149,7 +149,7 @@ public class FileSystemWatcherTests { } @Test - public void waitsForPollingInterval() throws Exception { + void waitsForPollingInterval() throws Exception { setupWatcher(10, 1); File folder = startWithNewFolder(); touch(new File(folder, "test1.txt")); @@ -162,7 +162,7 @@ public class FileSystemWatcherTests { } @Test - public void waitsForQuietPeriod() throws Exception { + void waitsForQuietPeriod() throws Exception { setupWatcher(300, 200); File folder = startWithNewFolder(); for (int i = 0; i < 10; i++) { @@ -175,8 +175,9 @@ public class FileSystemWatcherTests { } @Test - public void withExistingFiles() throws Exception { - File folder = this.temp.newFolder(); + void withExistingFiles() throws Exception { + File folder = new File(this.tempDir, UUID.randomUUID().toString()); + folder.mkdir(); touch(new File(folder, "test.txt")); this.watcher.addSourceFolder(folder); this.watcher.start(); @@ -188,9 +189,11 @@ public class FileSystemWatcherTests { } @Test - public void multipleSources() throws Exception { - File folder1 = this.temp.newFolder(); - File folder2 = this.temp.newFolder(); + void multipleSources() throws Exception { + File folder1 = new File(this.tempDir, UUID.randomUUID().toString()); + folder1.mkdir(); + File folder2 = new File(this.tempDir, UUID.randomUUID().toString()); + folder2.mkdir(); this.watcher.addSourceFolder(folder1); this.watcher.addSourceFolder(folder2); this.watcher.start(); @@ -212,8 +215,9 @@ public class FileSystemWatcherTests { } @Test - public void multipleListeners() throws Exception { - File folder = this.temp.newFolder(); + void multipleListeners() throws Exception { + File folder = new File(this.tempDir, UUID.randomUUID().toString()); + folder.mkdir(); final Set listener2Changes = new LinkedHashSet<>(); this.watcher.addSourceFolder(folder); this.watcher.addListener(listener2Changes::addAll); @@ -227,8 +231,9 @@ public class FileSystemWatcherTests { } @Test - public void modifyDeleteAndAdd() throws Exception { - File folder = this.temp.newFolder(); + void modifyDeleteAndAdd() throws Exception { + File folder = new File(this.tempDir, UUID.randomUUID().toString()); + folder.mkdir(); File modify = touch(new File(folder, "modify.txt")); File delete = touch(new File(folder, "delete.txt")); this.watcher.addSourceFolder(folder); @@ -247,8 +252,9 @@ public class FileSystemWatcherTests { } @Test - public void withTriggerFilter() throws Exception { - File folder = this.temp.newFolder(); + void withTriggerFilter() throws Exception { + File folder = new File(this.tempDir, UUID.randomUUID().toString()); + folder.mkdir(); File file = touch(new File(folder, "file.txt")); File trigger = touch(new File(folder, "trigger.txt")); this.watcher.addSourceFolder(folder); @@ -272,7 +278,8 @@ public class FileSystemWatcherTests { } private File startWithNewFolder() throws IOException { - File folder = this.temp.newFolder(); + File folder = new File(this.tempDir, UUID.randomUUID().toString()); + folder.mkdir(); this.watcher.addSourceFolder(folder); this.watcher.start(); return folder; diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java index d57afda693c..44a7a79051c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java @@ -18,11 +18,11 @@ package org.springframework.boot.devtools.filewatch; import java.io.File; import java.io.IOException; +import java.util.UUID; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; @@ -35,64 +35,65 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class FolderSnapshotTests { +class FolderSnapshotTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private File folder; private FolderSnapshot initialSnapshot; - @Before + @BeforeEach public void setup() throws Exception { this.folder = createTestFolderStructure(); this.initialSnapshot = new FolderSnapshot(this.folder); } @Test - public void folderMustNotBeNull() { + void folderMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(null)) .withMessageContaining("Folder must not be null"); } @Test - public void folderMustNotBeFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void folderMustNotBeFile() throws Exception { + File file = new File(this.tempDir, "file"); + file.createNewFile(); assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(file)) .withMessageContaining("Folder '" + file + "' must not be a file"); } @Test - public void folderDoesNotHaveToExist() throws Exception { - File file = new File(this.temporaryFolder.getRoot(), "does/not/exist"); + void folderDoesNotHaveToExist() throws Exception { + File file = new File(this.tempDir, "does/not/exist"); FolderSnapshot snapshot = new FolderSnapshot(file); assertThat(snapshot).isEqualTo(new FolderSnapshot(file)); } @Test - public void equalsWhenNothingHasChanged() { + void equalsWhenNothingHasChanged() { FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); assertThat(this.initialSnapshot).isEqualTo(updatedSnapshot); assertThat(this.initialSnapshot.hashCode()).isEqualTo(updatedSnapshot.hashCode()); } @Test - public void notEqualsWhenAFileIsAdded() throws Exception { + void notEqualsWhenAFileIsAdded() throws Exception { new File(new File(this.folder, "folder1"), "newfile").createNewFile(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test - public void notEqualsWhenAFileIsDeleted() { + void notEqualsWhenAFileIsDeleted() { new File(new File(this.folder, "folder1"), "file1").delete(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test - public void notEqualsWhenAFileIsModified() throws Exception { + void notEqualsWhenAFileIsModified() throws Exception { File file1 = new File(new File(this.folder, "folder1"), "file1"); FileCopyUtils.copy("updatedcontent".getBytes(), file1); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); @@ -100,26 +101,26 @@ public class FolderSnapshotTests { } @Test - public void getChangedFilesSnapshotMustNotBeNull() { + void getChangedFilesSnapshotMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) .withMessageContaining("Snapshot must not be null"); } @Test - public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { + void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { assertThatIllegalArgumentException().isThrownBy( () -> this.initialSnapshot.getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null)) .withMessageContaining("Snapshot source folder must be '" + this.folder + "'"); } @Test - public void getChangedFilesWhenNothingHasChanged() { + void getChangedFilesWhenNothingHasChanged() { FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); this.initialSnapshot.getChangedFiles(updatedSnapshot, null); } @Test - public void getChangedFilesWhenAFileIsAddedAndDeletedAndChanged() throws Exception { + void getChangedFilesWhenAFileIsAddedAndDeletedAndChanged() throws Exception { File folder1 = new File(this.folder, "folder1"); File file1 = new File(folder1, "file1"); File file2 = new File(folder1, "file2"); @@ -145,7 +146,7 @@ public class FolderSnapshotTests { } private File createTestFolderStructure() throws IOException { - File root = this.temporaryFolder.newFolder(); + File root = new File(this.tempDir, UUID.randomUUID().toString()); File folder1 = new File(root, "folder1"); folder1.mkdirs(); FileCopyUtils.copy("abc".getBytes(), new File(folder1, "file1")); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java index 586b0a611b9..11e45856cbc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java @@ -20,7 +20,7 @@ import java.io.IOException; import java.util.Collection; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.devtools.integrationtest.HttpTunnelIntegrationTests.TunnelConfiguration.TestTunnelClient; @@ -59,10 +59,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class HttpTunnelIntegrationTests { +class HttpTunnelIntegrationTests { @Test - public void httpServerDirect() { + void httpServerDirect() { AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); context.register(ServerConfiguration.class); context.refresh(); @@ -74,7 +74,7 @@ public class HttpTunnelIntegrationTests { } @Test - public void viaTunnel() { + void viaTunnel() { AnnotationConfigServletWebServerApplicationContext serverContext = new AnnotationConfigServletWebServerApplicationContext(); serverContext.register(ServerConfiguration.class); serverContext.refresh(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 05bbd45422c..d088d44d01d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -21,7 +21,7 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThatIOException; * @author Phillip Webb */ @SuppressWarnings("resource") -public class ConnectionInputStreamTests { +class ConnectionInputStreamTests { private static final byte[] NO_BYTES = {}; @Test - public void readHeader() throws Exception { + void readHeader() throws Exception { String header = ""; for (int i = 0; i < 100; i++) { header += "x-something-" + i + ": xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; @@ -48,7 +48,7 @@ public class ConnectionInputStreamTests { } @Test - public void readFully() throws Exception { + void readFully() throws Exception { byte[] bytes = "the data that we want to read fully".getBytes(); LimitedInputStream source = new LimitedInputStream(new ByteArrayInputStream(bytes), 2); ConnectionInputStream inputStream = new ConnectionInputStream(source); @@ -58,13 +58,13 @@ public class ConnectionInputStreamTests { } @Test - public void checkedRead() throws Exception { + void checkedRead() throws Exception { ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); assertThatIOException().isThrownBy(inputStream::checkedRead).withMessageContaining("End of stream"); } @Test - public void checkedReadArray() throws Exception { + void checkedReadArray() throws Exception { byte[] buffer = new byte[100]; ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java index 9ae70e2ead8..22d03591b54 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java @@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -32,10 +32,10 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @SuppressWarnings("resource") -public class ConnectionOutputStreamTests { +class ConnectionOutputStreamTests { @Test - public void write() throws Exception { + void write() throws Exception { OutputStream out = mock(OutputStream.class); ConnectionOutputStream outputStream = new ConnectionOutputStream(out); byte[] b = new byte[100]; @@ -44,7 +44,7 @@ public class ConnectionOutputStreamTests { } @Test - public void writeHttp() throws Exception { + void writeHttp() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ConnectionOutputStream outputStream = new ConnectionOutputStream(out); outputStream.writeHttp(new ByteArrayInputStream("hi".getBytes()), "x-type"); @@ -58,7 +58,7 @@ public class ConnectionOutputStreamTests { } @Test - public void writeHeaders() throws Exception { + void writeHeaders() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ConnectionOutputStream outputStream = new ConnectionOutputStream(out); outputStream.writeHeaders("A: a", "B: b"); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index 5a5b7f2ebca..94c369125b2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -31,36 +31,36 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class FrameTests { +class FrameTests { @Test - public void payloadMustNotBeNull() { + void payloadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((String) null)) .withMessageContaining("Payload must not be null"); } @Test - public void typeMustNotBeNull() { + void typeMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((Frame.Type) null)) .withMessageContaining("Type must not be null"); } @Test - public void textPayload() { + void textPayload() { Frame frame = new Frame("abc"); assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); assertThat(frame.getPayload()).isEqualTo("abc".getBytes()); } @Test - public void typedPayload() { + void typedPayload() { Frame frame = new Frame(Frame.Type.CLOSE); assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE); assertThat(frame.getPayload()).isEqualTo(new byte[] {}); } @Test - public void writeSmallPayload() throws Exception { + void writeSmallPayload() throws Exception { String payload = createString(1); Frame frame = new Frame(payload); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -69,7 +69,7 @@ public class FrameTests { } @Test - public void writeLargePayload() throws Exception { + void writeLargePayload() throws Exception { String payload = createString(126); Frame frame = new Frame(payload); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -85,21 +85,21 @@ public class FrameTests { } @Test - public void readFragmentedNotSupported() throws Exception { + void readFragmentedNotSupported() throws Exception { byte[] bytes = new byte[] { 0x0F }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) .withMessageContaining("Fragmented frames are not supported"); } @Test - public void readLargeFramesNotSupported() throws Exception { + void readLargeFramesNotSupported() throws Exception { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) .withMessageContaining("Large frames are not supported"); } @Test - public void readSmallTextFrame() throws Exception { + void readSmallTextFrame() throws Exception { byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x02, 0x41, 0x41 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); @@ -107,7 +107,7 @@ public class FrameTests { } @Test - public void readMaskedTextFrame() throws Exception { + void readMaskedTextFrame() throws Exception { byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, 0x4E, 0x4E }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); @@ -115,7 +115,7 @@ public class FrameTests { } @Test - public void readLargeTextFrame() throws Exception { + void readLargeTextFrame() throws Exception { byte[] bytes = new byte[134]; Arrays.fill(bytes, (byte) 0x4E); bytes[0] = (byte) 0x81; @@ -132,35 +132,35 @@ public class FrameTests { } @Test - public void readContinuation() throws Exception { + void readContinuation() throws Exception { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.CONTINUATION); } @Test - public void readBinary() throws Exception { + void readBinary() throws Exception { byte[] bytes = new byte[] { (byte) 0x82, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.BINARY); } @Test - public void readClose() throws Exception { + void readClose() throws Exception { byte[] bytes = new byte[] { (byte) 0x88, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE); } @Test - public void readPing() throws Exception { + void readPing() throws Exception { byte[] bytes = new byte[] { (byte) 0x89, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.PING); } @Test - public void readPong() throws Exception { + void readPong() throws Exception { byte[] bytes = new byte[] { (byte) 0x8A, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); assertThat(frame.getType()).isEqualTo(Frame.Type.PONG); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index eedb3b95432..25f74aed379 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -26,10 +26,10 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.tomcat.websocket.WsWebSocketContainer; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.web.client.RestTemplate; import org.springframework.web.socket.CloseStatus; @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class LiveReloadServerTests { +class LiveReloadServerTests { private static final String HANDSHAKE = "{command: 'hello', " + "protocols: ['http://livereload.com/protocols/official-7']}"; @@ -59,20 +59,20 @@ public class LiveReloadServerTests { private MonitoredLiveReloadServer server; - @Before + @BeforeEach public void setUp() throws Exception { this.server = new MonitoredLiveReloadServer(0); this.port = this.server.start(); } - @After + @AfterEach public void tearDown() throws Exception { this.server.stop(); } @Test - @Ignore - public void servesLivereloadJs() throws Exception { + @Disabled + void servesLivereloadJs() throws Exception { RestTemplate template = new RestTemplate(); URI uri = new URI("http://localhost:" + this.port + "/livereload.js"); String script = template.getForObject(uri, String.class); @@ -80,7 +80,7 @@ public class LiveReloadServerTests { } @Test - public void triggerReload() throws Exception { + void triggerReload() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.triggerReload(); Thread.sleep(200); @@ -90,7 +90,7 @@ public class LiveReloadServerTests { } @Test - public void pingPong() throws Exception { + void pingPong() throws Exception { LiveReloadWebSocketHandler handler = connect(); handler.sendMessage(new PingMessage()); Thread.sleep(200); @@ -99,7 +99,7 @@ public class LiveReloadServerTests { } @Test - public void clientClose() throws Exception { + void clientClose() throws Exception { LiveReloadWebSocketHandler handler = connect(); handler.close(); awaitClosedException(); @@ -114,7 +114,7 @@ public class LiveReloadServerTests { } @Test - public void serverClose() throws Exception { + void serverClose() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.stop(); Thread.sleep(200); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index 0432e74e8f0..ff056bc822b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -26,10 +26,9 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.classpath.ClassPathChangedEvent; import org.springframework.boot.devtools.filewatch.ChangedFile; @@ -53,50 +52,46 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Andy Wilkinson */ -public class ClassPathChangeUploaderTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class ClassPathChangeUploaderTests { private MockClientHttpRequestFactory requestFactory; private ClassPathChangeUploader uploader; - @Before + @BeforeEach public void setup() { this.requestFactory = new MockClientHttpRequestFactory(); this.uploader = new ClassPathChangeUploader("http://localhost/upload", this.requestFactory); } @Test - public void urlMustNotBeNull() { + void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test - public void urlMustNotBeEmpty() { + void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test - public void requestFactoryMustNotBeNull() { + void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) .withMessageContaining("RequestFactory must not be null"); } @Test - public void urlMustNotBeMalformed() { + void urlMustNotBeMalformed() { assertThatIllegalArgumentException() .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test - public void sendsClassLoaderFiles() throws Exception { - File sourceFolder = this.temp.newFolder(); + void sendsClassLoaderFiles(@TempDir File sourceFolder) throws Exception { ClassPathChangedEvent event = createClassPathChangedEvent(sourceFolder); this.requestFactory.willRespond(HttpStatus.OK); this.uploader.onApplicationEvent(event); @@ -106,8 +101,7 @@ public class ClassPathChangeUploaderTests { } @Test - public void retriesOnSocketException() throws Exception { - File sourceFolder = this.temp.newFolder(); + void retriesOnSocketException(@TempDir File sourceFolder) throws Exception { ClassPathChangedEvent event = createClassPathChangedEvent(sourceFolder); this.requestFactory.willRespond(new SocketException()); this.requestFactory.willRespond(HttpStatus.OK); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index 469b97b23bb..a6237130b1b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.devtools.remote.client; import java.io.IOException; import java.net.URI; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class DelayedLiveReloadTriggerTests { +class DelayedLiveReloadTriggerTests { private static final String URL = "http://localhost:8080"; @@ -66,7 +66,7 @@ public class DelayedLiveReloadTriggerTests { private DelayedLiveReloadTrigger trigger; - @Before + @BeforeEach public void setup() throws IOException { MockitoAnnotations.initMocks(this); given(this.errorRequest.execute()).willReturn(this.errorResponse); @@ -77,35 +77,35 @@ public class DelayedLiveReloadTriggerTests { } @Test - public void liveReloadServerMustNotBeNull() { + void liveReloadServerMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) .withMessageContaining("LiveReloadServer must not be null"); } @Test - public void requestFactoryMustNotBeNull() { + void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) .withMessageContaining("RequestFactory must not be null"); } @Test - public void urlMustNotBeNull() { + void urlMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) .withMessageContaining("URL must not be empty"); } @Test - public void urlMustNotBeEmpty() { + void urlMustNotBeEmpty() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) .withMessageContaining("URL must not be empty"); } @Test - public void triggerReloadOnStatus() throws Exception { + void triggerReloadOnStatus() throws Exception { given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); @@ -116,7 +116,7 @@ public class DelayedLiveReloadTriggerTests { } @Test - public void timeout() throws Exception { + void timeout() throws Exception { given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()); this.trigger.setTimings(10, 0, 10); this.trigger.run(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index 86c5e1c801f..58692c5a9ad 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.devtools.remote.client; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.given; * @author Rob Winch * @since 1.3.0 */ -public class HttpHeaderInterceptorTests { +class HttpHeaderInterceptorTests { private String name; @@ -59,7 +59,7 @@ public class HttpHeaderInterceptorTests { private MockHttpServletRequest httpRequest; - @Before + @BeforeEach public void setup() throws Exception { MockitoAnnotations.initMocks(this); this.body = new byte[] {}; @@ -72,31 +72,31 @@ public class HttpHeaderInterceptorTests { } @Test - public void constructorNullHeaderName() { + void constructorNullHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) .withMessageContaining("Name must not be empty"); } @Test - public void constructorEmptyHeaderName() { + void constructorEmptyHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) .withMessageContaining("Name must not be empty"); } @Test - public void constructorNullHeaderValue() { + void constructorNullHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) .withMessageContaining("Value must not be empty"); } @Test - public void constructorEmptyHeaderValue() { + void constructorEmptyHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) .withMessageContaining("Value must not be empty"); } @Test - public void intercept() throws IOException { + void intercept() throws IOException { ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution); assertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value); assertThat(result).isEqualTo(this.response); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index e884fe5d0dd..6e2fa3db7e5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -21,9 +21,9 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -37,7 +37,8 @@ import org.springframework.boot.devtools.remote.server.Dispatcher; import org.springframework.boot.devtools.remote.server.DispatcherFilter; import org.springframework.boot.devtools.restart.MockRestarter; import org.springframework.boot.devtools.restart.RestartScopeInitializer; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; @@ -59,19 +60,14 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class RemoteClientConfigurationTests { - - @Rule - public MockRestarter restarter = new MockRestarter(); - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith({ OutputCaptureExtension.class, MockRestarter.class }) +class RemoteClientConfigurationTests { private AnnotationConfigServletWebServerApplicationContext context; private AnnotationConfigApplicationContext clientContext; - @After + @AfterEach public void cleanup() { if (this.context != null) { this.context.close(); @@ -82,31 +78,31 @@ public class RemoteClientConfigurationTests { } @Test - public void warnIfRestartDisabled() { + void warnIfRestartDisabled(CapturedOutput capturedOutput) { configure("spring.devtools.remote.restart.enabled:false"); - assertThat(this.output.toString()).contains("Remote restart is disabled"); + assertThat(capturedOutput).contains("Remote restart is disabled"); } @Test - public void warnIfNotHttps() { + void warnIfNotHttps(CapturedOutput capturedOutput) { configure("http://localhost", true); - assertThat(this.output.toString()).contains("is insecure"); + assertThat(capturedOutput).contains("is insecure"); } @Test - public void doesntWarnIfUsingHttps() { + void doesntWarnIfUsingHttps(CapturedOutput capturedOutput) { configure("https://localhost", true); - assertThat(this.output.toString()).doesNotContain("is insecure"); + assertThat(capturedOutput).doesNotContain("is insecure"); } @Test - public void failIfNoSecret() { + void failIfNoSecret() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> configure("http://localhost", false)) .withMessageContaining("required to secure your connection"); } @Test - public void liveReloadOnClassPathChanged() throws Exception { + void liveReloadOnClassPathChanged() throws Exception { configure(); Set changeSet = new HashSet<>(); ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false); @@ -119,14 +115,14 @@ public class RemoteClientConfigurationTests { } @Test - public void liveReloadDisabled() { + void liveReloadDisabled() { configure("spring.devtools.livereload.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test - public void remoteRestartDisabled() { + void remoteRestartDisabled() { configure("spring.devtools.remote.restart.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 7e2cf31db91..16ca385136b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -22,8 +22,8 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -49,7 +49,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class DispatcherFilterTests { +class DispatcherFilterTests { @Mock private Dispatcher dispatcher; @@ -65,20 +65,20 @@ public class DispatcherFilterTests { private DispatcherFilter filter; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.filter = new DispatcherFilter(this.dispatcher); } @Test - public void dispatcherMustNotBeNull() { + void dispatcherMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DispatcherFilter(null)) .withMessageContaining("Dispatcher must not be null"); } @Test - public void ignoresNotServletRequests() throws Exception { + void ignoresNotServletRequests() throws Exception { ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); this.filter.doFilter(request, response, this.chain); @@ -87,7 +87,7 @@ public class DispatcherFilterTests { } @Test - public void ignoredByDispatcher() throws Exception { + void ignoredByDispatcher() throws Exception { HttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); HttpServletResponse response = new MockHttpServletResponse(); this.filter.doFilter(request, response, this.chain); @@ -95,7 +95,7 @@ public class DispatcherFilterTests { } @Test - public void handledByDispatcher() throws Exception { + void handledByDispatcher() throws Exception { HttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); HttpServletResponse response = new MockHttpServletResponse(); willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class)); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 1f10d35be78..1d7fd8aaf2c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -20,8 +20,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -49,7 +49,7 @@ import static org.mockito.Mockito.withSettings; * * @author Phillip Webb */ -public class DispatcherTests { +class DispatcherTests { @Mock private AccessManager accessManager; @@ -62,7 +62,7 @@ public class DispatcherTests { private ServerHttpResponse serverResponse; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.request = new MockHttpServletRequest(); @@ -72,19 +72,19 @@ public class DispatcherTests { } @Test - public void accessManagerMustNotBeNull() { + void accessManagerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) .withMessageContaining("AccessManager must not be null"); } @Test - public void mappersMustNotBeNull() { + void mappersMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null)) .withMessageContaining("Mappers must not be null"); } @Test - public void accessManagerVetoRequest() throws Exception { + void accessManagerVetoRequest() throws Exception { given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(false); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); @@ -96,7 +96,7 @@ public class DispatcherTests { } @Test - public void accessManagerAllowRequest() throws Exception { + void accessManagerAllowRequest() throws Exception { given(this.accessManager.isAllowed(any(ServerHttpRequest.class))).willReturn(true); HandlerMapper mapper = mock(HandlerMapper.class); Handler handler = mock(Handler.class); @@ -107,7 +107,7 @@ public class DispatcherTests { } @Test - public void ordersMappers() throws Exception { + void ordersMappers() throws Exception { HandlerMapper mapper1 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); HandlerMapper mapper2 = mock(HandlerMapper.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) mapper1).getOrder()).willReturn(1); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index fd2eb4b55eb..c0bd058ae2c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.devtools.remote.server; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Rob Winch * @author Phillip Webb */ -public class HttpHeaderAccessManagerTests { +class HttpHeaderAccessManagerTests { private static final String HEADER = "X-AUTH_TOKEN"; @@ -44,7 +44,7 @@ public class HttpHeaderAccessManagerTests { private HttpHeaderAccessManager manager; - @Before + @BeforeEach public void setup() { this.request = new MockHttpServletRequest("GET", "/"); this.serverRequest = new ServletServerHttpRequest(this.request); @@ -52,48 +52,48 @@ public class HttpHeaderAccessManagerTests { } @Test - public void headerNameMustNotBeNull() { + void headerNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) .withMessageContaining("HeaderName must not be empty"); } @Test - public void headerNameMustNotBeEmpty() { + void headerNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) .withMessageContaining("HeaderName must not be empty"); } @Test - public void expectedSecretMustNotBeNull() { + void expectedSecretMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) .withMessageContaining("ExpectedSecret must not be empty"); } @Test - public void expectedSecretMustNotBeEmpty() { + void expectedSecretMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) .withMessageContaining("ExpectedSecret must not be empty"); } @Test - public void allowsMatching() { + void allowsMatching() { this.request.addHeader(HEADER, SECRET); assertThat(this.manager.isAllowed(this.serverRequest)).isTrue(); } @Test - public void disallowsWrongSecret() { + void disallowsWrongSecret() { this.request.addHeader(HEADER, "wrong"); assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } @Test - public void disallowsNoSecret() { + void disallowsNoSecret() { assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } @Test - public void disallowsWrongHeader() { + void disallowsWrongHeader() { this.request.addHeader("X-WRONG", SECRET); assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java index d6072f6ce41..580a412eed9 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.boot.devtools.remote.server; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.server.ServerHttpRequest; @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class HttpStatusHandlerTests { +class HttpStatusHandlerTests { private MockHttpServletRequest servletRequest; @@ -45,7 +45,7 @@ public class HttpStatusHandlerTests { private ServerHttpRequest request; - @Before + @BeforeEach public void setup() { this.servletRequest = new MockHttpServletRequest(); this.servletResponse = new MockHttpServletResponse(); @@ -54,20 +54,20 @@ public class HttpStatusHandlerTests { } @Test - public void statusMustNotBeNull() { + void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null)) .withMessageContaining("Status must not be null"); } @Test - public void respondsOk() throws Exception { + void respondsOk() throws Exception { HttpStatusHandler handler = new HttpStatusHandler(); handler.handle(this.request, this.response); assertThat(this.servletResponse.getStatus()).isEqualTo(200); } @Test - public void respondsWithStatus() throws Exception { + void respondsWithStatus() throws Exception { HttpStatusHandler handler = new HttpStatusHandler(HttpStatus.I_AM_A_TEAPOT); handler.handle(this.request, this.response); assertThat(this.servletResponse.getStatus()).isEqualTo(418); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index c467dedb041..d4f425bf7e2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.devtools.remote.server; import javax.servlet.http.HttpServletRequest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; @@ -34,30 +34,30 @@ import static org.mockito.Mockito.mock; * @author Rob Winch * @author Phillip Webb */ -public class UrlHandlerMapperTests { +class UrlHandlerMapperTests { private Handler handler = mock(Handler.class); @Test - public void requestUriMustNotBeNull() { + void requestUriMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) .withMessageContaining("URL must not be empty"); } @Test - public void requestUriMustNotBeEmpty() { + void requestUriMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("", this.handler)) .withMessageContaining("URL must not be empty"); } @Test - public void requestUrlMustStartWithSlash() { + void requestUrlMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) .withMessageContaining("URL must start with '/'"); } @Test - public void handlesMatchedUrl() { + void handlesMatchedUrl() { UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler); HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); @@ -65,7 +65,7 @@ public class UrlHandlerMapperTests { } @Test - public void ignoresDifferentUrl() { + void ignoresDifferentUrl() { UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler); HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel/other"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index 5328097fedc..915bd982e83 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -21,14 +21,14 @@ import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; +import java.util.UUID; import java.util.jar.Attributes; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipOutputStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.StringUtils; @@ -40,37 +40,39 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class ChangeableUrlsTests { +class ChangeableUrlsTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void folderUrl() throws Exception { + void folderUrl() throws Exception { URL url = makeUrl("myproject"); assertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(1); } @Test - public void fileUrl() throws Exception { - URL url = this.temporaryFolder.newFile().toURI().toURL(); + void fileUrl() throws Exception { + File file = new File(this.tempDir, "file"); + file.createNewFile(); + URL url = file.toURI().toURL(); assertThat(ChangeableUrls.fromUrls(url)).isEmpty(); } @Test - public void httpUrl() throws Exception { + void httpUrl() throws Exception { URL url = new URL("https://spring.io"); assertThat(ChangeableUrls.fromUrls(url)).isEmpty(); } @Test - public void httpsUrl() throws Exception { + void httpsUrl() throws Exception { URL url = new URL("https://spring.io"); assertThat(ChangeableUrls.fromUrls(url)).isEmpty(); } @Test - public void skipsUrls() throws Exception { + void skipsUrls() throws Exception { ChangeableUrls urls = ChangeableUrls.fromUrls(makeUrl("spring-boot"), makeUrl("spring-boot-autoconfigure"), makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"), makeUrl("spring-boot-starter-some-thing")); @@ -78,9 +80,12 @@ public class ChangeableUrlsTests { } @Test - public void urlsFromJarClassPathAreConsidered() throws Exception { - File relative = this.temporaryFolder.newFolder(); - URL absoluteUrl = this.temporaryFolder.newFolder().toURI().toURL(); + void urlsFromJarClassPathAreConsidered() throws Exception { + File relative = new File(this.tempDir, UUID.randomUUID().toString()); + relative.mkdir(); + File absolute = new File(this.tempDir, UUID.randomUUID().toString()); + absolute.mkdirs(); + URL absoluteUrl = absolute.toURI().toURL(); File jarWithClassPath = makeJarFileWithUrlsInManifestClassPath("project-core/target/classes/", "project-web/target/classes/", "does-not-exist/target/classes", relative.getName() + "/", absoluteUrl); new File(jarWithClassPath.getParentFile(), "project-core/target/classes").mkdirs(); @@ -94,7 +99,7 @@ public class ChangeableUrlsTests { } private URL makeUrl(String name) throws IOException { - File file = this.temporaryFolder.newFolder(); + File file = new File(this.tempDir, UUID.randomUUID().toString()); file = new File(file, name); file = new File(file, "target"); file = new File(file, "classes"); @@ -103,7 +108,7 @@ public class ChangeableUrlsTests { } private File makeJarFileWithUrlsInManifestClassPath(Object... urls) throws Exception { - File classpathJar = this.temporaryFolder.newFile("classpath.jar"); + File classpathJar = new File(this.tempDir, "classpath.jar"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), @@ -113,7 +118,7 @@ public class ChangeableUrlsTests { } private URL makeJarFileWithNoManifest() throws Exception { - File classpathJar = this.temporaryFolder.newFile("no-manifest.jar"); + File classpathJar = new File(this.tempDir, "no-manifest.jar"); new ZipOutputStream(new FileOutputStream(classpathJar)).close(); return classpathJar.toURI().toURL(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java index 7cdfcedc5f6..52efd3b941c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolverTests.java @@ -19,10 +19,9 @@ package org.springframework.boot.devtools.restart; import java.io.File; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.restart.ClassLoaderFilesResourcePatternResolver.DeletedClassLoaderFileResource; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; @@ -52,34 +51,31 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class ClassLoaderFilesResourcePatternResolverTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class ClassLoaderFilesResourcePatternResolverTests { private ClassLoaderFiles files; private ClassLoaderFilesResourcePatternResolver resolver; - @Before + @BeforeEach public void setup() { this.files = new ClassLoaderFiles(); this.resolver = new ClassLoaderFilesResourcePatternResolver(new GenericApplicationContext(), this.files); } @Test - public void getClassLoaderShouldReturnClassLoader() { + void getClassLoaderShouldReturnClassLoader() { assertThat(this.resolver.getClassLoader()).isNotNull(); } @Test - public void getResourceShouldReturnResource() { + void getResourceShouldReturnResource() { Resource resource = this.resolver.getResource("index.html"); assertThat(resource).isNotNull().isInstanceOf(ClassPathResource.class); } @Test - public void getResourceWhenHasServletContextShouldReturnServletResource() { + void getResourceWhenHasServletContextShouldReturnServletResource() { GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); Resource resource = this.resolver.getResource("index.html"); @@ -87,8 +83,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void getResourceWhenDeletedShouldReturnDeletedResource() throws Exception { - File folder = this.temp.newFolder(); + void getResourceWhenDeletedShouldReturnDeletedResource(@TempDir File folder) throws Exception { File file = createFile(folder, "name.class"); this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); Resource resource = this.resolver.getResource("file:" + file.getAbsolutePath()); @@ -96,16 +91,14 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void getResourcesShouldReturnResources() throws Exception { - File folder = this.temp.newFolder(); + void getResourcesShouldReturnResources(@TempDir File folder) throws Exception { createFile(folder, "name.class"); Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); assertThat(resources).isNotEmpty(); } @Test - public void getResourcesWhenDeletedShouldFilterDeleted() throws Exception { - File folder = this.temp.newFolder(); + void getResourcesWhenDeletedShouldFilterDeleted(@TempDir File folder) throws Exception { createFile(folder, "name.class"); this.files.addFile(folder.getName(), "name.class", new ClassLoaderFile(Kind.DELETED, null)); Resource[] resources = this.resolver.getResources("file:" + folder.getAbsolutePath() + "/**"); @@ -113,7 +106,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void customResourceLoaderIsUsedInNonWebApplication() { + void customResourceLoaderIsUsedInNonWebApplication() { GenericApplicationContext context = new GenericApplicationContext(); ResourceLoader resourceLoader = mock(ResourceLoader.class); context.setResourceLoader(resourceLoader); @@ -123,7 +116,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void customProtocolResolverIsUsedInNonWebApplication() { + void customProtocolResolverIsUsedInNonWebApplication() { GenericApplicationContext context = new GenericApplicationContext(); Resource resource = mock(Resource.class); ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource); @@ -135,7 +128,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void customResourceLoaderIsUsedInWebApplication() { + void customResourceLoaderIsUsedInWebApplication() { GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); ResourceLoader resourceLoader = mock(ResourceLoader.class); context.setResourceLoader(resourceLoader); @@ -145,7 +138,7 @@ public class ClassLoaderFilesResourcePatternResolverTests { } @Test - public void customProtocolResolverIsUsedInWebApplication() { + void customProtocolResolverIsUsedInWebApplication() { GenericWebApplicationContext context = new GenericWebApplicationContext(new MockServletContext()); Resource resource = mock(Resource.class); ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java index f73fc5d9569..bd55a1265fd 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.restart; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -29,30 +29,30 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Madhura Bhave */ -public class DefaultRestartInitializerTests { +class DefaultRestartInitializerTests { @Test - public void jUnitStackShouldReturnNull() { + void jUnitStackShouldReturnNull() { testSkippedStacks("org.junit.runners.Something"); } @Test - public void jUnit5StackShouldReturnNull() { + void jUnit5StackShouldReturnNull() { testSkippedStacks("org.junit.platform.Something"); } @Test - public void springTestStackShouldReturnNull() { + void springTestStackShouldReturnNull() { testSkippedStacks("org.springframework.boot.test.Something"); } @Test - public void cucumberStackShouldReturnNull() { + void cucumberStackShouldReturnNull() { testSkippedStacks("cucumber.runtime.Runtime.run"); } @Test - public void validMainThreadShouldReturnUrls() { + void validMainThreadShouldReturnUrls() { DefaultRestartInitializer initializer = new DefaultRestartInitializer(); ClassLoader classLoader = new MockAppClassLoader(getClass().getClassLoader()); Thread thread = new Thread(); @@ -62,7 +62,7 @@ public class DefaultRestartInitializerTests { } @Test - public void threadNotNamedMainShouldReturnNull() { + void threadNotNamedMainShouldReturnNull() { DefaultRestartInitializer initializer = new DefaultRestartInitializer(); ClassLoader classLoader = new MockAppClassLoader(getClass().getClassLoader()); Thread thread = new Thread(); @@ -72,7 +72,7 @@ public class DefaultRestartInitializerTests { } @Test - public void threadNotUsingAppClassLoader() { + void threadNotUsingAppClassLoader() { DefaultRestartInitializer initializer = new DefaultRestartInitializer(); ClassLoader classLoader = new MockLauncherClassLoader(getClass().getClassLoader()); Thread thread = new Thread(); @@ -82,7 +82,7 @@ public class DefaultRestartInitializerTests { } @Test - public void urlsCanBeRetrieved() { + void urlsCanBeRetrieved() { assertThat(new DefaultRestartInitializer().getUrls(Thread.currentThread())).isNotEmpty(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 4ec8fd44dd2..d5e0a47db4b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.devtools.restart; import java.lang.reflect.Method; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.util.ReflectionUtils; @@ -32,38 +32,38 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class MainMethodTests { +class MainMethodTests { private static ThreadLocal mainMethod = new ThreadLocal<>(); private Method actualMain; - @Before + @BeforeEach public void setup() throws Exception { this.actualMain = Valid.class.getMethod("main", String[].class); } @Test - public void threadMustNotBeNull() { + void threadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new MainMethod(null)) .withMessageContaining("Thread must not be null"); } @Test - public void validMainMethod() throws Exception { + void validMainMethod() throws Exception { MainMethod method = new TestThread(Valid::main).test(); assertThat(method.getMethod()).isEqualTo(this.actualMain); assertThat(method.getDeclaringClassName()).isEqualTo(this.actualMain.getDeclaringClass().getName()); } @Test - public void missingArgsMainMethod() throws Exception { + void missingArgsMainMethod() throws Exception { assertThatIllegalStateException().isThrownBy(() -> new TestThread(MissingArgs::main).test()) .withMessageContaining("Unable to find main method"); } @Test - public void nonStatic() throws Exception { + void nonStatic() throws Exception { assertThatIllegalStateException().isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) .withMessageContaining("Unable to find main method"); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java index 3c13fe9f19c..07f7193f37f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java @@ -20,9 +20,12 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; import org.springframework.beans.factory.ObjectFactory; @@ -36,33 +39,29 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class MockRestarter implements TestRule { +public class MockRestarter implements BeforeEachCallback, AfterEachCallback, ParameterResolver { private Map attributes = new HashMap<>(); private Restarter mock = mock(Restarter.class); - @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - - @Override - public void evaluate() throws Throwable { - setup(); - base.evaluate(); - cleanup(); - } - - }; + public Restarter getMock() { + return this.mock; } - @SuppressWarnings("rawtypes") - private void setup() { + @Override + public void afterEach(ExtensionContext context) throws Exception { + this.attributes.clear(); + Restarter.clearInstance(); + } + + @Override + public void beforeEach(ExtensionContext context) throws Exception { Restarter.setInstance(this.mock); given(this.mock.getInitialUrls()).willReturn(new URL[] {}); given(this.mock.getOrAddAttribute(anyString(), any(ObjectFactory.class))).willAnswer((invocation) -> { String name = invocation.getArgument(0); - ObjectFactory factory = invocation.getArgument(1); + ObjectFactory factory = invocation.getArgument(1); Object attribute = MockRestarter.this.attributes.get(name); if (attribute == null) { attribute = factory.getObject(); @@ -73,12 +72,15 @@ public class MockRestarter implements TestRule { given(this.mock.getThreadFactory()).willReturn(Thread::new); } - private void cleanup() { - this.attributes.clear(); - Restarter.clearInstance(); + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return parameterContext.getParameter().getType().equals(Restarter.class); } - public Restarter getMock() { + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { return this.mock; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java index b3884f61cbc..5a7fca44d25 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java @@ -18,9 +18,9 @@ package org.springframework.boot.devtools.restart; import java.net.URL; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -37,18 +37,18 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OnInitializedRestarterConditionTests { +class OnInitializedRestarterConditionTests { private static Object wait = new Object(); - @Before - @After + @BeforeEach + @AfterEach public void cleanup() { Restarter.clearInstance(); } @Test - public void noInstance() { + void noInstance() { Restarter.clearInstance(); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); @@ -56,7 +56,7 @@ public class OnInitializedRestarterConditionTests { } @Test - public void noInitialization() { + void noInitialization() { Restarter.initialize(new String[0], false, RestartInitializer.NONE); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); assertThat(context.containsBean("bean")).isFalse(); @@ -64,7 +64,7 @@ public class OnInitializedRestarterConditionTests { } @Test - public void initialized() throws Exception { + void initialized() throws Exception { Thread thread = new Thread(TestInitialized::main); thread.start(); synchronized (wait) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java index be36563c1cd..a4d4ae3f30f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java @@ -18,17 +18,18 @@ package org.springframework.boot.devtools.restart; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.ApplicationPreparedEvent; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.event.ApplicationStartingEvent; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.test.util.ReflectionTestUtils; @@ -43,29 +44,27 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class RestartApplicationListenerTests { +@ExtendWith(OutputCaptureExtension.class) +class RestartApplicationListenerTests { private static final String ENABLED_PROPERTY = "spring.devtools.restart.enabled"; private static final String[] ARGS = new String[] { "a", "b", "c" }; - @Rule - public final OutputCaptureRule output = new OutputCaptureRule(); - - @Before - @After + @BeforeEach + @AfterEach public void cleanup() { Restarter.clearInstance(); System.clearProperty(ENABLED_PROPERTY); } @Test - public void isHighestPriority() { + void isHighestPriority() { assertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test - public void initializeWithReady() { + void initializeWithReady() { testInitialize(false); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); @@ -73,7 +72,7 @@ public class RestartApplicationListenerTests { } @Test - public void initializeWithFail() { + void initializeWithFail() { testInitialize(true); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("args", ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); @@ -81,11 +80,11 @@ public class RestartApplicationListenerTests { } @Test - public void disableWithSystemProperty() { + void disableWithSystemProperty(CapturedOutput capturedOutput) { System.setProperty(ENABLED_PROPERTY, "false"); testInitialize(false); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false); - assertThat(this.output.toString()).contains("Restart disabled due to System property"); + assertThat(capturedOutput).contains("Restart disabled due to System property"); } private void testInitialize(boolean failed) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java index ac967a63871..104551f795c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.devtools.restart; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -35,14 +35,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class RestartScopeInitializerTests { +class RestartScopeInitializerTests { private static AtomicInteger createCount; private static AtomicInteger refreshCount; @Test - public void restartScope() { + void restartScope() { createCount = new AtomicInteger(); refreshCount = new AtomicInteger(); ConfigurableApplicationContext context = runApplication(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index e29f890a911..b29a3d91e39 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -22,16 +22,17 @@ import java.util.Collection; import java.util.Collections; import java.util.concurrent.ThreadFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.event.ContextClosedEvent; @@ -54,35 +55,33 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Phillip Webb * @author Andy Wilkinson */ -public class RestarterTests { +@ExtendWith(OutputCaptureExtension.class) +class RestarterTests { - @Rule - public OutputCaptureRule out = new OutputCaptureRule(); - - @Before + @BeforeEach public void setup() { RestarterInitializer.setRestarterInstance(); } - @After + @AfterEach public void cleanup() { Restarter.clearInstance(); } @Test - public void cantGetInstanceBeforeInitialize() { + void cantGetInstanceBeforeInitialize() { Restarter.clearInstance(); assertThatIllegalStateException().isThrownBy(Restarter::getInstance) .withMessageContaining("Restarter has not been initialized"); } @Test - public void testRestart() throws Exception { + void testRestart(CapturedOutput capturedOutput) throws Exception { Restarter.clearInstance(); Thread thread = new Thread(SampleApplication::main); thread.start(); Thread.sleep(2600); - String output = this.out.toString(); + String output = capturedOutput.toString(); assertThat(StringUtils.countOccurrencesOf(output, "Tick 0")).isGreaterThan(1); assertThat(StringUtils.countOccurrencesOf(output, "Tick 1")).isGreaterThan(1); assertThat(CloseCountingApplicationListener.closed).isGreaterThan(0); @@ -90,7 +89,7 @@ public class RestarterTests { @Test @SuppressWarnings("rawtypes") - public void getOrAddAttributeWithNewAttribute() { + void getOrAddAttributeWithNewAttribute() { ObjectFactory objectFactory = mock(ObjectFactory.class); given(objectFactory.getObject()).willReturn("abc"); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); @@ -98,13 +97,13 @@ public class RestarterTests { } @Test - public void addUrlsMustNotBeNull() { + void addUrlsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null)) .withMessageContaining("Urls must not be null"); } @Test - public void addUrls() throws Exception { + void addUrls() throws Exception { URL url = new URL("file:/proj/module-a.jar!/"); Collection urls = Collections.singleton(url); Restarter restarter = Restarter.getInstance(); @@ -115,13 +114,13 @@ public class RestarterTests { } @Test - public void addClassLoaderFilesMustNotBeNull() { + void addClassLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) .withMessageContaining("ClassLoaderFiles must not be null"); } @Test - public void addClassLoaderFiles() { + void addClassLoaderFiles() { ClassLoaderFiles classLoaderFiles = new ClassLoaderFiles(); classLoaderFiles.addFile("f", new ClassLoaderFile(Kind.ADDED, "abc".getBytes())); Restarter restarter = Restarter.getInstance(); @@ -133,7 +132,7 @@ public class RestarterTests { @Test @SuppressWarnings("rawtypes") - public void getOrAddAttributeWithExistingAttribute() { + void getOrAddAttributeWithExistingAttribute() { Restarter.getInstance().getOrAddAttribute("x", () -> "abc"); ObjectFactory objectFactory = mock(ObjectFactory.class); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); @@ -142,7 +141,7 @@ public class RestarterTests { } @Test - public void getThreadFactory() throws Exception { + void getThreadFactory() throws Exception { final ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); final ClassLoader contextClassLoader = new URLClassLoader(new URL[0]); Thread thread = new Thread(() -> { @@ -161,7 +160,7 @@ public class RestarterTests { } @Test - public void getInitialUrls() throws Exception { + void getInitialUrls() throws Exception { Restarter.clearInstance(); RestartInitializer initializer = mock(RestartInitializer.class); URL[] urls = new URL[] { new URL("file:/proj/module-a.jar!/") }; diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java index 75cae415fff..bbf0d1d11d5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java @@ -18,10 +18,10 @@ package org.springframework.boot.devtools.restart; import java.util.concurrent.CountDownLatch; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link SilentExitExceptionHandler}. @@ -29,10 +29,10 @@ import static org.junit.Assert.fail; * @author Phillip Webb * @author Andy Wilkinson */ -public class SilentExitExceptionHandlerTests { +class SilentExitExceptionHandlerTests { @Test - public void setupAndExit() throws Exception { + void setupAndExit() throws Exception { TestThread testThread = new TestThread() { @Override public void run() { @@ -46,7 +46,7 @@ public class SilentExitExceptionHandlerTests { } @Test - public void doesntInterfereWithOtherExceptions() throws Exception { + void doesntInterfereWithOtherExceptions() throws Exception { TestThread testThread = new TestThread() { @Override public void run() { @@ -59,7 +59,7 @@ public class SilentExitExceptionHandlerTests { } @Test - public void preventsNonZeroExitCodeWhenAllOtherThreadsAreDaemonThreads() { + void preventsNonZeroExitCodeWhenAllOtherThreadsAreDaemonThreads() { try { SilentExitExceptionHandler.exitCurrentThread(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 92efe43758d..982c6318df6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.restart.classloader; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; @@ -28,50 +28,50 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ClassLoaderFileTests { +class ClassLoaderFileTests { public static final byte[] BYTES = "ABC".getBytes(); @Test - public void kindMustNotBeNull() { + void kindMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null)) .withMessageContaining("Kind must not be null"); } @Test - public void addedContentsMustNotBeNull() { + void addedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) .withMessageContaining("Contents must not be null"); } @Test - public void modifiedContentsMustNotBeNull() { + void modifiedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) .withMessageContaining("Contents must not be null"); } @Test - public void deletedContentsMustBeNull() { + void deletedContentsMustBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) .withMessageContaining("Contents must be null"); } @Test - public void added() { + void added() { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, BYTES); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.ADDED); assertThat(file.getContents()).isEqualTo(BYTES); } @Test - public void modified() { + void modified() { ClassLoaderFile file = new ClassLoaderFile(Kind.MODIFIED, BYTES); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.MODIFIED); assertThat(file.getContents()).isEqualTo(BYTES); } @Test - public void deleted() { + void deleted() { ClassLoaderFile file = new ClassLoaderFile(Kind.DELETED, null); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.DELETED); assertThat(file.getContents()).isNull(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index 41f36677645..532201fe345 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -22,7 +22,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles.SourceFolder; @@ -36,41 +36,41 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ClassLoaderFilesTests { +class ClassLoaderFilesTests { private ClassLoaderFiles files = new ClassLoaderFiles(); @Test - public void addFileNameMustNotBeNull() { + void addFileNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) .withMessageContaining("Name must not be null"); } @Test - public void addFileFileMustNotBeNull() { + void addFileFileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile("test", null)) .withMessageContaining("File must not be null"); } @Test - public void getFileWithNullName() { + void getFileWithNullName() { assertThat(this.files.getFile(null)).isNull(); } @Test - public void addAndGet() { + void addAndGet() { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, new byte[10]); this.files.addFile("myfile", file); assertThat(this.files.getFile("myfile")).isEqualTo(file); } @Test - public void getMissing() { + void getMissing() { assertThat(this.files.getFile("missing")).isNull(); } @Test - public void addTwice() { + void addTwice() { ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]); ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); this.files.addFile("myfile", file1); @@ -79,7 +79,7 @@ public class ClassLoaderFilesTests { } @Test - public void addTwiceInDifferentSourceFolders() { + void addTwiceInDifferentSourceFolders() { ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]); ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); this.files.addFile("a", "myfile", file1); @@ -90,7 +90,7 @@ public class ClassLoaderFilesTests { } @Test - public void getSourceFolders() { + void getSourceFolders() { ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]); ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); ClassLoaderFile file3 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); @@ -110,7 +110,7 @@ public class ClassLoaderFilesTests { } @Test - public void serialize() throws Exception { + void serialize() throws Exception { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, new byte[10]); this.files.addFile("myfile", file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -123,7 +123,7 @@ public class ClassLoaderFilesTests { } @Test - public void addAll() { + void addAll() { ClassLoaderFile file1 = new ClassLoaderFile(Kind.ADDED, new byte[10]); this.files.addFile("a", "myfile1", file1); ClassLoaderFiles toAdd = new ClassLoaderFiles(); @@ -142,7 +142,7 @@ public class ClassLoaderFilesTests { } @Test - public void getSize() { + void getSize() { this.files.addFile("s1", "n1", mock(ClassLoaderFile.class)); this.files.addFile("s1", "n2", mock(ClassLoaderFile.class)); this.files.addFile("s2", "n3", mock(ClassLoaderFile.class)); @@ -151,13 +151,13 @@ public class ClassLoaderFilesTests { } @Test - public void classLoaderFilesMustNotBeNull() { + void classLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFiles(null)) .withMessageContaining("ClassLoaderFiles must not be null"); } @Test - public void constructFromExistingSet() { + void constructFromExistingSet() { this.files.addFile("s1", "n1", mock(ClassLoaderFile.class)); this.files.addFile("s1", "n2", mock(ClassLoaderFile.class)); ClassLoaderFiles copy = new ClassLoaderFiles(this.files); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 4adb545d2e2..3cb76b87d4f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -29,10 +29,9 @@ import java.util.List; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import org.springframework.util.FileCopyUtils; @@ -48,15 +47,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb */ @SuppressWarnings("resource") -public class RestartClassLoaderTests { +class RestartClassLoaderTests { private static final String PACKAGE = RestartClassLoaderTests.class.getPackage().getName(); private static final String PACKAGE_PATH = PACKAGE.replace('.', '/'); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - private File sampleJarFile; private URLClassLoader parentClassLoader; @@ -65,9 +61,9 @@ public class RestartClassLoaderTests { private RestartClassLoader reloadClassLoader; - @Before - public void setup() throws Exception { - this.sampleJarFile = createSampleJarFile(); + @BeforeEach + public void setup(@TempDir File tempDir) throws Exception { + this.sampleJarFile = createSampleJarFile(tempDir); URL url = this.sampleJarFile.toURI().toURL(); ClassLoader classLoader = getClass().getClassLoader(); URL[] urls = new URL[] { url }; @@ -76,8 +72,8 @@ public class RestartClassLoaderTests { this.reloadClassLoader = new RestartClassLoader(this.parentClassLoader, urls, this.updatedFiles); } - private File createSampleJarFile() throws IOException { - File file = this.temp.newFile("sample.jar"); + private File createSampleJarFile(File tempDir) throws IOException { + File file = new File(tempDir, "sample.jar"); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file)); jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.class")); StreamUtils.copy(getClass().getResourceAsStream("Sample.class"), jarOutputStream); @@ -90,64 +86,64 @@ public class RestartClassLoaderTests { } @Test - public void parentMustNotBeNull() { + void parentMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) .withMessageContaining("Parent must not be null"); } @Test - public void updatedFilesMustNotBeNull() { + void updatedFilesMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) .withMessageContaining("UpdatedFiles must not be null"); } @Test - public void getResourceFromReloadableUrl() throws Exception { + void getResourceFromReloadableUrl() throws Exception { String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); assertThat(content).startsWith("fromchild"); } @Test - public void getResourceFromParent() throws Exception { + void getResourceFromParent() throws Exception { String content = readString(this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); assertThat(content).startsWith("fromparent"); } @Test - public void getResourcesFiltersDuplicates() throws Exception { + void getResourcesFiltersDuplicates() throws Exception { List resources = toList(this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); assertThat(resources.size()).isEqualTo(1); } @Test - public void loadClassFromReloadableUrl() throws Exception { + void loadClassFromReloadableUrl() throws Exception { Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".Sample"); assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); } @Test - public void loadClassFromParent() throws Exception { + void loadClassFromParent() throws Exception { Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); assertThat(loaded.getClassLoader()).isEqualTo(getClass().getClassLoader()); } @Test - public void getDeletedResource() { + void getDeletedResource() { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); assertThat(this.reloadClassLoader.getResource(name)).isNull(); } @Test - public void getDeletedResourceAsStream() { + void getDeletedResourceAsStream() { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); assertThat(this.reloadClassLoader.getResourceAsStream(name)).isNull(); } @Test - public void getUpdatedResource() throws Exception { + void getUpdatedResource() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); @@ -156,7 +152,7 @@ public class RestartClassLoaderTests { } @Test - public void getResourcesWithDeleted() throws Exception { + void getResourcesWithDeleted() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); List resources = toList(this.reloadClassLoader.getResources(name)); @@ -164,7 +160,7 @@ public class RestartClassLoaderTests { } @Test - public void getResourcesWithUpdated() throws Exception { + void getResourcesWithUpdated() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); @@ -173,7 +169,7 @@ public class RestartClassLoaderTests { } @Test - public void getDeletedClass() throws Exception { + void getDeletedClass() throws Exception { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); assertThatExceptionOfType(ClassNotFoundException.class) @@ -181,7 +177,7 @@ public class RestartClassLoaderTests { } @Test - public void getUpdatedClass() throws Exception { + void getUpdatedClass() throws Exception { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, new byte[10])); assertThatExceptionOfType(ClassFormatError.class) @@ -189,7 +185,7 @@ public class RestartClassLoaderTests { } @Test - public void getAddedClass() throws Exception { + void getAddedClass() throws Exception { String name = PACKAGE_PATH + "/SampleParent.class"; byte[] bytes = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes)); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java index b22001a2a3f..48d2565ecd2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java @@ -22,7 +22,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class DefaultSourceFolderUrlFilterTests { +class DefaultSourceFolderUrlFilterTests { private static final String SOURCE_ROOT = "/Users/me/code/some-root/"; @@ -55,22 +55,22 @@ public class DefaultSourceFolderUrlFilterTests { private DefaultSourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter(); @Test - public void mavenSourceFolder() throws Exception { + void mavenSourceFolder() throws Exception { doTest("my-module/target/classes/"); } @Test - public void gradleEclipseSourceFolder() throws Exception { + void gradleEclipseSourceFolder() throws Exception { doTest("my-module/bin/"); } @Test - public void unusualSourceFolder() throws Exception { + void unusualSourceFolder() throws Exception { doTest("my-module/something/quite/quite/mad/"); } @Test - public void skippedProjects() throws Exception { + void skippedProjects() throws Exception { String sourceFolder = "/Users/me/code/spring-boot-samples/" + "spring-boot-sample-devtools"; URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java index af490979a1b..6bb4fbd0a7b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.restart.server; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; @@ -30,16 +30,16 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class HttpRestartServerHandlerTests { +class HttpRestartServerHandlerTests { @Test - public void serverMustNotBeNull() { + void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServerHandler(null)) .withMessageContaining("Server must not be null"); } @Test - public void handleDelegatesToServer() throws Exception { + void handleDelegatesToServer() throws Exception { HttpRestartServer server = mock(HttpRestartServer.class); HttpRestartServerHandler handler = new HttpRestartServerHandler(server); ServerHttpRequest request = mock(ServerHttpRequest.class); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 52988b8d60e..c72cbb94df1 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -20,8 +20,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -45,7 +45,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class HttpRestartServerTests { +class HttpRestartServerTests { @Mock private RestartServer delegate; @@ -55,26 +55,26 @@ public class HttpRestartServerTests { @Captor private ArgumentCaptor filesCaptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.server = new HttpRestartServer(this.delegate); } @Test - public void sourceFolderUrlFilterMustNotBeNull() { + void sourceFolderUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((SourceFolderUrlFilter) null)) .withMessageContaining("SourceFolderUrlFilter must not be null"); } @Test - public void restartServerMustNotBeNull() { + void restartServerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((RestartServer) null)) .withMessageContaining("RestartServer must not be null"); } @Test - public void sendClassLoaderFiles() throws Exception { + void sendClassLoaderFiles() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ClassLoaderFiles files = new ClassLoaderFiles(); @@ -88,7 +88,7 @@ public class HttpRestartServerTests { } @Test - public void sendNoContent() throws Exception { + void sendNoContent() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); @@ -98,7 +98,7 @@ public class HttpRestartServerTests { } @Test - public void sendBadData() throws Exception { + void sendBadData() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(new byte[] { 0, 0, 0 }); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index c53ffd1aea8..956cd517f9d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -24,9 +24,8 @@ import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; @@ -41,19 +40,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class RestartServerTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class RestartServerTests { @Test - public void sourceFolderUrlFilterMustNotBeNull() { + void sourceFolderUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null)) .withMessageContaining("SourceFolderUrlFilter must not be null"); } @Test - public void updateAndRestart() throws Exception { + void updateAndRestart() throws Exception { URL url1 = new URL("file:/proj/module-a.jar!/"); URL url2 = new URL("file:/proj/module-b.jar!/"); URL url3 = new URL("file:/proj/module-c.jar!/"); @@ -74,9 +70,8 @@ public class RestartServerTests { } @Test - public void updateSetsJarLastModified() throws Exception { + void updateSetsJarLastModified(@TempDir File folder) throws Exception { long startTime = System.currentTimeMillis(); - File folder = this.temp.newFolder(); File jarFile = new File(folder, "module-a.jar"); new FileOutputStream(jarFile).close(); jarFile.setLastModified(0); @@ -92,11 +87,10 @@ public class RestartServerTests { } @Test - public void updateReplacesLocalFilesWhenPossible() throws Exception { + void updateReplacesLocalFilesWhenPossible(@TempDir File folder) throws Exception { // This is critical for Cloud Foundry support where the application is // run exploded and resources can be found from the servlet root (outside of the // classloader) - File folder = this.temp.newFolder(); File classFile = new File(folder, "ClassA.class"); FileCopyUtils.copy("abc".getBytes(), classFile); URL url = folder.toURI().toURL(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java index d9840ab3786..590536d4c82 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java @@ -20,9 +20,8 @@ import java.io.File; import java.io.IOException; import java.net.URL; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +30,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class DevToolsSettingsTests { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); +class DevToolsSettingsTests { private static final String ROOT = DevToolsSettingsTests.class.getPackage().getName().replace('.', '/') + "/"; @Test - public void includePatterns() throws Exception { + void includePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-include.properties"); assertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue(); @@ -47,7 +43,7 @@ public class DevToolsSettingsTests { } @Test - public void excludePatterns() throws Exception { + void excludePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings.load(ROOT + "spring-devtools-exclude.properties"); assertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue(); assertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue(); @@ -55,17 +51,16 @@ public class DevToolsSettingsTests { } @Test - public void defaultIncludePatterns() throws Exception { + void defaultIncludePatterns(@TempDir File tempDir) throws Exception { DevToolsSettings settings = DevToolsSettings.get(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue(); - assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-autoconfigure"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-actuator"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-starter"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl(tempDir, "spring-boot-starter-some-thing"))).isTrue(); } - private URL makeUrl(String name) throws IOException { - File file = this.temporaryFolder.newFolder(); + private URL makeUrl(File file, String name) throws IOException { file = new File(file, name); file = new File(file, "target"); file = new File(file, "classes"); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index d045629df29..89bd6bdec66 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -25,20 +25,20 @@ import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.concurrent.Executor; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.devtools.test.MockClientHttpRequestFactory; import org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection.TunnelChannel; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpStatus; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -50,10 +50,8 @@ import static org.mockito.Mockito.verify; * @author Rob Winch * @author Andy Wilkinson */ -public class HttpTunnelConnectionTests { - - @Rule - public OutputCaptureRule outputCapture = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class HttpTunnelConnectionTests { private String url; @@ -66,7 +64,7 @@ public class HttpTunnelConnectionTests { private MockClientHttpRequestFactory requestFactory = new MockClientHttpRequestFactory(); - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.url = "http://localhost:12345"; @@ -75,32 +73,32 @@ public class HttpTunnelConnectionTests { } @Test - public void urlMustNotBeNull() { + void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test - public void urlMustNotBeEmpty() { + void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) .withMessageContaining("URL must not be empty"); } @Test - public void urlMustNotBeMalformed() { + void urlMustNotBeMalformed() { assertThatIllegalArgumentException() .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test - public void requestFactoryMustNotBeNull() { + void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(this.url, null)) .withMessageContaining("RequestFactory must not be null"); } @Test - public void closeTunnelChangesIsOpen() throws Exception { + void closeTunnelChangesIsOpen() throws Exception { this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE); WritableByteChannel channel = openTunnel(false); assertThat(channel.isOpen()).isTrue(); @@ -109,7 +107,7 @@ public class HttpTunnelConnectionTests { } @Test - public void closeTunnelCallsCloseableOnce() throws Exception { + void closeTunnelCallsCloseableOnce() throws Exception { this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE); WritableByteChannel channel = openTunnel(false); verify(this.closeable, never()).close(); @@ -119,7 +117,7 @@ public class HttpTunnelConnectionTests { } @Test - public void typicalTraffic() throws Exception { + void typicalTraffic() throws Exception { this.requestFactory.willRespond("hi", "=2", "=3"); TunnelChannel channel = openTunnel(true); write(channel, "hello"); @@ -129,7 +127,7 @@ public class HttpTunnelConnectionTests { } @Test - public void trafficWithLongPollTimeouts() throws Exception { + void trafficWithLongPollTimeouts() throws Exception { for (int i = 0; i < 10; i++) { this.requestFactory.willRespond(HttpStatus.NO_CONTENT); } @@ -141,11 +139,11 @@ public class HttpTunnelConnectionTests { } @Test - public void connectFailureLogsWarning() throws Exception { + void connectFailureLogsWarning(CapturedOutput capturedOutput) throws Exception { this.requestFactory.willRespond(new ConnectException()); TunnelChannel tunnel = openTunnel(true); assertThat(tunnel.isOpen()).isFalse(); - this.outputCapture.expect(containsString("Failed to connect to remote application at http://localhost:12345")); + assertThat(capturedOutput).contains("Failed to connect to remote application at http://localhost:12345"); } private void write(TunnelChannel channel, String string) throws IOException { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index d953df5d14c..7b5212abbcf 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -25,7 +25,7 @@ import java.nio.channels.Channels; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -38,24 +38,24 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class TunnelClientTests { +class TunnelClientTests { private MockTunnelConnection tunnelConnection = new MockTunnelConnection(); @Test - public void listenPortMustNotBeNegative() { + void listenPortMustNotBeNegative() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) .withMessageContaining("ListenPort must be greater than or equal to 0"); } @Test - public void tunnelConnectionMustNotBeNull() { + void tunnelConnectionMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(1, null)) .withMessageContaining("TunnelConnection must not be null"); } @Test - public void typicalTraffic() throws Exception { + void typicalTraffic() throws Exception { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); @@ -68,7 +68,7 @@ public class TunnelClientTests { } @Test - public void socketChannelClosedTriggersTunnelClose() throws Exception { + void socketChannelClosedTriggersTunnelClose() throws Exception { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); @@ -81,7 +81,7 @@ public class TunnelClientTests { } @Test - public void stopTriggersTunnelClose() throws Exception { + void stopTriggersTunnelClose() throws Exception { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); @@ -93,7 +93,7 @@ public class TunnelClientTests { } @Test - public void addListener() throws Exception { + void addListener() throws Exception { TunnelClient client = new TunnelClient(0, this.tunnelConnection); TunnelClientListener listener = mock(TunnelClientListener.class); client.addListener(listener); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index 3b104b08bca..7217e0f898d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -21,7 +21,7 @@ import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -32,16 +32,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class HttpTunnelPayloadForwarderTests { +class HttpTunnelPayloadForwarderTests { @Test - public void targetChannelMustNotBeNull() { + void targetChannelMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) .withMessageContaining("TargetChannel must not be null"); } @Test - public void forwardInSequence() throws Exception { + void forwardInSequence() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(out); HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel); @@ -52,7 +52,7 @@ public class HttpTunnelPayloadForwarderTests { } @Test - public void forwardOutOfSequence() throws Exception { + void forwardOutOfSequence() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(out); HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel); @@ -63,7 +63,7 @@ public class HttpTunnelPayloadForwarderTests { } @Test - public void overflow() throws Exception { + void overflow() throws Exception { WritableByteChannel channel = Channels.newChannel(new ByteArrayOutputStream()); HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel); assertThatIllegalStateException().isThrownBy(() -> { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index 436f9f970e5..3ffb025e3f6 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -25,7 +25,7 @@ import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; @@ -46,35 +46,35 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class HttpTunnelPayloadTests { +class HttpTunnelPayloadTests { @Test - public void sequenceMustBePositive() { + void sequenceMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) .withMessageContaining("Sequence must be positive"); } @Test - public void dataMustNotBeNull() { + void dataMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(1, null)) .withMessageContaining("Data must not be null"); } @Test - public void getSequence() { + void getSequence() { HttpTunnelPayload payload = new HttpTunnelPayload(1, ByteBuffer.allocate(1)); assertThat(payload.getSequence()).isEqualTo(1L); } @Test - public void getData() throws Exception { + void getData() throws Exception { ByteBuffer data = ByteBuffer.wrap("hello".getBytes()); HttpTunnelPayload payload = new HttpTunnelPayload(1, data); assertThat(getData(payload)).isEqualTo(data.array()); } @Test - public void assignTo() throws Exception { + void assignTo() throws Exception { ByteBuffer data = ByteBuffer.wrap("hello".getBytes()); HttpTunnelPayload payload = new HttpTunnelPayload(2, data); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); @@ -85,7 +85,7 @@ public class HttpTunnelPayloadTests { } @Test - public void getNoData() throws Exception { + void getNoData() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); HttpTunnelPayload payload = HttpTunnelPayload.get(request); @@ -93,7 +93,7 @@ public class HttpTunnelPayloadTests { } @Test - public void getWithMissingHeader() throws Exception { + void getWithMissingHeader() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.setContent("hello".getBytes()); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); @@ -102,7 +102,7 @@ public class HttpTunnelPayloadTests { } @Test - public void getWithData() throws Exception { + void getWithData() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.setContent("hello".getBytes()); servletRequest.addHeader("x-seq", 123); @@ -113,7 +113,7 @@ public class HttpTunnelPayloadTests { } @Test - public void getPayloadData() throws Exception { + void getPayloadData() throws Exception { ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream("hello".getBytes())); ByteBuffer payloadData = HttpTunnelPayload.getPayloadData(channel); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -125,7 +125,7 @@ public class HttpTunnelPayloadTests { } @Test - public void getPayloadDataWithTimeout() throws Exception { + void getPayloadDataWithTimeout() throws Exception { ReadableByteChannel channel = mock(ReadableByteChannel.class); given(channel.read(any(ByteBuffer.class))).willThrow(new SocketTimeoutException()); ByteBuffer payload = HttpTunnelPayload.getPayloadData(channel); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java index fba704a402f..c2c0a0ae716 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.tunnel.server; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; @@ -30,16 +30,16 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class HttpTunnelServerHandlerTests { +class HttpTunnelServerHandlerTests { @Test - public void serverMustNotBeNull() { + void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServerHandler(null)) .withMessageContaining("Server must not be null"); } @Test - public void handleDelegatesToServer() throws Exception { + void handleDelegatesToServer() throws Exception { HttpTunnelServer server = mock(HttpTunnelServer.class); HttpTunnelServerHandler handler = new HttpTunnelServerHandler(server); ServerHttpRequest request = mock(ServerHttpRequest.class); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index f7ee4d6cb48..941944230bd 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -27,8 +27,8 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -57,7 +57,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class HttpTunnelServerTests { +class HttpTunnelServerTests { private static final int DEFAULT_LONG_POLL_TIMEOUT = 10000; @@ -80,7 +80,7 @@ public class HttpTunnelServerTests { private MockServerChannel serverChannel; - @Before + @BeforeEach public void setup() throws Exception { MockitoAnnotations.initMocks(this); this.server = new HttpTunnelServer(this.serverConnection); @@ -98,33 +98,33 @@ public class HttpTunnelServerTests { } @Test - public void serverConnectionIsRequired() { + void serverConnectionIsRequired() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null)) .withMessageContaining("ServerConnection must not be null"); } @Test - public void serverConnectedOnFirstRequest() throws Exception { + void serverConnectedOnFirstRequest() throws Exception { verify(this.serverConnection, never()).open(anyInt()); this.server.handle(this.request, this.response); verify(this.serverConnection, times(1)).open(DEFAULT_LONG_POLL_TIMEOUT); } @Test - public void longPollTimeout() throws Exception { + void longPollTimeout() throws Exception { this.server.setLongPollTimeout(800); this.server.handle(this.request, this.response); verify(this.serverConnection, times(1)).open(800); } @Test - public void longPollTimeoutMustBePositiveValue() { + void longPollTimeoutMustBePositiveValue() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0)) .withMessageContaining("LongPollTimeout must be a positive value"); } @Test - public void initialRequestIsSentToServer() throws Exception { + void initialRequestIsSentToServer() throws Exception { this.servletRequest.addHeader(SEQ_HEADER, "1"); this.servletRequest.setContent("hello".getBytes()); this.server.handle(this.request, this.response); @@ -134,7 +134,7 @@ public class HttpTunnelServerTests { } @Test - public void initialRequestIsUsedForFirstServerResponse() throws Exception { + void initialRequestIsUsedForFirstServerResponse() throws Exception { this.servletRequest.addHeader(SEQ_HEADER, "1"); this.servletRequest.setContent("hello".getBytes()); this.server.handle(this.request, this.response); @@ -147,7 +147,7 @@ public class HttpTunnelServerTests { } @Test - public void initialRequestHasNoPayload() throws Exception { + void initialRequestHasNoPayload() throws Exception { this.server.handle(this.request, this.response); this.serverChannel.disconnect(); this.server.getServerThread().join(); @@ -155,7 +155,7 @@ public class HttpTunnelServerTests { } @Test - public void typicalRequestResponseTraffic() throws Exception { + void typicalRequestResponseTraffic() throws Exception { MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("hello server", 1); @@ -176,7 +176,7 @@ public class HttpTunnelServerTests { } @Test - public void clientIsAwareOfServerClose() throws Exception { + void clientIsAwareOfServerClose() throws Exception { MockHttpConnection h1 = new MockHttpConnection("1", 1); this.server.handle(h1); this.serverChannel.disconnect(); @@ -185,7 +185,7 @@ public class HttpTunnelServerTests { } @Test - public void clientCanCloseServer() throws Exception { + void clientCanCloseServer() throws Exception { MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("DISCONNECT", 1); @@ -197,7 +197,7 @@ public class HttpTunnelServerTests { } @Test - public void neverMoreThanTwoHttpConnections() throws Exception { + void neverMoreThanTwoHttpConnections() throws Exception { MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("1", 2); @@ -211,7 +211,7 @@ public class HttpTunnelServerTests { } @Test - public void requestReceivedOutOfOrder() throws Exception { + void requestReceivedOutOfOrder() throws Exception { MockHttpConnection h1 = new MockHttpConnection(); MockHttpConnection h2 = new MockHttpConnection("1+2", 1); MockHttpConnection h3 = new MockHttpConnection("+3", 2); @@ -224,7 +224,7 @@ public class HttpTunnelServerTests { } @Test - public void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception { + void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception { this.server.setDisconnectTimeout(1000); this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); @@ -239,7 +239,7 @@ public class HttpTunnelServerTests { } @Test - public void disconnectTimeout() throws Exception { + void disconnectTimeout() throws Exception { this.server.setDisconnectTimeout(100); this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); @@ -250,13 +250,13 @@ public class HttpTunnelServerTests { } @Test - public void disconnectTimeoutMustBePositive() { + void disconnectTimeoutMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0)) .withMessageContaining("DisconnectTimeout must be a positive value"); } @Test - public void httpConnectionRespondWithPayload() throws Exception { + void httpConnectionRespondWithPayload() throws Exception { HttpConnection connection = new HttpConnection(this.request, this.response); connection.waitForResponse(); connection.respond(new HttpTunnelPayload(1, ByteBuffer.wrap("hello".getBytes()))); @@ -266,7 +266,7 @@ public class HttpTunnelServerTests { } @Test - public void httpConnectionRespondWithStatus() throws Exception { + void httpConnectionRespondWithStatus() throws Exception { HttpConnection connection = new HttpConnection(this.request, this.response); connection.waitForResponse(); connection.respond(HttpStatus.I_AM_A_TEAPOT); @@ -275,7 +275,7 @@ public class HttpTunnelServerTests { } @Test - public void httpConnectionAsync() throws Exception { + void httpConnectionAsync() throws Exception { ServerHttpAsyncRequestControl async = mock(ServerHttpAsyncRequestControl.class); ServerHttpRequest request = mock(ServerHttpRequest.class); given(request.getAsyncRequestControl(this.response)).willReturn(async); @@ -287,7 +287,7 @@ public class HttpTunnelServerTests { } @Test - public void httpConnectionNonAsync() throws Exception { + void httpConnectionNonAsync() throws Exception { testHttpConnectionNonAsync(0); testHttpConnectionNonAsync(100); } @@ -310,7 +310,7 @@ public class HttpTunnelServerTests { } @Test - public void httpConnectionRunning() throws Exception { + void httpConnectionRunning() throws Exception { HttpConnection connection = new HttpConnection(this.request, this.response); assertThat(connection.isOlderThan(100)).isFalse(); Thread.sleep(200); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index 47c4eb0953d..2a5c3a04a13 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -24,8 +24,8 @@ import java.nio.channels.ByteChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -public class SocketTargetServerConnectionTests { +class SocketTargetServerConnectionTests { private static final int DEFAULT_TIMEOUT = 1000; @@ -43,14 +43,14 @@ public class SocketTargetServerConnectionTests { private SocketTargetServerConnection connection; - @Before + @BeforeEach public void setup() throws IOException { this.server = new MockServer(); this.connection = new SocketTargetServerConnection(() -> this.server.getPort()); } @Test - public void readData() throws Exception { + void readData() throws Exception { this.server.willSend("hello".getBytes()); this.server.start(); ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT); @@ -60,7 +60,7 @@ public class SocketTargetServerConnectionTests { } @Test - public void writeData() throws Exception { + void writeData() throws Exception { this.server.expect("hello".getBytes()); this.server.start(); ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT); @@ -70,7 +70,7 @@ public class SocketTargetServerConnectionTests { } @Test - public void timeout() throws Exception { + void timeout() throws Exception { this.server.delay(1000); this.server.start(); ByteChannel channel = this.connection.open(10); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java index 53f348b9506..55d4b81f416 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.devtools.tunnel.server; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -26,16 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class StaticPortProviderTests { +class StaticPortProviderTests { @Test - public void portMustBePositive() { + void portMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticPortProvider(0)) .withMessageContaining("Port must be positive"); } @Test - public void getPort() { + void getPort() { StaticPortProvider provider = new StaticPortProvider(123); assertThat(provider.getPort()).isEqualTo(123); } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java index 8bd79db7d25..69863817fad 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/restassured/UserDocumentationTests.java @@ -18,21 +18,21 @@ package org.springframework.boot.docs.test.autoconfigure.restdocs.restassured; // tag::source[] import io.restassured.specification.RequestSpecification; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.is; import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureRestDocs public class UserDocumentationTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java index eed131ae4d0..27e97f8c6a7 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/autoconfigure/restdocs/webclient/UsersDocumentationTests.java @@ -18,17 +18,17 @@ package org.springframework.boot.docs.test.autoconfigure.restdocs.webclient; // tag::source[] import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @WebFluxTest @AutoConfigureRestDocs public class UsersDocumentationTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/context/ApplicationArgumentsExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/context/ApplicationArgumentsExampleTests.java index 9a1acdd6270..dc6affc73e2 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/context/ApplicationArgumentsExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/context/ApplicationArgumentsExampleTests.java @@ -16,18 +16,18 @@ package org.springframework.boot.docs.test.context; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; // tag::example[] -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(args = "--app.test=one") public class ApplicationArgumentsExampleTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java index c5eb5333e7f..99083589dc8 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockMvcExampleTests.java @@ -18,20 +18,20 @@ package org.springframework.boot.docs.test.web; // tag::test-mock-mvc[] -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc public class MockMvcExampleTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java index 52c21abf449..d743de3c46c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/MockWebTestClientExampleTests.java @@ -18,16 +18,16 @@ package org.springframework.boot.docs.test.web; // tag::test-mock-web-test-client[] -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureWebTestClient public class MockWebTestClientExampleTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortTestRestTemplateExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortTestRestTemplateExampleTests.java index dd415bf994d..57d0ae195ac 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortTestRestTemplateExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortTestRestTemplateExampleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,19 @@ package org.springframework.boot.docs.test.web; // tag::test-random-port[] -import org.junit.Test; -import org.junit.runner.RunWith; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortTestRestTemplateExampleTests { diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java index f24b46815ef..0427087a3a0 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/test/web/RandomPortWebTestClientExampleTests.java @@ -18,16 +18,16 @@ package org.springframework.boot.docs.test.web; // tag::test-random-port[] -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortWebTestClientExampleTests { diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java index f56982b2d4a..0cbf982be38 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/autoconfigure/UserServiceAutoConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.docs.autoconfigure; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class UserServiceAutoConfigurationTests { +class UserServiceAutoConfigurationTests { // tag::runner[] private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() @@ -41,7 +41,7 @@ public class UserServiceAutoConfigurationTests { // tag::test-env[] @Test - public void serviceNameCanBeConfigured() { + void serviceNameCanBeConfigured() { this.contextRunner.withPropertyValues("user.name=test123").run((context) -> { assertThat(context).hasSingleBean(UserService.class); assertThat(context.getBean(UserService.class).getName()).isEqualTo("test123"); @@ -51,7 +51,7 @@ public class UserServiceAutoConfigurationTests { // tag::test-classloader[] @Test - public void serviceIsIgnoredIfLibraryIsNotPresent() { + void serviceIsIgnoredIfLibraryIsNotPresent() { this.contextRunner.withClassLoader(new FilteredClassLoader(UserService.class)) .run((context) -> assertThat(context).doesNotHaveBean("userService")); } @@ -59,7 +59,7 @@ public class UserServiceAutoConfigurationTests { // tag::test-user-config[] @Test - public void defaultServiceBacksOff() { + void defaultServiceBacksOff() { this.contextRunner.withUserConfiguration(UserConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(UserService.class); assertThat(context).getBean("myUserService").isSameAs(context.getBean(UserService.class)); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/builder/SpringApplicationBuilderExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/builder/SpringApplicationBuilderExampleTests.java index 0002a7ad745..83369cc6e02 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/builder/SpringApplicationBuilderExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/builder/SpringApplicationBuilderExampleTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.docs.builder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.test.system.OutputCaptureRule; -import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -31,17 +29,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions("spring-web-*.jar") -public class SpringApplicationBuilderExampleTests { - - @Rule - public OutputCaptureRule outputCapture = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class SpringApplicationBuilderExampleTests { @Test - public void contextHierarchyWithDisabledBanner() { - new SpringApplicationBuilderExample().hierarchyWithDisabledBanner(new String[0]); - assertThat(this.outputCapture.toString()).doesNotContain(":: Spring Boot ::"); + void contextHierarchyWithDisabledBanner(CapturedOutput capturedOutput) { + System.setProperty("spring.main.web-application-type", "none"); + try { + new SpringApplicationBuilderExample().hierarchyWithDisabledBanner(new String[0]); + assertThat(capturedOutput).doesNotContain(":: Spring Boot ::"); + } + finally { + System.clearProperty("spring.main.web-application-type"); + } } } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java index f948ce9d947..2dc4ff7f6f7 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/EnvironmentPostProcessorExampleTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.docs.context; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.core.env.StandardEnvironment; @@ -28,12 +28,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class EnvironmentPostProcessorExampleTests { +class EnvironmentPostProcessorExampleTests { private final StandardEnvironment environment = new StandardEnvironment(); @Test - public void applyEnvironmentPostProcessor() { + void applyEnvironmentPostProcessor() { assertThat(this.environment.containsProperty("test.foo.bar")).isFalse(); new EnvironmentPostProcessorExample().postProcessEnvironment(this.environment, new SpringApplication()); assertThat(this.environment.containsProperty("test.foo.bar")).isTrue(); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java index 4f0345d39eb..dadd54a9c39 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/embedded/TomcatLegacyCookieProcessorExampleTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.docs.context.embedded; import org.apache.catalina.Context; import org.apache.tomcat.util.http.LegacyCookieProcessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.docs.context.embedded.TomcatLegacyCookieProcessorExample.LegacyCookieProcessorConfiguration; @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class TomcatLegacyCookieProcessorExampleTests { +class TomcatLegacyCookieProcessorExampleTests { @Test - public void cookieProcessorIsCustomized() { + void cookieProcessorIsCustomized() { ServletWebServerApplicationContext applicationContext = (ServletWebServerApplicationContext) new SpringApplication( TestConfiguration.class, LegacyCookieProcessorConfiguration.class).run(); Context context = (Context) ((TomcatWebServer) applicationContext.getWebServer()).getTomcat().getHost() diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java index 50f892f3494..10b6997bc6f 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/context/properties/bind/AppSystemPropertiesTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.docs.context.properties.bind; import java.time.Duration; import java.util.function.Consumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; @@ -34,13 +34,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class AppSystemPropertiesTests { +class AppSystemPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(Config.class); @Test - public void bindWithDefaultUnit() { + void bindWithDefaultUnit() { this.contextRunner.withPropertyValues("app.system.session-timeout=40", "app.system.read-timeout=5000") .run(assertBinding((properties) -> { assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofSeconds(40)); @@ -49,7 +49,7 @@ public class AppSystemPropertiesTests { } @Test - public void bindWithExplicitUnit() { + void bindWithExplicitUnit() { this.contextRunner.withPropertyValues("app.system.session-timeout=1h", "app.system.read-timeout=5s") .run(assertBinding((properties) -> { assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofMinutes(60)); @@ -58,7 +58,7 @@ public class AppSystemPropertiesTests { } @Test - public void bindWithIso8601Format() { + void bindWithIso8601Format() { this.contextRunner.withPropertyValues("app.system.session-timeout=PT15S", "app.system.read-timeout=PT0.5S") .run(assertBinding((properties) -> { assertThat(properties.getSessionTimeout()).isEqualTo(Duration.ofSeconds(15)); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java index 94ad315c8e8..2d441f5c406 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/BasicDataSourceExampleTests.java @@ -20,14 +20,14 @@ import java.sql.SQLException; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -36,16 +36,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(properties = "app.datasource.jdbcUrl=jdbc:h2:mem:basic;DB_CLOSE_DELAY=-1") @Import(BasicDataSourceExample.BasicDataSourceConfiguration.class) -public class BasicDataSourceExampleTests { +class BasicDataSourceExampleTests { @Autowired private ApplicationContext context; @Test - public void validateConfiguration() throws SQLException { + void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:basic"); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java index dc7f034ba01..10a801536b2 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/CompleteTwoDataSourcesExampleTests.java @@ -20,14 +20,14 @@ import java.sql.SQLException; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -36,16 +36,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @Import(CompleteTwoDataSourcesExample.CompleteDataSourcesConfiguration.class) -public class CompleteTwoDataSourcesExampleTests { +class CompleteTwoDataSourcesExampleTests { @Autowired private ApplicationContext context; @Test - public void validateConfiguration() throws SQLException { + void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("firstDataSource")).isSameAs(dataSource); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java index ecfeff3a3f7..0e290c19f43 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/ConfigurableDataSourceExampleTests.java @@ -21,14 +21,14 @@ import java.sql.SQLException; import javax.sql.DataSource; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -37,17 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(properties = { "app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1", "app.datasource.configuration.maximum-pool-size=42" }) @Import(ConfigurableDataSourceExample.ConfigurableDataSourceConfiguration.class) -public class ConfigurableDataSourceExampleTests { +class ConfigurableDataSourceExampleTests { @Autowired private ApplicationContext context; @Test - public void validateConfiguration() throws SQLException { + void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:configurable"); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java index 0ab15c3b2a1..f64d9b87656 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleDataSourceExampleTests.java @@ -21,14 +21,14 @@ import java.sql.SQLException; import javax.sql.DataSource; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -37,17 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(properties = { "app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1", "app.datasource.maximum-pool-size=42" }) @Import(SimpleDataSourceExample.SimpleDataSourceConfiguration.class) -public class SimpleDataSourceExampleTests { +class SimpleDataSourceExampleTests { @Autowired private ApplicationContext context; @Test - public void validateConfiguration() throws SQLException { + void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); HikariDataSource dataSource = this.context.getBean(HikariDataSource.class); assertThat(dataSource.getConnection().getMetaData().getURL()).isEqualTo("jdbc:h2:mem:simple"); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java index efd7e4039d9..1866436a391 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jdbc/SimpleTwoDataSourcesExampleTests.java @@ -21,14 +21,14 @@ import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -37,17 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(properties = { "app.datasource.second.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", "app.datasource.second.max-total=42" }) @Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class) -public class SimpleTwoDataSourcesExampleTests { +class SimpleTwoDataSourcesExampleTests { @Autowired private ApplicationContext context; @Test - public void validateConfiguration() throws SQLException { + void validateConfiguration() throws SQLException { assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2); DataSource dataSource = this.context.getBean(DataSource.class); assertThat(this.context.getBean("firstDataSource")).isSameAs(dataSource); diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jmx/SampleJmxTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jmx/SampleJmxTests.java index 0680ff1ed62..c469e6daa32 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jmx/SampleJmxTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/jmx/SampleJmxTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,13 @@ package org.springframework.boot.docs.jmx; import javax.management.MBeanServer; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Example integration test that uses JMX. @@ -33,16 +33,16 @@ import org.springframework.test.context.junit4.SpringRunner; */ @SuppressWarnings("unused") // tag::test[] -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(properties = "spring.jmx.enabled=true") @DirtiesContext -public class SampleJmxTests { +class SampleJmxTests { @Autowired private MBeanServer mBeanServer; @Test - public void exampleTest() { + void exampleTest() { // ... } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java index c321f0d82f9..ccdcec3c21b 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/web/client/SampleWebClientTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.docs.web.client; import java.time.Duration; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -29,7 +29,7 @@ import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpHeaders; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -39,15 +39,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ // tag::test[] -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class SampleWebClientTests { +class SampleWebClientTests { @Autowired private TestRestTemplate template; @Test - public void testRequest() { + void testRequest() { HttpHeaders headers = this.template.getForEntity("/example", String.class).getHeaders(); assertThat(headers.getLocation()).hasHost("other.example.com"); } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java index 825d0f307fe..3331d571234 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java @@ -16,12 +16,13 @@ package org.springframework.boot.context.properties.migrator; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; @@ -32,14 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class PropertiesMigrationListenerTests { - - @Rule - public final OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class PropertiesMigrationListenerTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void closeContext() { if (this.context != null) { this.context.close(); @@ -47,9 +46,9 @@ public class PropertiesMigrationListenerTests { } @Test - public void sampleReport() { + void sampleReport(CapturedOutput capturedOutput) { this.context = createSampleApplication().run("--banner.charset=UTF8"); - assertThat(this.output.toString()).contains("commandLineArgs").contains("spring.banner.charset") + assertThat(capturedOutput).contains("commandLineArgs").contains("spring.banner.charset") .contains("Each configuration key has been temporarily mapped") .doesNotContain("Please refer to the migration guide"); } diff --git a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java index ef22fa4a5d0..34b4501a312 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java @@ -22,7 +22,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepository; import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepositoryJsonBuilder; @@ -46,18 +46,18 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class PropertiesMigrationReporterTests { +class PropertiesMigrationReporterTests { private ConfigurableEnvironment environment = new MockEnvironment(); @Test - public void reportIsNullWithNoMatchingKeys() { + void reportIsNullWithNoMatchingKeys() { String report = createWarningReport(new SimpleConfigurationMetadataRepository()); assertThat(report).isNull(); } @Test - public void replacementKeysAreRemapped() throws IOException { + void replacementKeysAreRemapped() throws IOException { MutablePropertySources propertySources = this.environment.getPropertySources(); PropertySource one = loadPropertySource("one", "config/config-error.properties"); PropertySource two = loadPropertySource("two", "config/config-warnings.properties"); @@ -70,7 +70,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void warningReport() throws IOException { + void warningReport() throws IOException { this.environment.getPropertySources().addFirst(loadPropertySource("test", "config/config-warnings.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("ignore", "config/config-error.properties")); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); @@ -81,7 +81,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void errorReport() throws IOException { + void errorReport() throws IOException { this.environment.getPropertySources() .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("test2", "config/config-error.properties")); @@ -93,7 +93,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void errorReportNoReplacement() throws IOException { + void errorReportNoReplacement() throws IOException { this.environment.getPropertySources() .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("second", "config/config-error.properties")); @@ -105,7 +105,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void durationTypeIsHandledTransparently() { + void durationTypeIsHandledTransparently() { MutablePropertySources propertySources = this.environment.getPropertySources(); Map content = new LinkedHashMap<>(); content.put("test.cache-seconds", 50); @@ -124,7 +124,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException { + void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException { this.environment.getPropertySources() .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); String report = createErrorReport(loadRepository("metadata/type-conversion-metadata.json")); @@ -134,7 +134,7 @@ public class PropertiesMigrationReporterTests { } @Test - public void invalidReplacementHandled() throws IOException { + void invalidReplacementHandled() throws IOException { this.environment.getPropertySources() .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata-invalid-replacement.json")); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/pom.xml b/spring-boot-project/spring-boot-test-autoconfigure/pom.xml index 2a2689799d2..fdc06ff8dfe 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/pom.xml +++ b/spring-boot-project/spring-boot-test-autoconfigure/pom.xml @@ -327,6 +327,11 @@ + + org.junit.platform + junit-platform-launcher + test + org.mongodb mongodb-driver-async diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java index 65e1ca1af75..827494a37e6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationContextCustomizerFactoryTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.test.autoconfigure; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.test.context.ContextCustomizer; @@ -27,30 +27,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class OverrideAutoConfigurationContextCustomizerFactoryTests { +class OverrideAutoConfigurationContextCustomizerFactoryTests { private OverrideAutoConfigurationContextCustomizerFactory factory = new OverrideAutoConfigurationContextCustomizerFactory(); @Test - public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { + void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() { + void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() { ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledTrue.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() { + void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); assertThat(customizer).isNotNull(); } @Test - public void hashCodeAndEquals() { + void hashCodeAndEquals() { ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null); ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameAnnotation.class, null); assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode()); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests.java index ef6be75a7cc..786e78ef3e9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests.java @@ -23,12 +23,10 @@ import java.util.List; import javax.annotation.PostConstruct; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -37,9 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @SpringBootTest -public class SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests { +class SpringBootDependencyInjectionTestExecutionListenerPostConstructIntegrationTests { private List calls = new ArrayList<>(); @@ -51,7 +48,7 @@ public class SpringBootDependencyInjectionTestExecutionListenerPostConstructInte } @Test - public void postConstructShouldBeInvokedOnlyOnce() { + void postConstructShouldBeInvokedOnlyOnce() { // gh-6874 assertThat(this.calls).hasSize(1); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java index 4307da33515..0cd58db6710 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java @@ -16,14 +16,15 @@ package org.springframework.boot.test.autoconfigure; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; @@ -32,7 +33,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.Matchers.containsString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -41,21 +41,19 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class SpringBootDependencyInjectionTestExecutionListenerTests { - - @Rule - public OutputCaptureRule out = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class SpringBootDependencyInjectionTestExecutionListenerTests { private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener(); @Test - public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() { + void orderShouldBeSameAsDependencyInjectionTestExecutionListener() { Ordered injectionListener = new DependencyInjectionTestExecutionListener(); assertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder()); } @Test - public void prepareFailingTestInstanceShouldPrintReport() throws Exception { + void prepareFailingTestInstanceShouldPrintReport(CapturedOutput capturedOutput) throws Exception { TestContext testContext = mock(TestContext.class); given(testContext.getTestInstance()).willThrow(new IllegalStateException()); SpringApplication application = new SpringApplication(Config.class); @@ -68,13 +66,12 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { catch (IllegalStateException ex) { // Expected } - this.out.expect(containsString("CONDITIONS EVALUATION REPORT")); - this.out.expect(containsString("Positive matches")); - this.out.expect(containsString("Negative matches")); + assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT").contains("Positive matches") + .contains("Negative matches"); } @Test - public void originalFailureIsThrownWhenReportGenerationFails() throws Exception { + void originalFailureIsThrownWhenReportGenerationFails() throws Exception { TestContext testContext = mock(TestContext.class); IllegalStateException originalFailure = new IllegalStateException(); given(testContext.getTestInstance()).willThrow(originalFailure); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java index f07e9335ace..2020d36c824 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java @@ -19,8 +19,12 @@ package org.springframework.boot.test.autoconfigure.cache; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Test; -import org.junit.runner.notification.RunNotifier; +import org.junit.jupiter.api.Test; +import org.junit.platform.engine.discovery.DiscoverySelectors; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; import org.junit.runners.model.InitializationError; import org.springframework.beans.factory.annotation.Autowired; @@ -32,7 +36,6 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.ExampleEntity; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -43,51 +46,55 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { +class ImportsContextCustomizerFactoryWithAutoConfigurationTests { static ApplicationContext contextFromTest; @Test - public void testClassesThatHaveSameAnnotationsShareAContext() throws InitializationError { - RunNotifier notifier = new RunNotifier(); - new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); + void testClassesThatHaveSameAnnotationsShareAContext() throws InitializationError { + executeTests(DataJpaTest1.class); ApplicationContext test1Context = contextFromTest; - new SpringJUnit4ClassRunner(DataJpaTest3.class).run(notifier); + executeTests(DataJpaTest3.class); ApplicationContext test2Context = contextFromTest; assertThat(test1Context).isSameAs(test2Context); } @Test - public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() throws InitializationError { - RunNotifier notifier = new RunNotifier(); - new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); + void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() throws InitializationError { + executeTests(DataJpaTest1.class); ApplicationContext test1Context = contextFromTest; - new SpringJUnit4ClassRunner(DataJpaTest2.class).run(notifier); + executeTests(DataJpaTest2.class); ApplicationContext test2Context = contextFromTest; assertThat(test1Context).isSameAs(test2Context); } @Test - public void testClassesThatOnlyHaveDifferingPropertyMappedAnnotationAttributesDoNotShareAContext() + void testClassesThatOnlyHaveDifferingPropertyMappedAnnotationAttributesDoNotShareAContext() throws InitializationError { - RunNotifier notifier = new RunNotifier(); - new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier); + executeTests(DataJpaTest1.class); ApplicationContext test1Context = contextFromTest; - new SpringJUnit4ClassRunner(DataJpaTest4.class).run(notifier); + executeTests(DataJpaTest4.class); ApplicationContext test2Context = contextFromTest; assertThat(test1Context).isNotSameAs(test2Context); } + private void executeTests(Class testClass) { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(DiscoverySelectors.selectClass(testClass)).build(); + Launcher launcher = LauncherFactory.create(); + launcher.execute(request); + } + @DataJpaTest @ContextConfiguration(classes = EmptyConfig.class) @Unrelated1 - public static class DataJpaTest1 { + static class DataJpaTest1 { @Autowired private ApplicationContext context; @Test - public void test() { + void test() { contextFromTest = this.context; } @@ -96,13 +103,13 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { @DataJpaTest @ContextConfiguration(classes = EmptyConfig.class) @Unrelated2 - public static class DataJpaTest2 { + static class DataJpaTest2 { @Autowired private ApplicationContext context; @Test - public void test() { + void test() { contextFromTest = this.context; } @@ -111,13 +118,13 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { @DataJpaTest @ContextConfiguration(classes = EmptyConfig.class) @Unrelated1 - public static class DataJpaTest3 { + static class DataJpaTest3 { @Autowired private ApplicationContext context; @Test - public void test() { + void test() { contextFromTest = this.context; } @@ -126,13 +133,13 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests { @DataJpaTest(showSql = false) @ContextConfiguration(classes = EmptyConfig.class) @Unrelated1 - public static class DataJpaTest4 { + static class DataJpaTest4 { @Autowired private ApplicationContext context; @Test - public void test() { + void test() { contextFromTest = this.context; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheIntegrationTests.java index d18ad82fe99..14ed23a42a0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.core; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -26,7 +25,6 @@ import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.support.NoOpCacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -35,16 +33,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureCache -public class AutoConfigureCacheIntegrationTests { +class AutoConfigureCacheIntegrationTests { @Autowired private ApplicationContext applicationContext; @Test - public void shouldConfigureNoOpCacheManager() { + void shouldConfigureNoOpCacheManager() { CacheManager bean = this.applicationContext.getBean(CacheManager.class); assertThat(bean).isInstanceOf(NoOpCacheManager.class); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheWithExistingCacheManagerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheWithExistingCacheManagerIntegrationTests.java index 9ab8eb1065e..5d3148e8076 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheWithExistingCacheManagerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/core/AutoConfigureCacheWithExistingCacheManagerIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.core; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -27,7 +26,6 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -37,16 +35,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureCache -public class AutoConfigureCacheWithExistingCacheManagerIntegrationTests { +class AutoConfigureCacheWithExistingCacheManagerIntegrationTests { @Autowired private ApplicationContext applicationContext; @Test - public void shouldNotReplaceExistingCacheManager() { + void shouldNotReplaceExistingCacheManager() { CacheManager bean = this.applicationContext.getBean(CacheManager.class); assertThat(bean).isInstanceOf(ConcurrentMapCacheManager.class); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java index 35f55e8ce68..91e9c7d21a5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.data.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +27,6 @@ import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfigurati import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -39,11 +37,10 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @DataJdbcTest @TestPropertySource( properties = "spring.datasource.schema=classpath:org/springframework/boot/test/autoconfigure/data/jdbc/schema.sql") -public class DataJdbcTestIntegrationTests { +class DataJdbcTestIntegrationTests { @Autowired private ExampleRepository repository; @@ -58,31 +55,31 @@ public class DataJdbcTestIntegrationTests { private JdbcTemplate jdbcTemplate; @Test - public void testRepository() { + void testRepository() { this.jdbcTemplate.update("INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (1, 'a', 'alpha')"); this.jdbcTemplate.update("INSERT INTO EXAMPLE_ENTITY (id, name, reference) VALUES (2, 'b', 'bravo')"); assertThat(this.repository.findAll()).hasSize(2); } @Test - public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { + void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test - public void didNotInjectExampleComponent() { + void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test - public void flywayAutoConfigurationWasImported() { + void flywayAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test - public void liquibaseAutoConfigurationWasImported() { + void liquibaseAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestPropertiesIntegrationTests.java index e18e4747972..aeb6d7af084 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.data.jdbc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @DataJdbcTest(properties = "spring.profiles.active=test") -public class DataJdbcTestPropertiesIntegrationTests { +class DataJdbcTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index 5f5f01a5aa9..08f693c2484 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.data.ldap; import java.util.Optional; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -29,7 +28,6 @@ import org.springframework.ldap.query.LdapQuery; import org.springframework.ldap.query.LdapQueryBuilder; import org.springframework.ldap.support.LdapUtils; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -39,11 +37,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @DataLdapTest @TestPropertySource(properties = { "spring.ldap.embedded.base-dn=dc=spring,dc=org", "spring.ldap.embedded.ldif=classpath:org/springframework/boot/test/autoconfigure/data/ldap/schema.ldif" }) -public class DataLdapTestIntegrationTests { +class DataLdapTestIntegrationTests { @Autowired private LdapTemplate ldapTemplate; @@ -55,7 +52,7 @@ public class DataLdapTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testRepository() { + void testRepository() { LdapQuery ldapQuery = LdapQueryBuilder.query().where("cn").is("Bob Smith"); Optional entry = this.exampleRepository.findOne(ldapQuery); assertThat(entry.isPresent()).isTrue(); @@ -66,7 +63,7 @@ public class DataLdapTestIntegrationTests { } @Test - public void didNotInjectExampleService() { + void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestPropertiesIntegrationTests.java index 91260ad9167..31f54f0bfaa 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.data.ldap; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @DataLdapTest(properties = "spring.profiles.active=test") -public class DataLdapTestPropertiesIntegrationTests { +class DataLdapTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestWithIncludeFilterIntegrationTests.java index 745ec77f4db..ef18abf5520 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestWithIncludeFilterIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.data.ldap; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan.Filter; @@ -25,7 +24,6 @@ import org.springframework.ldap.query.LdapQuery; import org.springframework.ldap.query.LdapQueryBuilder; import org.springframework.stereotype.Service; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -34,17 +32,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @DataLdapTest(includeFilters = @Filter(Service.class)) @TestPropertySource(properties = { "spring.ldap.embedded.base-dn=dc=spring,dc=org", "spring.ldap.embedded.ldif=classpath:org/springframework/boot/test/autoconfigure/data/ldap/schema.ldif" }) -public class DataLdapTestWithIncludeFilterIntegrationTests { +class DataLdapTestWithIncludeFilterIntegrationTests { @Autowired private ExampleService service; @Test - public void testService() { + void testService() { LdapQuery ldapQuery = LdapQueryBuilder.query().where("cn").is("Will Smith"); assertThat(this.service.hasEntry(ldapQuery)).isFalse(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java index c651959880a..dbf2152c7ea 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,12 @@ package org.springframework.boot.test.autoconfigure.data.mongo; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -33,9 +31,8 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Michael Simons */ -@RunWith(SpringRunner.class) @DataMongoTest -public class DataMongoTestIntegrationTests { +class DataMongoTestIntegrationTests { @Autowired private MongoTemplate mongoTemplate; @@ -47,7 +44,7 @@ public class DataMongoTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testRepository() { + void testRepository() { ExampleDocument exampleDocument = new ExampleDocument(); exampleDocument.setText("Look, new @DataMongoTest!"); exampleDocument = this.exampleRepository.save(exampleDocument); @@ -56,7 +53,7 @@ public class DataMongoTestIntegrationTests { } @Test - public void didNotInjectExampleService() { + void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestPropertiesIntegrationTests.java index 54004b98a83..88d3cdcc4fb 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.data.mongo; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @DataMongoTest(properties = "spring.profiles.active=test") -public class DataMongoTestPropertiesIntegrationTests { +class DataMongoTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java index 8f83f0cacd9..3b941f5c8bc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java @@ -18,12 +18,10 @@ package org.springframework.boot.test.autoconfigure.data.mongo; import java.time.Duration; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -32,9 +30,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @DataMongoTest -public class DataMongoTestReactiveIntegrationTests { +class DataMongoTestReactiveIntegrationTests { @Autowired private ReactiveMongoTemplate mongoTemplate; @@ -43,7 +40,7 @@ public class DataMongoTestReactiveIntegrationTests { private ExampleReactiveRepository exampleRepository; @Test - public void testRepository() { + void testRepository() { ExampleDocument exampleDocument = new ExampleDocument(); exampleDocument.setText("Look, new @DataMongoTest!"); exampleDocument = this.exampleRepository.save(exampleDocument).block(Duration.ofSeconds(30)); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java index 2b35dbbec93..15d9d7e5b82 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.data.mongo; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.stereotype.Service; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Michael Simons */ -@RunWith(SpringRunner.class) @DataMongoTest(includeFilters = @Filter(Service.class)) -public class DataMongoTestWithIncludeFilterIntegrationTests { +class DataMongoTestWithIncludeFilterIntegrationTests { @Autowired private ExampleService service; @Test - public void testService() { + void testService() { assertThat(this.service.hasCollection("foobar")).isFalse(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java index 5c13527cad8..a865efed2b5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java @@ -20,12 +20,11 @@ import org.junit.jupiter.api.Test; import org.neo4j.ogm.session.Session; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.testsupport.testcontainers.SkippableContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; @@ -43,12 +42,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ @ContextConfiguration(initializers = DataNeo4jTestIntegrationTests.Initializer.class) @DataNeo4jTest -@Testcontainers -public class DataNeo4jTestIntegrationTests { +@DisabledWithoutDockerTestcontainers +class DataNeo4jTestIntegrationTests { @Container - public static SkippableContainer> neo4j = new SkippableContainer<>( - () -> new Neo4jContainer<>().withAdminPassword(null)); + static final Neo4jContainer neo4j = new Neo4jContainer<>().withAdminPassword(null); @Autowired private Session session; @@ -60,7 +58,7 @@ public class DataNeo4jTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testRepository() { + void testRepository() { ExampleGraph exampleGraph = new ExampleGraph(); exampleGraph.setDescription("Look, new @DataNeo4jTest!"); assertThat(exampleGraph.getId()).isNull(); @@ -70,7 +68,7 @@ public class DataNeo4jTestIntegrationTests { } @Test - public void didNotInjectExampleService() { + void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @@ -79,7 +77,7 @@ public class DataNeo4jTestIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java index 3c1c3bdc23e..c11e2893820 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java @@ -19,11 +19,10 @@ package org.springframework.boot.test.autoconfigure.data.neo4j; import org.junit.jupiter.api.Test; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.testsupport.testcontainers.SkippableContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.Environment; @@ -37,20 +36,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@Testcontainers +@DisabledWithoutDockerTestcontainers @ContextConfiguration(initializers = DataNeo4jTestPropertiesIntegrationTests.Initializer.class) @DataNeo4jTest(properties = "spring.profiles.active=test") -public class DataNeo4jTestPropertiesIntegrationTests { +class DataNeo4jTestPropertiesIntegrationTests { @Container - public static SkippableContainer> neo4j = new SkippableContainer<>( - () -> new Neo4jContainer<>().withAdminPassword(null)); + static final Neo4jContainer neo4j = new Neo4jContainer<>().withAdminPassword(null); @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } @@ -58,7 +56,7 @@ public class DataNeo4jTestPropertiesIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java index 69be3c4a886..7ce964d9f1f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java @@ -19,11 +19,10 @@ package org.springframework.boot.test.autoconfigure.data.neo4j; import org.junit.jupiter.api.Test; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.boot.testsupport.testcontainers.SkippableContainer; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan.Filter; @@ -38,20 +37,19 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Michael Simons */ -@Testcontainers +@DisabledWithoutDockerTestcontainers @ContextConfiguration(initializers = DataNeo4jTestWithIncludeFilterIntegrationTests.Initializer.class) @DataNeo4jTest(includeFilters = @Filter(Service.class)) -public class DataNeo4jTestWithIncludeFilterIntegrationTests { +class DataNeo4jTestWithIncludeFilterIntegrationTests { @Container - public static SkippableContainer> neo4j = new SkippableContainer<>( - () -> new Neo4jContainer<>().withAdminPassword(null)); + static final Neo4jContainer neo4j = new Neo4jContainer<>().withAdminPassword(null); @Autowired private ExampleService service; @Test - public void testService() { + void testService() { assertThat(this.service.hasNode(ExampleGraph.class)).isFalse(); } @@ -59,7 +57,7 @@ public class DataNeo4jTestWithIncludeFilterIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getContainer().getBoltUrl()) + TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getBoltUrl()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java index f736feb418f..46800292a62 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java @@ -21,11 +21,11 @@ import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.boot.testsupport.testcontainers.RedisContainer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; @@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Jayaram Pradhan */ -@Testcontainers +@DisabledWithoutDockerTestcontainers @ContextConfiguration(initializers = DataRedisTestIntegrationTests.Initializer.class) @DataRedisTest -public class DataRedisTestIntegrationTests { +class DataRedisTestIntegrationTests { @Container public static RedisContainer redis = new RedisContainer(); @@ -62,7 +62,7 @@ public class DataRedisTestIntegrationTests { private static final Charset CHARSET = StandardCharsets.UTF_8; @Test - public void testRepository() { + void testRepository() { PersonHash personHash = new PersonHash(); personHash.setDescription("Look, new @DataRedisTest!"); assertThat(personHash.getId()).isNull(); @@ -74,7 +74,7 @@ public class DataRedisTestIntegrationTests { } @Test - public void didNotInjectExampleService() { + void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @@ -83,7 +83,7 @@ public class DataRedisTestIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) + TestPropertyValues.of("spring.redis.port=" + redis.getFirstMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java index 55c21c5ef0b..3e10961ac8b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestPropertiesIntegrationTests.java @@ -18,10 +18,10 @@ package org.springframework.boot.test.autoconfigure.data.redis; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.boot.testsupport.testcontainers.RedisContainer; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; @@ -36,19 +36,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@Testcontainers +@DisabledWithoutDockerTestcontainers @ContextConfiguration(initializers = DataRedisTestPropertiesIntegrationTests.Initializer.class) @DataRedisTest(properties = "spring.profiles.active=test") -public class DataRedisTestPropertiesIntegrationTests { +class DataRedisTestPropertiesIntegrationTests { @Container - public static RedisContainer redis = new RedisContainer(); + static final RedisContainer redis = new RedisContainer(); @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } @@ -56,7 +56,7 @@ public class DataRedisTestPropertiesIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) + TestPropertyValues.of("spring.redis.port=" + redis.getFirstMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java index fa76c11dd3b..b6d10f36ee4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java @@ -18,10 +18,10 @@ package org.springframework.boot.test.autoconfigure.data.redis; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.boot.testsupport.testcontainers.DisabledWithoutDockerTestcontainers; import org.springframework.boot.testsupport.testcontainers.RedisContainer; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Jayaram Pradhan */ -@Testcontainers +@DisabledWithoutDockerTestcontainers @ContextConfiguration(initializers = DataRedisTestWithIncludeFilterIntegrationTests.Initializer.class) @DataRedisTest(includeFilters = @Filter(Service.class)) -public class DataRedisTestWithIncludeFilterIntegrationTests { +class DataRedisTestWithIncludeFilterIntegrationTests { @Container - public static RedisContainer redis = new RedisContainer(); + static final RedisContainer redis = new RedisContainer(); @Autowired private ExampleRepository exampleRepository; @@ -51,7 +51,7 @@ public class DataRedisTestWithIncludeFilterIntegrationTests { private ExampleService service; @Test - public void testService() { + void testService() { PersonHash personHash = new PersonHash(); personHash.setDescription("Look, new @DataRedisTest!"); assertThat(personHash.getId()).isNull(); @@ -63,7 +63,7 @@ public class DataRedisTestWithIncludeFilterIntegrationTests { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of("spring.redis.port=" + redis.getMappedPort()) + TestPropertyValues.of("spring.redis.port=" + redis.getFirstMappedPort()) .applyTo(configurableApplicationContext.getEnvironment()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java index 82c213012aa..6af51402f05 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/FilterAnnotationsTests.java @@ -23,7 +23,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; @@ -41,38 +41,38 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class FilterAnnotationsTests { +class FilterAnnotationsTests { @Test - public void filterAnnotation() throws Exception { + void filterAnnotation() throws Exception { FilterAnnotations filterAnnotations = get(FilterByAnnotation.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isTrue(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isFalse(); } @Test - public void filterAssignableType() throws Exception { + void filterAssignableType() throws Exception { FilterAnnotations filterAnnotations = get(FilterByType.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test - public void filterCustom() throws Exception { + void filterCustom() throws Exception { FilterAnnotations filterAnnotations = get(FilterByCustom.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test - public void filterAspectJ() throws Exception { + void filterAspectJ() throws Exception { FilterAnnotations filterAnnotations = get(FilterByAspectJ.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test - public void filterRegex() throws Exception { + void filterRegex() throws Exception { FilterAnnotations filterAnnotations = get(FilterByRegex.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java index 03fc511a784..852a084b282 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactoryTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.test.autoconfigure.filter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.ConfigurableApplicationContext; @@ -35,7 +35,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class TypeExcludeFiltersContextCustomizerFactoryTests { +class TypeExcludeFiltersContextCustomizerFactoryTests { private TypeExcludeFiltersContextCustomizerFactory factory = new TypeExcludeFiltersContextCustomizerFactory(); @@ -44,19 +44,19 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { private ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { + void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() { ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() { + void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); assertThat(customizer).isNotNull(); } @Test - public void hashCodeAndEquals() { + void hashCodeAndEquals() { ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithExcludeFilters.class, null); ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameExcludeFilters.class, null); ContextCustomizer customizer3 = this.factory.createContextCustomizer(WithDifferentExcludeFilters.class, null); @@ -65,7 +65,7 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests { } @Test - public void getContextCustomizerShouldAddExcludeFilters() throws Exception { + void getContextCustomizerShouldAddExcludeFilters() throws Exception { ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null); customizer.customizeContext(this.context, this.mergedContextConfiguration); this.context.refresh(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java index f388d65c2a2..298d3197241 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -28,7 +27,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -38,16 +36,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Greg Potter */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase -public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { +class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests { @Autowired private DataSource dataSource; @Test - public void replacesDefinedDataSourceWithExplicit() throws Exception { + void replacesDefinedDataSourceWithExplicit() throws Exception { // Look that the datasource is replaced with an H2 DB. String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("H2"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests.java index 43871463d9c..00815827375 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests.java @@ -18,13 +18,13 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -34,15 +34,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @AutoConfigureTestDatabase -public class AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests { +class AutoConfigureTestDatabaseWithNoDatabaseIntegrationTests { @Autowired private ApplicationContext context; @Test - public void testContextLoads() { + void testContextLoads() { // gh-6897 assertThat(this.context).isNotNull(); assertThat(this.context.getBeanNamesForType(DataSource.class)).isNotEmpty(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index 489c3edca10..e0dd1f2b3d8 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -20,8 +20,7 @@ import java.util.Collection; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +29,6 @@ import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfigurati import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -41,11 +39,10 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @TestPropertySource( properties = "spring.datasource.schema=classpath:org/springframework/boot/test/autoconfigure/jdbc/schema.sql") -public class JdbcTestIntegrationTests { +class JdbcTestIntegrationTests { @Autowired private JdbcTemplate jdbcTemplate; @@ -57,7 +54,7 @@ public class JdbcTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testJdbcTemplate() { + void testJdbcTemplate() { ExampleRepository repository = new ExampleRepository(this.jdbcTemplate); repository.save(new ExampleEntity(1, "John")); Collection entities = repository.findAll(); @@ -68,24 +65,24 @@ public class JdbcTestIntegrationTests { } @Test - public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { + void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test - public void didNotInjectExampleRepository() { + void didNotInjectExampleRepository() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); } @Test - public void flywayAutoConfigurationWasImported() { + void flywayAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test - public void liquibaseAutoConfigurationWasImported() { + void liquibaseAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestPropertiesIntegrationTests.java index f046e594965..d56ad938d04 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.jdbc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @JdbcTest(properties = "spring.profiles.active=test") -public class JdbcTestPropertiesIntegrationTests { +class JdbcTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java index 01eb8942d29..98a8ec7b566 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests.java @@ -18,14 +18,12 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -35,17 +33,16 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED, connection = EmbeddedDatabaseConnection.HSQL) -public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests { @Autowired private DataSource dataSource; @Test - public void replacesAutoConfiguredDataSource() throws Exception { + void replacesAutoConfiguredDataSource() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java index a1f717f3b8a..98dcf63706b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -32,16 +30,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED) -public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOverrideIntegrationTests { @Autowired private DataSource dataSource; @Test - public void usesDefaultEmbeddedDatabase() throws Exception { + void usesDefaultEmbeddedDatabase() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); // @AutoConfigureTestDatabase would use H2 but HSQL is manually defined assertThat(product).startsWith("HSQL"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java index 1801654b6ba..855abfa39f5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -28,7 +27,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -38,16 +36,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.HSQL) -public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTests { @Autowired private DataSource dataSource; @Test - public void replacesDefinedDataSourceWithExplicit() throws Exception { + void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java index d10dfed32e6..e20c03a9e28 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -32,16 +30,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) -public class JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests { @Autowired private DataSource dataSource; @Test - public void usesDefaultEmbeddedDatabase() throws Exception { + void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java index 77e5d8f533f..fa2fedc5f30 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -29,7 +28,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -39,17 +37,16 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.HSQL) @TestPropertySource(properties = "spring.test.database.replace=ANY") -public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationTests { @Autowired private DataSource dataSource; @Test - public void replacesDefinedDataSourceWithExplicit() throws Exception { + void replacesDefinedDataSourceWithExplicit() throws Exception { // H2 is explicitly defined but HSQL is the override. String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java index 1a47260d79e..2f20d407944 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests.java @@ -18,15 +18,13 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -36,17 +34,16 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.HSQL) @TestPropertySource(properties = "spring.test.database.replace=AUTO_CONFIGURED") -public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredIntegrationTests { @Autowired private DataSource dataSource; @Test - public void replacesAutoConfiguredDataSource() throws Exception { + void replacesAutoConfiguredDataSource() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java index fa314fc72d1..fd5407f75b7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests.java @@ -18,12 +18,10 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -33,16 +31,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest @TestPropertySource(properties = "spring.test.database.replace=NONE") -public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests { +class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegrationTests { @Autowired private DataSource dataSource; @Test - public void usesDefaultEmbeddedDatabase() throws Exception { + void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithIncludeFilterIntegrationTests.java index 8aa6fdece5f..46ac3afcb69 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestWithIncludeFilterIntegrationTests.java @@ -16,14 +16,12 @@ package org.springframework.boot.test.autoconfigure.jdbc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.stereotype.Repository; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -32,17 +30,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JdbcTest(includeFilters = @Filter(Repository.class)) @TestPropertySource( properties = "spring.datasource.schema=classpath:org/springframework/boot/test/autoconfigure/jdbc/schema.sql") -public class JdbcTestWithIncludeFilterIntegrationTests { +class JdbcTestWithIncludeFilterIntegrationTests { @Autowired private ExampleRepository repository; @Test - public void testRepository() { + void testRepository() { this.repository.save(new ExampleEntity(42, "Smith")); ExampleEntity entity = this.repository.findById(42); assertThat(entity).isNotNull(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index 61d0644992b..7d368af518b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.test.autoconfigure.jdbc; import javax.sql.DataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -36,18 +36,18 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class TestDatabaseAutoConfigurationTests { +class TestDatabaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test - public void replaceWithNoDataSourceAvailable() { + void replaceWithNoDataSourceAvailable() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } @Test - public void replaceWithUniqueDatabase() { + void replaceWithUniqueDatabase() { this.contextRunner.withUserConfiguration(ExistingDataSourceConfiguration.class).run((context) -> { DataSource datasource = context.getBean(DataSource.class); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java index 0b551510047..5db713711b0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java @@ -20,8 +20,7 @@ import javax.sql.DataSource; import org.jooq.DSLContext; import org.jooq.SQLDialect; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -29,7 +28,6 @@ import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.boot.test.autoconfigure.orm.jpa.ExampleComponent; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -40,9 +38,8 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * * @author Michael Simons */ -@RunWith(SpringRunner.class) @JooqTest -public class JooqTestIntegrationTests { +class JooqTestIntegrationTests { @Autowired private DSLContext dsl; @@ -54,31 +51,31 @@ public class JooqTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testDSLContext() { + void testDSLContext() { assertThat(this.dsl.selectCount().from("INFORMATION_SCHEMA.TABLES").fetchOne(0, Integer.class)) .isGreaterThan(0); } @Test - public void useDefinedDataSource() throws Exception { + void useDefinedDataSource() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("HSQL"); assertThat(this.dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); } @Test - public void didNotInjectExampleComponent() { + void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test - public void flywayAutoConfigurationWasImported() { + void flywayAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test - public void liquibaseAutoConfigurationWasImported() { + void liquibaseAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestPropertiesIntegrationTests.java index 5ae1aa600ab..dc9235acc40 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.jooq; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @JooqTest(properties = "spring.profiles.active=test") -public class JooqTestPropertiesIntegrationTests { +class JooqTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java index 1ee0a771101..b934be094ab 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestWithAutoConfigureTestDatabaseIntegrationTests.java @@ -20,13 +20,11 @@ import javax.sql.DataSource; import org.jooq.DSLContext; import org.jooq.SQLDialect; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -35,10 +33,9 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @JooqTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) -public class JooqTestWithAutoConfigureTestDatabaseIntegrationTests { +class JooqTestWithAutoConfigureTestDatabaseIntegrationTests { @Autowired private DSLContext dsl; @@ -47,7 +44,7 @@ public class JooqTestWithAutoConfigureTestDatabaseIntegrationTests { private DataSource dataSource; @Test - public void replacesAutoConfiguredDataSource() throws Exception { + void replacesAutoConfiguredDataSource() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).startsWith("H2"); assertThat(this.dsl.configuration().dialect()).isEqualTo(SQLDialect.H2); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java index 993be4dadd3..b6214d651c2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.json; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.app.ExampleBasicObject; @@ -30,7 +29,6 @@ import org.springframework.boot.test.json.JacksonTester; import org.springframework.boot.test.json.JsonContent; import org.springframework.boot.test.json.JsonbTester; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -41,10 +39,9 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @JsonTest @ContextConfiguration(classes = ExampleJsonApplication.class) -public class JsonTestIntegrationTests { +class JsonTestIntegrationTests { @Autowired private BasicJsonTester basicJson; @@ -65,39 +62,39 @@ public class JsonTestIntegrationTests { private JsonbTester jsonbJson; @Test - public void basicJson() { + void basicJson() { assertThat(this.basicJson.from("{\"a\":\"b\"}")).hasJsonPathStringValue("@.a"); } @Test - public void jacksonBasic() throws Exception { + void jacksonBasic() throws Exception { ExampleBasicObject object = new ExampleBasicObject(); object.setValue("spring"); assertThat(this.jacksonBasicJson.write(object)).isEqualToJson("example.json"); } @Test - public void jacksonCustom() throws Exception { + void jacksonCustom() throws Exception { ExampleCustomObject object = new ExampleCustomObject("spring"); assertThat(this.jacksonCustomJson.write(object)).isEqualToJson("example.json"); } @Test - public void gson() throws Exception { + void gson() throws Exception { ExampleBasicObject object = new ExampleBasicObject(); object.setValue("spring"); assertThat(this.gsonJson.write(object)).isEqualToJson("example.json"); } @Test - public void jsonb() throws Exception { + void jsonb() throws Exception { ExampleBasicObject object = new ExampleBasicObject(); object.setValue("spring"); assertThat(this.jsonbJson.write(object)).isEqualToJson("example.json"); } @Test - public void customView() throws Exception { + void customView() throws Exception { ExampleJsonObjectWithView object = new ExampleJsonObjectWithView(); object.setValue("spring"); JsonContent content = this.jacksonWithViewJson diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestPropertiesIntegrationTests.java index a96ab346537..75ffd44952b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.json; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @JsonTest(properties = "spring.profiles.active=test") -public class JsonTestPropertiesIntegrationTests { +class JsonTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestWithAutoConfigureJsonTestersTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestWithAutoConfigureJsonTestersTests.java index 35f5d32e332..e8076338fc2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestWithAutoConfigureJsonTestersTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestWithAutoConfigureJsonTestersTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.json; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.app.ExampleBasicObject; @@ -27,7 +26,6 @@ import org.springframework.boot.test.json.GsonTester; import org.springframework.boot.test.json.JacksonTester; import org.springframework.boot.test.json.JsonbTester; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -37,11 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @JsonTest @AutoConfigureJsonTesters(enabled = false) @ContextConfiguration(classes = ExampleJsonApplication.class) -public class JsonTestWithAutoConfigureJsonTestersTests { +class JsonTestWithAutoConfigureJsonTestersTests { @Autowired(required = false) private BasicJsonTester basicJson; @@ -56,22 +53,22 @@ public class JsonTestWithAutoConfigureJsonTestersTests { private JsonbTester jsonbTester; @Test - public void basicJson() { + void basicJson() { assertThat(this.basicJson).isNull(); } @Test - public void jackson() { + void jackson() { assertThat(this.jacksonTester).isNull(); } @Test - public void gson() { + void gson() { assertThat(this.gsonTester).isNull(); } @Test - public void jsonb() { + void jsonb() { assertThat(this.jsonbTester).isNull(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/SpringBootTestWithAutoConfigureJsonTestersTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/SpringBootTestWithAutoConfigureJsonTestersTests.java index c674509bcae..45da575d01b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/SpringBootTestWithAutoConfigureJsonTestersTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/SpringBootTestWithAutoConfigureJsonTestersTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.json; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.app.ExampleBasicObject; @@ -28,7 +27,6 @@ import org.springframework.boot.test.json.GsonTester; import org.springframework.boot.test.json.JacksonTester; import org.springframework.boot.test.json.JsonbTester; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -38,11 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureJsonTesters @ContextConfiguration(classes = ExampleJsonApplication.class) -public class SpringBootTestWithAutoConfigureJsonTestersTests { +class SpringBootTestWithAutoConfigureJsonTestersTests { @Autowired private BasicJsonTester basicJson; @@ -57,7 +54,7 @@ public class SpringBootTestWithAutoConfigureJsonTestersTests { private JsonbTester jsonbTester; @Test - public void contextLoads() { + void contextLoads() { assertThat(this.basicJson).isNotNull(); assertThat(this.jacksonTester).isNotNull(); assertThat(this.jsonbTester).isNotNull(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index 1ab344381bd..8324341391f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.orm.jpa; import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +27,6 @@ import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfigurati import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -40,10 +38,9 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * @author Phillip Webb * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @DataJpaTest @TestPropertySource(properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false") -public class DataJpaTestIntegrationTests { +class DataJpaTestIntegrationTests { @Autowired private TestEntityManager entities; @@ -61,7 +58,7 @@ public class DataJpaTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void testEntityManager() { + void testEntityManager() { ExampleEntity entity = this.entities.persist(new ExampleEntity("spring", "123")); this.entities.flush(); Object id = this.entities.getId(entity); @@ -70,7 +67,7 @@ public class DataJpaTestIntegrationTests { } @Test - public void testEntityManagerPersistAndGetId() { + void testEntityManagerPersistAndGetId() { Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), Long.class); assertThat(id).isNotNull(); String reference = this.jdbcTemplate.queryForObject("SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", @@ -79,7 +76,7 @@ public class DataJpaTestIntegrationTests { } @Test - public void testRepository() { + void testRepository() { this.entities.persist(new ExampleEntity("spring", "123")); this.entities.persist(new ExampleEntity("boot", "124")); this.entities.flush(); @@ -88,24 +85,24 @@ public class DataJpaTestIntegrationTests { } @Test - public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { + void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); } @Test - public void didNotInjectExampleComponent() { + void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test - public void flywayAutoConfigurationWasImported() { + void flywayAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class)); } @Test - public void liquibaseAutoConfigurationWasImported() { + void liquibaseAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestPropertiesIntegrationTests.java index 6b4971c2ea3..da8567836f4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.orm.jpa; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @DataJpaTest(properties = "spring.profiles.active=test") -public class DataJpaTestPropertiesIntegrationTests { +class DataJpaTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index 344f066b2ea..848ea270653 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -20,8 +20,8 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnitUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -39,7 +39,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class TestEntityManagerTests { +class TestEntityManagerTests { @Mock private EntityManagerFactory entityManagerFactory; @@ -52,7 +52,7 @@ public class TestEntityManagerTests { private TestEntityManager testEntityManager; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.testEntityManager = new TestEntityManager(this.entityManagerFactory); @@ -60,13 +60,13 @@ public class TestEntityManagerTests { } @Test - public void createWhenEntityManagerIsNullShouldThrowException() { + void createWhenEntityManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestEntityManager(null)) .withMessageContaining("EntityManagerFactory must not be null"); } @Test - public void persistAndGetIdShouldPersistAndGetId() { + void persistAndGetIdShouldPersistAndGetId() { bindEntityManager(); TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); @@ -76,7 +76,7 @@ public class TestEntityManagerTests { } @Test - public void persistAndGetIdForTypeShouldPersistAndGetId() { + void persistAndGetIdForTypeShouldPersistAndGetId() { bindEntityManager(); TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); @@ -86,7 +86,7 @@ public class TestEntityManagerTests { } @Test - public void persistShouldPersist() { + void persistShouldPersist() { bindEntityManager(); TestEntity entity = new TestEntity(); TestEntity result = this.testEntityManager.persist(entity); @@ -95,7 +95,7 @@ public class TestEntityManagerTests { } @Test - public void persistAndFlushShouldPersistAndFlush() { + void persistAndFlushShouldPersistAndFlush() { bindEntityManager(); TestEntity entity = new TestEntity(); TestEntity result = this.testEntityManager.persistAndFlush(entity); @@ -105,7 +105,7 @@ public class TestEntityManagerTests { } @Test - public void persistFlushFindShouldPersistAndFlushAndFind() { + void persistFlushFindShouldPersistAndFlushAndFind() { bindEntityManager(); TestEntity entity = new TestEntity(); TestEntity found = new TestEntity(); @@ -118,7 +118,7 @@ public class TestEntityManagerTests { } @Test - public void mergeShouldMerge() { + void mergeShouldMerge() { bindEntityManager(); TestEntity entity = new TestEntity(); given(this.entityManager.merge(entity)).willReturn(entity); @@ -128,7 +128,7 @@ public class TestEntityManagerTests { } @Test - public void removeShouldRemove() { + void removeShouldRemove() { bindEntityManager(); TestEntity entity = new TestEntity(); this.testEntityManager.remove(entity); @@ -136,7 +136,7 @@ public class TestEntityManagerTests { } @Test - public void findShouldFind() { + void findShouldFind() { bindEntityManager(); TestEntity entity = new TestEntity(); given(this.entityManager.find(TestEntity.class, 123)).willReturn(entity); @@ -145,14 +145,14 @@ public class TestEntityManagerTests { } @Test - public void flushShouldFlush() { + void flushShouldFlush() { bindEntityManager(); this.testEntityManager.flush(); verify(this.entityManager).flush(); } @Test - public void refreshShouldRefresh() { + void refreshShouldRefresh() { bindEntityManager(); TestEntity entity = new TestEntity(); this.testEntityManager.refresh(entity); @@ -160,14 +160,14 @@ public class TestEntityManagerTests { } @Test - public void clearShouldClear() { + void clearShouldClear() { bindEntityManager(); this.testEntityManager.clear(); verify(this.entityManager).clear(); } @Test - public void detachShouldDetach() { + void detachShouldDetach() { bindEntityManager(); TestEntity entity = new TestEntity(); this.testEntityManager.detach(entity); @@ -175,7 +175,7 @@ public class TestEntityManagerTests { } @Test - public void getIdForTypeShouldGetId() { + void getIdForTypeShouldGetId() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Integer result = this.testEntityManager.getId(entity, Integer.class); @@ -183,7 +183,7 @@ public class TestEntityManagerTests { } @Test - public void getIdForTypeWhenTypeIsWrongShouldThrowException() { + void getIdForTypeWhenTypeIsWrongShouldThrowException() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); assertThatIllegalArgumentException().isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) @@ -192,7 +192,7 @@ public class TestEntityManagerTests { } @Test - public void getIdShouldGetId() { + void getIdShouldGetId() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Object result = this.testEntityManager.getId(entity); @@ -200,13 +200,13 @@ public class TestEntityManagerTests { } @Test - public void getEntityManagerShouldGetEntityManager() { + void getEntityManagerShouldGetEntityManager() { bindEntityManager(); assertThat(this.testEntityManager.getEntityManager()).isEqualTo(this.entityManager); } @Test - public void getEntityManagerWhenNotSetShouldThrowException() { + void getEntityManagerWhenNotSetShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.testEntityManager::getEntityManager) .withMessageContaining("No transactional EntityManager found"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java index 8414653abca..e71ceebf9de 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.test.autoconfigure.override; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +28,7 @@ import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration; import org.springframework.boot.test.context.SpringBootTestContextBootstrapper; import org.springframework.context.ApplicationContext; import org.springframework.test.context.BootstrapWith; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -39,17 +39,17 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @OverrideAutoConfiguration(enabled = false) @BootstrapWith(SpringBootTestContextBootstrapper.class) @ImportAutoConfiguration(ExampleTestConfig.class) -public class OverrideAutoConfigurationEnabledFalseIntegrationTests { +class OverrideAutoConfigurationEnabledFalseIntegrationTests { @Autowired private ApplicationContext context; @Test - public void disabledAutoConfiguration() { + void disabledAutoConfiguration() { ApplicationContext context = this.context; assertThat(context.getBean(ExampleTestConfig.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java index 9e3b350abdc..7a66bb6db3c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledTrueIntegrationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.test.autoconfigure.override; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -27,7 +27,7 @@ import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration; import org.springframework.boot.test.context.SpringBootTestContextBootstrapper; import org.springframework.context.ApplicationContext; import org.springframework.test.context.BootstrapWith; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -37,17 +37,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @OverrideAutoConfiguration(enabled = true) @BootstrapWith(SpringBootTestContextBootstrapper.class) @ImportAutoConfiguration(ExampleTestConfig.class) -public class OverrideAutoConfigurationEnabledTrueIntegrationTests { +class OverrideAutoConfigurationEnabledTrueIntegrationTests { @Autowired private ApplicationContext context; @Test - public void autoConfiguredContext() { + void autoConfiguredContext() { ApplicationContext context = this.context; assertThat(context.getBean(OverrideAutoConfigurationSpringBootApplication.class)).isNotNull(); assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)).isNotNull(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index 856aab5f4c5..2744df4d8bb 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.test.autoconfigure.properties; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AliasFor; @@ -32,65 +32,65 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Andy Wilkinson */ -public class AnnotationsPropertySourceTests { +class AnnotationsPropertySourceTests { @Test - public void createWhenSourceIsNullShouldThrowException() { + void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new AnnotationsPropertySource(null)) .withMessageContaining("Property source must not be null"); } @Test - public void propertiesWhenHasNoAnnotationShouldBeEmpty() { + void propertiesWhenHasNoAnnotationShouldBeEmpty() { AnnotationsPropertySource source = new AnnotationsPropertySource(NoAnnotation.class); assertThat(source.getPropertyNames()).isEmpty(); assertThat(source.getProperty("value")).isNull(); } @Test - public void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName() { + void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName() { AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("abc"); } @Test - public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() { + void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() { AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.value"); assertThat(source.getProperty("test.value")).isEqualTo("abc"); } @Test - public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() { + void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() { AnnotationsPropertySource source = new AnnotationsPropertySource(AttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test"); assertThat(source.getProperty("test")).isEqualTo("abc"); } @Test - public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() { + void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() { AnnotationsPropertySource source = new AnnotationsPropertySource(TypeAndAttributeLevelWithPrefix.class); assertThat(source.getPropertyNames()).containsExactly("test.example"); assertThat(source.getProperty("test.example")).isEqualTo("abc"); } @Test - public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() { + void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() { AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtTypeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @Test - public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() { + void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() { AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtAttributeLevel.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("ignore")).isNull(); } @Test - public void propertiesWhenContainsArraysShouldExpandNames() { + void propertiesWhenContainsArraysShouldExpandNames() { AnnotationsPropertySource source = new AnnotationsPropertySource(Arrays.class); assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", "classes[0]", "classes[1]", "ints[0]", "ints[1]", "longs[0]", "longs[1]", "floats[0]", "floats[1]", "doubles[0]", "doubles[1]", @@ -112,20 +112,20 @@ public class AnnotationsPropertySourceTests { } @Test - public void propertiesWhenHasCamelCaseShouldConvertToKebabCase() { + void propertiesWhenHasCamelCaseShouldConvertToKebabCase() { AnnotationsPropertySource source = new AnnotationsPropertySource(CamelCaseToKebabCase.class); assertThat(source.getPropertyNames()).contains("camel-case-to-kebab-case"); } @Test - public void propertiesFromMetaAnnotationsAreMapped() { + void propertiesFromMetaAnnotationsAreMapped() { AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromSingleMetaAnnotation.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("foo"); } @Test - public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() { + void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() { AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromMultipleMetaAnnotations.class); assertThat(source.getPropertyNames()).containsExactly("value", "test.value", "test.example"); assertThat(source.getProperty("value")).isEqualTo("alpha"); @@ -134,26 +134,26 @@ public class AnnotationsPropertySourceTests { } @Test - public void propertyMappedAttributesCanBeAliased() { + void propertyMappedAttributesCanBeAliased() { AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAttributeWithAnAlias.class); assertThat(source.getPropertyNames()).containsExactly("aliasing.value"); assertThat(source.getProperty("aliasing.value")).isEqualTo("baz"); } @Test - public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { + void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { new AnnotationsPropertySource(PropertyMappedWithSelfAnnotatingAnnotation.class); } @Test - public void typeLevelAnnotationOnSuperClass() { + void typeLevelAnnotationOnSuperClass() { AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAnnotationOnSuperClass.class); assertThat(source.getPropertyNames()).containsExactly("value"); assertThat(source.getProperty("value")).isEqualTo("abc"); } @Test - public void aliasedPropertyMappedAttributeOnSuperClass() { + void aliasedPropertyMappedAttributeOnSuperClass() { AnnotationsPropertySource source = new AnnotationsPropertySource( AliasedPropertyMappedAnnotationOnSuperClass.class); assertThat(source.getPropertyNames()).containsExactly("aliasing.value"); @@ -161,13 +161,13 @@ public class AnnotationsPropertySourceTests { } @Test - public void enumValueMapped() { + void enumValueMapped() { AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueMapped.class); assertThat(source.getProperty("testenum.value")).isEqualTo(EnumItem.TWO); } @Test - public void enumValueNotMapped() { + void enumValueNotMapped() { AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueNotMapped.class); assertThat(source.containsProperty("testenum.value")).isFalse(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index 45eadf376d0..ed6d1415b40 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.test.autoconfigure.properties; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -40,12 +40,12 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class PropertyMappingContextCustomizerFactoryTests { +class PropertyMappingContextCustomizerFactoryTests { private PropertyMappingContextCustomizerFactory factory = new PropertyMappingContextCustomizerFactory(); @Test - public void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() { + void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() { ContextCustomizer customizer = this.factory.createContextCustomizer(NoMapping.class, null); ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); @@ -57,19 +57,19 @@ public class PropertyMappingContextCustomizerFactoryTests { } @Test - public void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() { + void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(TypeMapping.class, null); assertThat(customizer).isNotNull(); } @Test - public void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() { + void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); assertThat(customizer).isNotNull(); } @Test - public void hashCodeAndEqualsShouldBeBasedOnPropertyValues() { + void hashCodeAndEqualsShouldBeBasedOnPropertyValues() { ContextCustomizer customizer1 = this.factory.createContextCustomizer(TypeMapping.class, null); ContextCustomizer customizer2 = this.factory.createContextCustomizer(AttributeMapping.class, null); ContextCustomizer customizer3 = this.factory.createContextCustomizer(OtherMapping.class, null); @@ -78,7 +78,7 @@ public class PropertyMappingContextCustomizerFactoryTests { } @Test - public void prepareContextShouldAddPropertySource() { + void prepareContextShouldAddPropertySource() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, null); @@ -86,7 +86,7 @@ public class PropertyMappingContextCustomizerFactoryTests { } @Test - public void propertyMappingShouldNotBeUsedWithComponent() { + void propertyMappingShouldNotBeUsedWithComponent() { ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(ConfigMapping.class); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingTests.java index c016a0a5357..dc6126cc63c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,12 @@ package org.springframework.boot.test.autoconfigure.properties; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -30,15 +30,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @ExampleMapping(exampleProperty = "abc") -public class PropertyMappingTests { +class PropertyMappingTests { @Autowired private Environment environment; @Test - public void hasProperty() { + void hasProperty() { assertThat(this.environment.getProperty("example-property")).isEqualTo("abc"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 818adf9620a..66193f97ba5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -18,9 +18,8 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -31,7 +30,6 @@ import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.FileSystemUtils; @@ -50,11 +48,10 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder * @author Andy Wilkinson * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @WebMvcTest(controllers = RestDocsTestController.class) @WithMockUser @AutoConfigureRestDocs -public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { +class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Autowired private MockMvc mvc; @@ -64,14 +61,14 @@ public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTes private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void snippetGeneration() throws Exception { + void snippetGeneration() throws Exception { this.mvc.perform(get("/")).andDo(this.documentationHandler .document(links(linkWithRel("self").description("Canonical location of this resource")))); File defaultSnippetsDir = new File(this.generatedSnippets, "snippet-generation"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java index 348bdd42bc2..c7edfdc9894 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationIntegrationTests.java @@ -18,14 +18,12 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.testsupport.BuildOutput; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.FileSystemUtils; @@ -39,24 +37,23 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @WebMvcTest @AutoConfigureRestDocs(uriScheme = "https", uriHost = "api.example.com", uriPort = 443) -public class MockMvcRestDocsAutoConfigurationIntegrationTests { +class MockMvcRestDocsAutoConfigurationIntegrationTests { @Autowired private MockMvc mvc; private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void defaultSnippetsAreWritten() throws Exception { + void defaultSnippetsAreWritten() throws Exception { this.mvc.perform(get("/")).andDo(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index d9afa9459e7..4bd39cb3c17 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -19,9 +19,8 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -33,7 +32,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.FileSystemUtils; import static io.restassured.RestAssured.given; @@ -52,10 +50,9 @@ import static org.springframework.restdocs.restassured3.RestAssuredRestDocumenta * * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureRestDocs -public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { +class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @LocalServerPort private int port; @@ -65,14 +62,14 @@ public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegratio private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void snippetGeneration() { + void snippetGeneration() { given(this.documentationSpec) .filter(document("default-snippets", preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java index cf96361e618..5ed7089f3a2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java @@ -19,16 +19,14 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.FileSystemUtils; import static io.restassured.RestAssured.given; @@ -44,10 +42,9 @@ import static org.springframework.restdocs.restassured3.RestAssuredRestDocumenta * * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureRestDocs -public class RestAssuredRestDocsAutoConfigurationIntegrationTests { +class RestAssuredRestDocsAutoConfigurationIntegrationTests { @LocalServerPort private int port; @@ -57,14 +54,14 @@ public class RestAssuredRestDocsAutoConfigurationIntegrationTests { private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void defaultSnippetsAreWritten() { + void defaultSnippetsAreWritten() { given(this.documentationSpec) .filter(document("default-snippets", preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index aa73c5dbfcb..bfe06a73741 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -18,9 +18,8 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; @@ -31,7 +30,6 @@ import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation; import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.FileSystemUtils; @@ -46,25 +44,24 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume * * @author Eddú Meléndez */ -@RunWith(SpringRunner.class) @WebFluxTest @WithMockUser @AutoConfigureRestDocs(uriScheme = "https", uriHost = "api.example.com", uriPort = 443) -public class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { +class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Autowired private WebTestClient webTestClient; private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void defaultSnippetsAreWritten() throws Exception { + void defaultSnippetsAreWritten() throws Exception { this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java index 8869b95e815..d29b1809d9a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java @@ -18,15 +18,13 @@ package org.springframework.boot.test.autoconfigure.restdocs; import java.io.File; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.FileSystemUtils; @@ -39,25 +37,24 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume * * @author Roman Zaynetdinov */ -@RunWith(SpringRunner.class) @WebFluxTest @WithMockUser @AutoConfigureRestDocs(uriScheme = "https", uriHost = "api.example.com", uriPort = 443) -public class WebTestClientRestDocsAutoConfigurationIntegrationTests { +class WebTestClientRestDocsAutoConfigurationIntegrationTests { @Autowired private WebTestClient webTestClient; private File generatedSnippets; - @Before + @BeforeEach public void deleteSnippets() { this.generatedSnippets = new File(new BuildOutput(getClass()).getRootLocation(), "generated-snippets"); FileSystemUtils.deleteRecursively(this.generatedSnippets); } @Test - public void defaultSnippetsAreWritten() throws Exception { + void defaultSnippetsAreWritten() throws Exception { this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java index 510ab6c0571..8a4ead9d31f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.security; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -25,7 +24,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.Base64Utils; @@ -38,26 +36,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Andy Wilkinson */ @WebMvcTest -@RunWith(SpringRunner.class) @TestPropertySource(properties = { "debug=true" }) -public class MockMvcSecurityIntegrationTests { +class MockMvcSecurityIntegrationTests { @Autowired private MockMvc mockMvc; @Test @WithMockUser(username = "test", password = "test", roles = "USER") - public void okResponseWithMockUser() throws Exception { + void okResponseWithMockUser() throws Exception { this.mockMvc.perform(get("/")).andExpect(status().isOk()); } @Test - public void unauthorizedResponseWithNoUser() throws Exception { + void unauthorizedResponseWithNoUser() throws Exception { this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); } @Test - public void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { + void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java index e0f69b59c71..52fcbdfdb72 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java @@ -16,14 +16,12 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.web.client.MockServerRestTemplateCustomizer; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -34,16 +32,15 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @RestClientTest @AutoConfigureMockRestServiceServer(enabled = false) -public class AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests { +class AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests { @Autowired private ApplicationContext applicationContext; @Test - public void mockServerRestTemplateCustomizerShouldNotBeRegistered() { + void mockServerRestTemplateCustomizerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java index 8d67dfea88c..a8fa93e2ddc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -26,7 +25,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @@ -40,11 +38,10 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureWebClient(registerRestTemplate = true) @AutoConfigureMockRestServiceServer -public class AutoConfigureWebClientWithRestTemplateIntegrationTests { +class AutoConfigureWebClientWithRestTemplateIntegrationTests { @Autowired private RestTemplate restTemplate; @@ -53,7 +50,7 @@ public class AutoConfigureWebClientWithRestTemplateIntegrationTests { private MockRestServiceServer server; @Test - public void restTemplateTest() { + void restTemplateTest() { this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); ResponseEntity entity = this.restTemplate.getForEntity("/test", String.class); assertThat(entity.getBody()).isEqualTo("hello"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java index c2d679815cf..b2df64ab711 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.assertj.core.api.Assertions.assertThat; @@ -34,9 +32,8 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @RestClientTest(ExampleRestClient.class) -public class RestClientRestIntegrationTests { +class RestClientRestIntegrationTests { @Autowired private MockRestServiceServer server; @@ -45,19 +42,19 @@ public class RestClientRestIntegrationTests { private ExampleRestClient client; @Test - public void mockServerCall1() { + void mockServerCall1() { this.server.expect(requestTo("/test")).andRespond(withSuccess("1", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("1"); } @Test - public void mockServerCall2() { + void mockServerCall2() { this.server.expect(requestTo("/test")).andRespond(withSuccess("2", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("2"); } @Test - public void mockServerCallWithContent() { + void mockServerCallWithContent() { this.server.expect(requestTo("/test")).andExpect(content().string("test")) .andRespond(withSuccess("1", MediaType.TEXT_HTML)); this.client.testPostWithBody("test"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java index 996131429d7..5c4b7834b35 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java @@ -16,15 +16,13 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.ApplicationContext; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.assertj.core.api.Assertions.assertThat; @@ -37,9 +35,8 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @RestClientTest -public class RestClientTestNoComponentIntegrationTests { +class RestClientTestNoComponentIntegrationTests { @Autowired private ApplicationContext applicationContext; @@ -51,13 +48,13 @@ public class RestClientTestNoComponentIntegrationTests { private MockRestServiceServer server; @Test - public void exampleRestClientIsNotInjected() { + void exampleRestClientIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); } @Test - public void manuallyCreateBean() { + void manuallyCreateBean() { ExampleRestClient client = new ExampleRestClient(this.restTemplateBuilder); this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(client.test()).isEqualTo("hello"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestPropertiesIntegrationTests.java index 3a85309367e..c1fbe2eb53c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @RestClientTest(properties = "spring.profiles.active=test") -public class RestClientTestPropertiesIntegrationTests { +class RestClientTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index ec593fdc14a..9645c053244 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.web.client.MockServerRestTemplateCustomizer; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.assertj.core.api.Assertions.assertThat; @@ -35,9 +33,8 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @RestClientTest({ ExampleRestClient.class, AnotherExampleRestClient.class }) -public class RestClientTestTwoComponentsIntegrationTests { +class RestClientTestTwoComponentsIntegrationTests { @Autowired private ExampleRestClient client1; @@ -52,21 +49,21 @@ public class RestClientTestTwoComponentsIntegrationTests { private MockRestServiceServer server; @Test - public void serverShouldNotWork() { + void serverShouldNotWork() { assertThatIllegalStateException().isThrownBy( () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) .withMessageContaining("Unable to use auto-configured"); } @Test - public void client1RestCallViaCustomizer() { + void client1RestCallViaCustomizer() { this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client1.test()).isEqualTo("hello"); } @Test - public void client2RestCallViaCustomizer() { + void client2RestCallViaCustomizer() { this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test")) .andRespond(withSuccess("there", MediaType.TEXT_HTML)); assertThat(this.client2.test()).isEqualTo("there"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestPropertiesIntegrationTests.java index a935d409c9e..870aafa09d4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.reactive; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @WebFluxTest(properties = "spring.profiles.active=test") -public class WebFluxTestPropertiesIntegrationTests { +class WebFluxTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java index 19f8b5fb7e4..ef8a06374e2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTypeExcludeFilterTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.test.autoconfigure.web.reactive; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; @@ -39,12 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class WebFluxTypeExcludeFilterTests { +class WebFluxTypeExcludeFilterTests { private MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); @Test - public void matchWhenHasNoControllers() throws Exception { + void matchWhenHasNoControllers() throws Exception { WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithNoControllers.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); @@ -55,7 +55,7 @@ public class WebFluxTypeExcludeFilterTests { } @Test - public void matchWhenHasController() throws Exception { + void matchWhenHasController() throws Exception { WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithController.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isTrue(); @@ -66,7 +66,7 @@ public class WebFluxTypeExcludeFilterTests { } @Test - public void matchNotUsingDefaultFilters() throws Exception { + void matchNotUsingDefaultFilters() throws Exception { WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(NotUsingDefaultFilters.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isTrue(); @@ -77,7 +77,7 @@ public class WebFluxTypeExcludeFilterTests { } @Test - public void matchWithIncludeFilter() throws Exception { + void matchWithIncludeFilter() throws Exception { WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithIncludeFilter.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); @@ -88,7 +88,7 @@ public class WebFluxTypeExcludeFilterTests { } @Test - public void matchWithExcludeFilter() throws Exception { + void matchWithExcludeFilter() throws Exception { WebFluxTypeExcludeFilter filter = new WebFluxTypeExcludeFilter(WithExcludeFilter.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isFalse(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java index 6d31af0265e..e9941f77044 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java @@ -20,7 +20,7 @@ import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -48,13 +48,13 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Stephane Nicoll */ -public class WebTestClientAutoConfigurationTests { +class WebTestClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); @Test - public void shouldNotBeConfiguredWithoutWebHandler() { + void shouldNotBeConfiguredWithoutWebHandler() { this.contextRunner.run((context) -> { assertThat(context).hasNotFailed(); assertThat(context).doesNotHaveBean(WebTestClient.class); @@ -62,7 +62,7 @@ public class WebTestClientAutoConfigurationTests { } @Test - public void shouldCustomizeClientCodecs() { + void shouldCustomizeClientCodecs() { this.contextRunner.withUserConfiguration(CodecConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(WebTestClient.class); assertThat(context).hasSingleBean(CodecCustomizer.class); @@ -71,7 +71,7 @@ public class WebTestClientAutoConfigurationTests { } @Test - public void shouldCustomizeTimeout() { + void shouldCustomizeTimeout() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .withPropertyValues("spring.test.webtestclient.timeout=15m").run((context) -> { WebTestClient webTestClient = context.getBean(WebTestClient.class); @@ -82,7 +82,7 @@ public class WebTestClientAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void shouldApplySpringSecurityConfigurer() { + void shouldApplySpringSecurityConfigurer() { this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> { WebTestClient webTestClient = context.getBean(WebTestClient.class); WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, @@ -97,7 +97,7 @@ public class WebTestClientAutoConfigurationTests { @Test @SuppressWarnings("unchecked") - public void shouldNotApplySpringSecurityConfigurerWhenSpringSecurityNotOnClassPath() { + void shouldNotApplySpringSecurityConfigurerWhenSpringSecurityNotOnClassPath() { FilteredClassLoader classLoader = new FilteredClassLoader(SecurityMockServerConfigurers.class); this.contextRunner.withUserConfiguration(BaseConfiguration.class).withClassLoader(classLoader) .run((context) -> { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java index d6f8004b9ac..4be65ea48ab 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAllControllersIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; /** @@ -30,31 +28,30 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WithMockUser @WebFluxTest -public class WebFluxTestAllControllersIntegrationTests { +class WebFluxTestAllControllersIntegrationTests { @Autowired private WebTestClient webClient; @Test - public void shouldFindController1() { + void shouldFindController1() { this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test - public void shouldFindController2() { + void shouldFindController2() { this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("two"); } @Test - public void webExceptionHandling() { + void webExceptionHandling() { this.webClient.get().uri("/one/error").exchange().expectStatus().isBadRequest(); } @Test - public void shouldFindJsonController() { + void shouldFindJsonController() { this.webClient.get().uri("/json").exchange().expectStatus().isOk(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java index 4c3ae375a2a..2fab1ff8648 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration; @@ -28,7 +27,6 @@ import org.springframework.boot.autoconfigure.validation.ValidationAutoConfigura import org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration; @@ -40,40 +38,39 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * @author Artsiom Yudovin * @author Ali Dehghani */ -@RunWith(SpringRunner.class) @WebFluxTest -public class WebFluxTestAutoConfigurationIntegrationTests { +class WebFluxTestAutoConfigurationIntegrationTests { @Autowired private ApplicationContext applicationContext; @Test - public void messageSourceAutoConfigurationIsImported() { + void messageSourceAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(MessageSourceAutoConfiguration.class)); } @Test - public void validationAutoConfigurationIsImported() { + void validationAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(ValidationAutoConfiguration.class)); } @Test - public void mustacheAutoConfigurationIsImported() { + void mustacheAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class)); } @Test - public void freeMarkerAutoConfigurationIsImported() { + void freeMarkerAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); } @Test - public void thymeleafAutoConfigurationIsImported() { + void thymeleafAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); } @Test - public void errorWebFluxAutoConfigurationIsImported() { + void errorWebFluxAutoConfigurationIsImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(ErrorWebFluxAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java index dd9d0c59396..41b2184319b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java @@ -18,13 +18,11 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; import java.util.UUID; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; /** @@ -32,16 +30,15 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WithMockUser @WebFluxTest(controllers = ExampleController2.class) -public class WebFluxTestConverterIntegrationTests { +class WebFluxTestConverterIntegrationTests { @Autowired private WebTestClient webClient; @Test - public void shouldFindConverter() { + void shouldFindConverter() { UUID id = UUID.randomUUID(); this.webClient.get().uri("/two/" + id).exchange().expectStatus().isOk().expectBody(String.class) .isEqualTo(id + "two"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestMessageSourceIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestMessageSourceIntegrationTests.java index adb1830efc8..e8d5d68c0e6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestMessageSourceIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestMessageSourceIntegrationTests.java @@ -18,15 +18,13 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; import java.util.Locale; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -36,16 +34,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebFluxTest @TestPropertySource(properties = "spring.messages.basename=web-test-messages") -public class WebFluxTestMessageSourceIntegrationTests { +class WebFluxTestMessageSourceIntegrationTests { @Autowired private ApplicationContext context; @Test - public void messageSourceHasBeenAutoConfigured() { + void messageSourceHasBeenAutoConfigured() { assertThat(this.context.getMessage("a", null, Locale.ENGLISH)).isEqualTo("alpha"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java index e2e737f6046..4feb6387e31 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestOneControllerIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; /** @@ -30,21 +28,20 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WithMockUser @WebFluxTest(controllers = ExampleController1.class) -public class WebFluxTestOneControllerIntegrationTests { +class WebFluxTestOneControllerIntegrationTests { @Autowired private WebTestClient webClient; @Test - public void shouldFindController() { + void shouldFindController() { this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test - public void shouldNotScanOtherController() { + void shouldNotScanOtherController() { this.webClient.get().uri("/two").exchange().expectStatus().isNotFound(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java index 90107caf4e3..47b40fe65ff 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestWebTestClientCodecCustomizationIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; /** @@ -31,16 +29,15 @@ import org.springframework.test.web.reactive.server.WebTestClient; * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @WithMockUser @WebFluxTest(controllers = JsonController.class) -public class WebFluxTestWebTestClientCodecCustomizationIntegrationTests { +class WebFluxTestWebTestClientCodecCustomizationIntegrationTests { @Autowired private WebTestClient webClient; @Test - public void shouldBeAbleToCreatePojoViaParametersModule() { + void shouldBeAbleToCreatePojoViaParametersModule() { this.webClient.get().uri("/json").exchange().expectStatus().isOk().expectBody(ExamplePojo.class); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java index 1a3cc17b1c1..488a28a7522 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebTestClientSpringBootTestIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.web.reactive.webclient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; @@ -27,7 +26,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; @@ -39,11 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @SpringBootTest(properties = "spring.main.web-application-type=reactive", classes = { WebTestClientSpringBootTestIntegrationTests.TestConfiguration.class, ExampleWebFluxApplication.class }) @AutoConfigureWebTestClient -public class WebTestClientSpringBootTestIntegrationTests { +class WebTestClientSpringBootTestIntegrationTests { @Autowired private WebTestClient webClient; @@ -52,17 +49,17 @@ public class WebTestClientSpringBootTestIntegrationTests { private ApplicationContext applicationContext; @Test - public void shouldFindController1() { + void shouldFindController1() { this.webClient.get().uri("/one").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("one"); } @Test - public void shouldFindController2() { + void shouldFindController2() { this.webClient.get().uri("/two").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("two"); } @Test - public void shouldHaveRealService() { + void shouldHaveRealService() { assertThat(this.applicationContext.getBeansOfType(ExampleRealService.class)).hasSize(1); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java index ead392c780a..3ebf3c811e2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java @@ -15,7 +15,7 @@ */ package org.springframework.boot.test.autoconfigure.web.servlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; @@ -29,13 +29,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class MockMvcAutoConfigurationTests { +class MockMvcAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MockMvcAutoConfiguration.class)); @Test - public void registersDispatcherServletFromMockMvc() { + void registersDispatcherServletFromMockMvc() { this.contextRunner.run((context) -> { MockMvc mockMvc = context.getBean(MockMvc.class); assertThat(context).hasSingleBean(DispatcherServlet.class); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java index c811f261d03..8ce4b306ee5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java @@ -24,7 +24,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext; @@ -42,13 +42,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class SpringBootMockMvcBuilderCustomizerTests { +class SpringBootMockMvcBuilderCustomizerTests { private SpringBootMockMvcBuilderCustomizer customizer; @Test @SuppressWarnings("unchecked") - public void customizeShouldAddFilters() { + void customizeShouldAddFilters() { AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); MockServletContext servletContext = new MockServletContext(); context.setServletContext(servletContext); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java index bae24b6a6ae..52eac84b328 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java @@ -16,8 +16,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration; @@ -27,7 +26,6 @@ import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguratio import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.core.task.AsyncTaskExecutor; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; @@ -40,40 +38,39 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor * @author Andy Wilkinson * @author Levi Puot Paul */ -@RunWith(SpringRunner.class) @WebMvcTest -public class WebMvcTestAutoConfigurationIntegrationTests { +class WebMvcTestAutoConfigurationIntegrationTests { @Autowired private ApplicationContext applicationContext; @Test - public void freemarkerAutoConfigurationWasImported() { + void freemarkerAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class)); } @Test - public void groovyTemplatesAutoConfigurationWasImported() { + void groovyTemplatesAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class)); } @Test - public void mustacheAutoConfigurationWasImported() { + void mustacheAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class)); } @Test - public void thymeleafAutoConfigurationWasImported() { + void thymeleafAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class)); } @Test - public void taskExecutionAutoConfigurationWasImported() { + void taskExecutionAutoConfigurationWasImported() { assertThat(this.applicationContext).has(importedAutoConfiguration(TaskExecutionAutoConfiguration.class)); } @Test - public void asyncTaskExecutorWithApplicationTaskExecutor() { + void asyncTaskExecutorWithApplicationTaskExecutor() { assertThat(this.applicationContext.getBeansOfType(AsyncTaskExecutor.class)).hasSize(1); assertThat(ReflectionTestUtils.getField(this.applicationContext.getBean(RequestMappingHandlerAdapter.class), "taskExecutor")).isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPropertiesIntegrationTests.java index c0309c81083..12a8dcc6b76 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.servlet; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -31,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Artsiom Yudovin */ -@RunWith(SpringRunner.class) @WebMvcTest(properties = "spring.profiles.active=test") -public class WebMvcTestPropertiesIntegrationTests { +class WebMvcTestPropertiesIntegrationTests { @Autowired private Environment environment; @Test - public void environmentWithNewProfile() { + void environmentWithNewProfile() { assertThat(this.environment.getActiveProfiles()).containsExactly("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java index 08f585eb297..87553ac5224 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilterTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; @@ -40,12 +40,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class WebMvcTypeExcludeFilterTests { +class WebMvcTypeExcludeFilterTests { private MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); @Test - public void matchWhenHasNoControllers() throws Exception { + void matchWhenHasNoControllers() throws Exception { WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithNoControllers.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); @@ -58,7 +58,7 @@ public class WebMvcTypeExcludeFilterTests { } @Test - public void matchWhenHasController() throws Exception { + void matchWhenHasController() throws Exception { WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithController.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isTrue(); @@ -71,7 +71,7 @@ public class WebMvcTypeExcludeFilterTests { } @Test - public void matchNotUsingDefaultFilters() throws Exception { + void matchNotUsingDefaultFilters() throws Exception { WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(NotUsingDefaultFilters.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isTrue(); @@ -84,7 +84,7 @@ public class WebMvcTypeExcludeFilterTests { } @Test - public void matchWithIncludeFilter() throws Exception { + void matchWithIncludeFilter() throws Exception { WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithIncludeFilter.class); assertThat(excludes(filter, Controller1.class)).isFalse(); assertThat(excludes(filter, Controller2.class)).isFalse(); @@ -96,7 +96,7 @@ public class WebMvcTypeExcludeFilterTests { } @Test - public void matchWithExcludeFilter() throws Exception { + void matchWithExcludeFilter() throws Exception { WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithExcludeFilter.class); assertThat(excludes(filter, Controller1.class)).isTrue(); assertThat(excludes(filter, Controller2.class)).isFalse(); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java index de3f9f39f73..41cd87d24ec 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/MockMvcSpringBootTestIntegrationTests.java @@ -16,19 +16,18 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.ApplicationContext; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; @@ -42,14 +41,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc(print = MockMvcPrint.SYSTEM_ERR, printOnlyOnFailure = false) @WithMockUser(username = "user", password = "secret") -public class MockMvcSpringBootTestIntegrationTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class MockMvcSpringBootTestIntegrationTests { @MockBean private ExampleMockableService service; @@ -61,23 +57,23 @@ public class MockMvcSpringBootTestIntegrationTests { private MockMvc mvc; @Test - public void shouldFindController1() throws Exception { + void shouldFindController1(CapturedOutput capturedOutput) throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); - assertThat(this.output.toString()).contains("Request URI = /one"); + assertThat(capturedOutput).contains("Request URI = /one"); } @Test - public void shouldFindController2() throws Exception { + void shouldFindController2() throws Exception { this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test - public void shouldFindControllerAdvice() throws Exception { + void shouldFindControllerAdvice() throws Exception { this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test - public void shouldHaveRealService() { + void shouldHaveRealService() { assertThat(this.applicationContext.getBean(ExampleRealService.class)).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java index 6052e8e1f86..e1cd442ef87 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java @@ -18,14 +18,12 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import javax.validation.ConstraintViolationException; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.util.NestedServletException; @@ -41,10 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser -public class WebMvcTestAllControllersIntegrationTests { +class WebMvcTestAllControllersIntegrationTests { @Autowired private MockMvc mvc; @@ -53,34 +50,34 @@ public class WebMvcTestAllControllersIntegrationTests { private ErrorAttributes errorAttributes; @Test - public void shouldFindController1() throws Exception { + void shouldFindController1() throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); } @Test - public void shouldFindController2() throws Exception { + void shouldFindController2() throws Exception { this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } @Test - public void shouldFindControllerAdvice() throws Exception { + void shouldFindControllerAdvice() throws Exception { this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk()); } @Test - public void shouldRunValidationSuccess() throws Exception { + void shouldRunValidationSuccess() throws Exception { this.mvc.perform(get("/three/OK")).andExpect(status().isOk()).andExpect(content().string("Hello OK")); } @Test - public void shouldRunValidationFailure() throws Exception { + void shouldRunValidationFailure() throws Exception { assertThatExceptionOfType(NestedServletException.class) .isThrownBy(() -> this.mvc.perform(get("/three/invalid"))) .withCauseInstanceOf(ConstraintViolationException.class); } @Test - public void shouldNotFilterErrorAttributes() { + void shouldNotFilterErrorAttributes() { assertThat(this.errorAttributes).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java index bc28a4bd465..1a618ea4db2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestConverterIntegrationTests.java @@ -18,13 +18,11 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import java.util.UUID; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -36,16 +34,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebMvcTest(controllers = ExampleController2.class) @WithMockUser -public class WebMvcTestConverterIntegrationTests { +class WebMvcTestConverterIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldFindConverter() throws Exception { + void shouldFindConverter() throws Exception { String id = UUID.randomUUID().toString(); this.mvc.perform(get("/two/" + id)).andExpect(content().string(id + "two")).andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java index 8308056183a..fe1e30cc569 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,12 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.DispatcherServlet; @@ -36,18 +34,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser @TestPropertySource(properties = { "spring.mvc.throw-exception-if-no-handler-found=true", "spring.mvc.static-path-pattern=/static/**" }) -public class WebMvcTestCustomDispatcherServletIntegrationTests { +class WebMvcTestCustomDispatcherServletIntegrationTests { @Autowired private MockMvc mvc; @Test - public void dispatcherServletIsCustomized() throws Exception { + void dispatcherServletIsCustomized() throws Exception { this.mvc.perform(get("/does-not-exist")).andExpect(status().isBadRequest()) .andExpect(content().string("Invalid request: /does-not-exist")); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java index 6c582637c0c..28b4960172a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java @@ -16,14 +16,12 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.HttpHeaders; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -34,22 +32,21 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser -public class WebMvcTestHateoasIntegrationTests { +class WebMvcTestHateoasIntegrationTests { @Autowired private MockMvc mockMvc; @Test - public void plainResponse() throws Exception { + void plainResponse() throws Exception { this.mockMvc.perform(get("/hateoas/plain")) .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json")); } @Test - public void hateoasResponse() throws Exception { + void hateoasResponse() throws Exception { this.mockMvc.perform(get("/hateoas/resource")) .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8")); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestMessageSourceIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestMessageSourceIntegrationTests.java index 3f4964b035d..17107d44b24 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestMessageSourceIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestMessageSourceIntegrationTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import java.util.Locale; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -27,7 +26,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -37,17 +35,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser @TestPropertySource(properties = "spring.messages.basename=web-test-messages") -public class WebMvcTestMessageSourceIntegrationTests { +class WebMvcTestMessageSourceIntegrationTests { @Autowired private ApplicationContext context; @Test - public void messageSourceHasBeenAutoConfigured() { + void messageSourceHasBeenAutoConfigured() { assertThat(this.context.getMessage("a", null, Locale.ENGLISH)).isEqualTo("alpha"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java index f3bb39edd05..a458ea1e87c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestOneControllerIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -34,21 +32,20 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest(controllers = ExampleController2.class) @WithMockUser -public class WebMvcTestOneControllerIntegrationTests { +class WebMvcTestOneControllerIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldNotFindController1() throws Exception { + void shouldNotFindController1() throws Exception { this.mvc.perform(get("/one")).andExpect(status().isNotFound()); } @Test - public void shouldFindController2() throws Exception { + void shouldFindController2() throws Exception { this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java index c1d07293f3b..07754328ede 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java @@ -16,13 +16,11 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -34,16 +32,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser -public class WebMvcTestPageableIntegrationTests { +class WebMvcTestPageableIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldSupportPageable() throws Exception { + void shouldSupportPageable() throws Exception { this.mvc.perform(get("/paged").param("page", "2").param("size", "42")).andExpect(status().isOk()) .andExpect(content().string("2:42")); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java index 51f0914378a..b602dfe216b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java @@ -16,16 +16,15 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; @@ -38,22 +37,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser @AutoConfigureMockMvc(printOnlyOnFailure = false) -public class WebMvcTestPrintAlwaysIntegrationTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class WebMvcTestPrintAlwaysIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldPrint() throws Exception { + void shouldPrint(CapturedOutput capturedOutput) throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); - assertThat(this.output.toString()).contains("Request URI = /one"); + assertThat(capturedOutput).contains("Request URI = /one"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java index a49eb7b601c..94cdc5ece06 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java @@ -16,15 +16,23 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.engine.discovery.DiscoverySelectors; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -33,24 +41,58 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * Tests for {@link WebMvcTest @WebMvcTest} default print output. * * @author Phillip Webb + * @author Andy Wilkinson */ -@RunWith(WebMvcTestPrintDefaultRunner.class) -@WebMvcTest -@WithMockUser -@AutoConfigureMockMvc -public class WebMvcTestPrintDefaultIntegrationTests { - - @Autowired - private MockMvc mvc; +@ExtendWith(OutputCaptureExtension.class) +class WebMvcTestPrintDefaultIntegrationTests { @Test - public void shouldNotPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); + void shouldNotPrint(CapturedOutput capturedOutput) { + executeTests(ShouldNotPrint.class); + assertThat(capturedOutput).doesNotContain("HTTP Method"); } @Test - public void shouldPrint() throws Exception { - this.mvc.perform(get("/one")).andExpect(content().string("none")).andExpect(status().isOk()); + void shouldPrint(CapturedOutput capturedOutput) { + executeTests(ShouldPrint.class); + assertThat(capturedOutput).contains("HTTP Method"); + } + + private void executeTests(Class testClass) { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(DiscoverySelectors.selectClass(testClass)).build(); + Launcher launcher = LauncherFactory.create(); + launcher.execute(request); + } + + @WebMvcTest + @WithMockUser + @AutoConfigureMockMvc + static class ShouldNotPrint { + + @Autowired + private MockMvc mvc; + + @Test + void test() throws Exception { + this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); + } + + } + + @WebMvcTest + @WithMockUser + @AutoConfigureMockMvc + static class ShouldPrint { + + @Autowired + private MockMvc mvc; + + @Test + void test() throws Exception { + this.mvc.perform(get("/one")).andExpect(content().string("none")).andExpect(status().isOk()); + } + } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java index 44a7c3ca794..cab9476ef7a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultOverrideIntegrationTests.java @@ -16,16 +16,15 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.system.OutputCaptureRule; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; @@ -38,22 +37,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser @TestPropertySource(properties = "spring.test.mockmvc.print=NONE") -public class WebMvcTestPrintDefaultOverrideIntegrationTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class WebMvcTestPrintDefaultOverrideIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldFindController1() throws Exception { + void shouldFindController1(CapturedOutput capturedOutput) throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); - assertThat(this.output.toString()).doesNotContain("Request URI = /one"); + assertThat(capturedOutput).doesNotContain("Request URI = /one"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultRunner.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultRunner.java deleted file mode 100644 index be265207f06..00000000000 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultRunner.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; - -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -import org.springframework.boot.test.system.OutputCaptureRule; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; - -/** - * Test runner used for {@link WebMvcTestPrintDefaultIntegrationTests}. - * - * @author Phillip Webb - */ -public class WebMvcTestPrintDefaultRunner extends SpringJUnit4ClassRunner { - - public WebMvcTestPrintDefaultRunner(Class clazz) throws InitializationError { - super(clazz); - } - - @Override - protected Statement methodBlock(FrameworkMethod frameworkMethod) { - Statement statement = super.methodBlock(frameworkMethod); - statement = new AlwaysPassStatement(statement); - OutputCaptureRule outputCapture = new OutputCaptureRule(); - if (frameworkMethod.getName().equals("shouldPrint")) { - outputCapture.expect(containsString("HTTP Method")); - } - else if (frameworkMethod.getName().equals("shouldNotPrint")) { - outputCapture.expect(not(containsString("HTTP Method"))); - } - else { - throw new IllegalStateException("Unexpected test method"); - } - System.err.println(frameworkMethod.getName()); - return outputCapture.apply(statement, null); - } - - private static class AlwaysPassStatement extends Statement { - - private final Statement delegate; - - AlwaysPassStatement(Statement delegate) { - this.delegate = delegate; - } - - @Override - public void evaluate() throws Throwable { - try { - this.delegate.evaluate(); - } - catch (AssertionError ex) { - } - } - - } - -} diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java index f42f0f339b5..e3b28f74e47 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintOverrideIntegrationTests.java @@ -16,17 +16,16 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.rule.OutputCapture; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; @@ -39,22 +38,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser @AutoConfigureMockMvc(print = MockMvcPrint.NONE) -public class WebMvcTestPrintOverrideIntegrationTests { - - @Rule - public OutputCapture output = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class WebMvcTestPrintOverrideIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldNotPrint() throws Exception { + void shouldNotPrint(CapturedOutput capturedOutput) throws Exception { this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); - assertThat(this.output.toString()).doesNotContain("Request URI = /one"); + assertThat(capturedOutput).doesNotContain("Request URI = /one"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterIntegrationTests.java index e1caa324bb8..c4cc7d7825b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterIntegrationTests.java @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -32,15 +30,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest -public class WebMvcTestServletFilterIntegrationTests { +class WebMvcTestServletFilterIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldApplyFilter() throws Exception { + void shouldApplyFilter() throws Exception { this.mvc.perform(get("/one")).andExpect(header().string("x-test", "abc")); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java index 3a25352b28a..d01198abfcf 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestServletFilterRegistrationDisabledIntegrationTests.java @@ -16,15 +16,13 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -35,15 +33,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -@RunWith(SpringRunner.class) @WebMvcTest -public class WebMvcTestServletFilterRegistrationDisabledIntegrationTests { +class WebMvcTestServletFilterRegistrationDisabledIntegrationTests { @Autowired private MockMvc mvc; @Test - public void shouldNotApplyFilter() throws Exception { + void shouldNotApplyFilter() throws Exception { this.mvc.perform(get("/one")).andExpect(header().string("x-test", (String) null)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebClientIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebClientIntegrationTests.java index b1c1747e4ac..eec09dffa28 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebClientIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebClientIntegrationTests.java @@ -18,13 +18,11 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @@ -33,16 +31,15 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser -public class WebMvcTestWebClientIntegrationTests { +class WebMvcTestWebClientIntegrationTests { @Autowired private WebClient webClient; @Test - public void shouldAutoConfigureWebClient() throws Exception { + void shouldAutoConfigureWebClient() throws Exception { HtmlPage page = this.webClient.getPage("/html"); assertThat(page.getBody().getTextContent()).isEqualTo("Hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverCustomScopeIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverCustomScopeIntegrationTests.java index eeacd921141..f3d37a12855 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverCustomScopeIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverCustomScopeIntegrationTests.java @@ -16,10 +16,9 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; @@ -29,7 +28,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder; @@ -40,10 +38,9 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class WebMvcTestWebDriverCustomScopeIntegrationTests { +@TestMethodOrder(MethodOrderer.Alphanumeric.class) +class WebMvcTestWebDriverCustomScopeIntegrationTests { // gh-7454 @@ -53,12 +50,12 @@ public class WebMvcTestWebDriverCustomScopeIntegrationTests { private WebDriver webDriver; @Test - public void shouldAutoConfigureWebClient() { + void shouldAutoConfigureWebClient() { WebMvcTestWebDriverCustomScopeIntegrationTests.previousWebDriver = this.webDriver; } @Test - public void shouldBeTheSameWebClient() { + void shouldBeTheSameWebClient() { assertThat(previousWebDriver).isNotNull().isSameAs(this.webDriver); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java index 6d7727ee82d..9e9c341eb13 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java @@ -16,10 +16,9 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.WebDriver; @@ -28,7 +27,6 @@ import org.openqa.selenium.WebElement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -38,11 +36,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @WebMvcTest @WithMockUser -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class WebMvcTestWebDriverIntegrationTests { +@TestMethodOrder(MethodOrderer.Alphanumeric.class) +class WebMvcTestWebDriverIntegrationTests { private static WebDriver previousWebDriver; @@ -50,7 +47,7 @@ public class WebMvcTestWebDriverIntegrationTests { private WebDriver webDriver; @Test - public void shouldAutoConfigureWebClient() { + void shouldAutoConfigureWebClient() { this.webDriver.get("/html"); WebElement element = this.webDriver.findElement(By.tagName("body")); assertThat(element.getText()).isEqualTo("Hello"); @@ -58,7 +55,7 @@ public class WebMvcTestWebDriverIntegrationTests { } @Test - public void shouldBeADifferentWebClient() { + void shouldBeADifferentWebClient() { this.webDriver.get("/html"); WebElement element = this.webDriver.findElement(By.tagName("body")); assertThat(element.getText()).isEqualTo("Hello"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index 5588e1a9255..fb9851f3928 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -17,8 +17,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import com.gargoylesoftware.htmlunit.WebClient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -26,7 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -40,10 +38,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. * @author Phillip Webb * @author Stephane Nicoll */ -@RunWith(SpringRunner.class) @WebMvcTest @AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, webDriverEnabled = false) -public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { +class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Autowired private ApplicationContext context; @@ -52,18 +49,18 @@ public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { private MockMvc mvc; @Test - public void shouldNotAddFilters() throws Exception { + void shouldNotAddFilters() throws Exception { this.mvc.perform(get("/one")).andExpect(header().doesNotExist("x-test")); } @Test - public void shouldNotHaveWebDriver() { + void shouldNotHaveWebDriver() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(WebDriver.class)); } @Test - public void shouldNotHaveWebClient() { + void shouldNotHaveWebClient() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(WebClient.class)); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java index d99ea4fc862..0b8982805d1 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java @@ -21,7 +21,6 @@ import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.function.Consumer; @@ -143,11 +142,13 @@ class OutputCapture implements CapturedOutput { */ private static class SystemCapture { + private final Object monitor = new Object(); + private final PrintStreamCapture out; private final PrintStreamCapture err; - private final List capturedStrings = Collections.synchronizedList(new ArrayList<>()); + private final List capturedStrings = new ArrayList<>(); SystemCapture() { this.out = new PrintStreamCapture(System.out, this::captureOut); @@ -162,23 +163,31 @@ class OutputCapture implements CapturedOutput { } private void captureOut(String string) { - this.capturedStrings.add(new CapturedString(Type.OUT, string)); + synchronized (this.monitor) { + this.capturedStrings.add(new CapturedString(Type.OUT, string)); + } } private void captureErr(String string) { - this.capturedStrings.add(new CapturedString(Type.ERR, string)); + synchronized (this.monitor) { + this.capturedStrings.add(new CapturedString(Type.ERR, string)); + } } public void append(StringBuilder builder, Predicate filter) { - for (CapturedString stringCapture : this.capturedStrings) { - if (filter.test(stringCapture.getType())) { - builder.append(stringCapture); + synchronized (this.monitor) { + for (CapturedString stringCapture : this.capturedStrings) { + if (filter.test(stringCapture.getType())) { + builder.append(stringCapture); + } } } } public void reset() { - this.capturedStrings.clear(); + synchronized (this.monitor) { + this.capturedStrings.clear(); + } } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java index c2b16356c19..b6d1ad8d5da 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureRule.java @@ -36,7 +36,7 @@ import static org.hamcrest.Matchers.allOf; */ public class OutputCaptureRule implements TestRule { - private final org.springframework.boot.test.system.OutputCapture delegate = new org.springframework.boot.test.system.OutputCapture(); + private final OutputCapture delegate = new OutputCapture(); private List> matchers = new ArrayList<>(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java index c36d5d93850..b6e3aaad2cd 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { +abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { @LocalServerPort private int port = 0; @@ -64,25 +64,25 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests } @Test - public void runAndTestHttpEndpoint() { + void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build().get().uri("/").exchange() .expectBody(String.class).isEqualTo("Hello World"); } @Test - public void injectWebTestClient() { + void injectWebTestClient() { this.webClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World"); } @Test - public void injectTestRestTemplate() { + void injectTestRestTemplate() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } @Test - public void annotationAttributesOverridePropertiesFile() { + void annotationAttributesOverridePropertiesFile() { assertThat(this.value).isEqualTo(123); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java index 8b529972084..25d6ead68da 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestWebServerWebEnvironmentTests.java @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests { +abstract class AbstractSpringBootTestWebServerWebEnvironmentTests { @LocalServerPort private int port = 0; @@ -69,25 +69,25 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests { } @Test - public void runAndTestHttpEndpoint() { + void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class); assertThat(body).isEqualTo("Hello World"); } @Test - public void injectTestRestTemplate() { + void injectTestRestTemplate() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } @Test - public void annotationAttributesOverridePropertiesFile() { + void annotationAttributesOverridePropertiesFile() { assertThat(this.value).isEqualTo(123); } @Test - public void validateWebApplicationContextIsSet() { + void validateWebApplicationContextIsSet() { assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java index 6365bdf7984..02836265b35 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java @@ -30,36 +30,36 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class AnnotatedClassFinderTests { +class AnnotatedClassFinderTests { private AnnotatedClassFinder finder = new AnnotatedClassFinder(SpringBootConfiguration.class); @Test - public void findFromClassWhenSourceIsNullShouldThrowException() { + void findFromClassWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class) null)) .withMessageContaining("Source must not be null"); } @Test - public void findFromPackageWhenSourceIsNullShouldThrowException() { + void findFromPackageWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null)) .withMessageContaining("Source must not be null"); } @Test - public void findFromPackageWhenNoConfigurationFoundShouldReturnNull() { + void findFromPackageWhenNoConfigurationFoundShouldReturnNull() { Class config = this.finder.findFromPackage("org.springframework.boot"); assertThat(config).isNull(); } @Test - public void findFromClassWhenConfigurationIsFoundShouldReturnConfiguration() { + void findFromClassWhenConfigurationIsFoundShouldReturnConfiguration() { Class config = this.finder.findFromClass(Example.class); assertThat(config).isEqualTo(ExampleConfig.class); } @Test - public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() { + void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() { Class config = this.finder.findFromPackage("org.springframework.boot.test.context.example.scan"); assertThat(config).isEqualTo(ExampleConfig.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializerTests.java index 19a9ec33dc7..dcd9c7a07f6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ConfigFileApplicationContextInitializerTests.java @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @ContextConfiguration(classes = ConfigFileApplicationContextInitializerTests.Config.class, initializers = ConfigFileApplicationContextInitializer.class) -public class ConfigFileApplicationContextInitializerTests { +class ConfigFileApplicationContextInitializerTests { @Autowired private Environment environment; @Test - public void initializerPopulatesEnvironment() { + void initializerPopulatesEnvironment() { assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index 8d15d4dd135..d42a25d4aa9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Roy Jacobs */ -public class FilteredClassLoaderTests { +class FilteredClassLoaderTests { private static ClassPathResource TEST_RESOURCE = new ClassPathResource( "org/springframework/boot/test/context/FilteredClassLoaderTestsResource.txt"); @Test - public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception { + void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class.getPackage().getName())) { assertThatExceptionOfType(ClassNotFoundException.class) @@ -48,7 +48,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { + void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) { assertThatExceptionOfType(ClassNotFoundException.class) .isThrownBy(() -> classLoader.loadClass(getClass().getName())); @@ -56,7 +56,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadClassWhenNotFilteredShouldLoadClass() throws Exception { + void loadClassWhenNotFilteredShouldLoadClass() throws Exception { FilteredClassLoader classLoader = new FilteredClassLoader((className) -> false); Class loaded = classLoader.loadClass(getClass().getName()); assertThat(loaded.getName()).isEqualTo(getClass().getName()); @@ -64,7 +64,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourceWhenFilteredOnResourceShouldReturnNotFound() throws Exception { + void loadResourceWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath()); assertThat(loaded).isNull(); @@ -72,7 +72,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourceWhenNotFilteredShouldLoadResource() throws Exception { + void loadResourceWhenNotFilteredShouldLoadResource() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath()); assertThat(loaded).isNotNull(); @@ -80,7 +80,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() throws Exception { + void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { final Enumeration loaded = classLoader.getResources(TEST_RESOURCE.getPath()); assertThat(loaded.hasMoreElements()).isFalse(); @@ -88,7 +88,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourcesWhenNotFilteredShouldLoadResource() throws Exception { + void loadResourcesWhenNotFilteredShouldLoadResource() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { final Enumeration loaded = classLoader.getResources(TEST_RESOURCE.getPath()); assertThat(loaded.hasMoreElements()).isTrue(); @@ -96,7 +96,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() throws Exception { + void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) { final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath()); assertThat(loaded).isNull(); @@ -104,7 +104,7 @@ public class FilteredClassLoaderTests { } @Test - public void loadResourceAsStreamWhenNotFilteredShouldLoadResource() throws Exception { + void loadResourceAsStreamWhenNotFilteredShouldLoadResource() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) { final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath()); assertThat(loaded).isNotNull(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java index e5dbf9d5b31..a1ce41e80d4 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ @ExtendWith(SpringExtension.class) @Import(ImportedBean.class) -public class ImportsContextCustomizerFactoryIntegrationTests { +class ImportsContextCustomizerFactoryIntegrationTests { @Autowired private ApplicationContext context; @@ -47,12 +47,12 @@ public class ImportsContextCustomizerFactoryIntegrationTests { private ImportedBean bean; @Test - public void beanWasImported() { + void beanWasImported() { assertThat(this.bean).isNotNull(); } @Test - public void testItselfIsNotABean() { + void testItselfIsNotABean() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(getClass())); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index e31b7e537fe..91e4da864eb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -39,30 +39,30 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class ImportsContextCustomizerFactoryTests { +class ImportsContextCustomizerFactoryTests { private ImportsContextCustomizerFactory factory = new ImportsContextCustomizerFactory(); @Test - public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() { + void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() { ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null); assertThat(customizer).isNull(); } @Test - public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() { + void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); assertThat(customizer).isNotNull(); } @Test - public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() { + void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null); assertThat(customizer).isNotNull(); } @Test - public void contextCustomizerEqualsAndHashCode() { + void contextCustomizerEqualsAndHashCode() { ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null); ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null); ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null); @@ -75,14 +75,14 @@ public class ImportsContextCustomizerFactoryTests { } @Test - public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { + void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { assertThatIllegalStateException() .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) .withMessageContaining("Test classes cannot include @Bean methods"); } @Test - public void contextCustomizerImportsBeans() { + void contextCustomizerImportsBeans() { ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); customizer.customizeContext(context, mock(MergedContextConfiguration.class)); @@ -91,7 +91,7 @@ public class ImportsContextCustomizerFactoryTests { } @Test - public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { + void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null)) .isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java index f43c50dc13c..01f048b7d60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java @@ -40,34 +40,34 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ImportsContextCustomizerTests { +class ImportsContextCustomizerTests { @Test - public void importSelectorsCouldUseAnyAnnotations() { + void importSelectorsCouldUseAnyAnnotations() { assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class)) .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); } @Test - public void determinableImportSelector() { + void determinableImportSelector() { assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class)) .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); } @Test - public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { + void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class)) .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); } @Test - public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { + void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); } @Test - public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { + void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class)) .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java index ea12624ae86..510bad39db1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java @@ -50,7 +50,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DirtiesContext @ContextConfiguration(loader = SpringBootContextLoader.class) @WebAppConfiguration -public class SpringBootContextLoaderMockMvcTests { +class SpringBootContextLoaderMockMvcTests { @Autowired private WebApplicationContext context; @@ -66,12 +66,12 @@ public class SpringBootContextLoaderMockMvcTests { } @Test - public void testMockHttpEndpoint() throws Exception { + void testMockHttpEndpoint() throws Exception { this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } @Test - public void validateWebApplicationContextIsSet() { + void validateWebApplicationContextIsSet() { assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java index cccd2a3691c..624263dd4e8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java @@ -36,44 +36,44 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class SpringBootContextLoaderTests { +class SpringBootContextLoaderTests { @Test - public void environmentPropertiesSimple() { + void environmentPropertiesSimple() { Map config = getEnvironmentProperties(SimpleConfig.class); assertKey(config, "key", "myValue"); assertKey(config, "anotherKey", "anotherValue"); } @Test - public void environmentPropertiesSimpleNonAlias() { + void environmentPropertiesSimpleNonAlias() { Map config = getEnvironmentProperties(SimpleConfigNonAlias.class); assertKey(config, "key", "myValue"); assertKey(config, "anotherKey", "anotherValue"); } @Test - public void environmentPropertiesOverrideDefaults() { + void environmentPropertiesOverrideDefaults() { Map config = getEnvironmentProperties(OverrideConfig.class); assertKey(config, "server.port", "2345"); } @Test - public void environmentPropertiesAppend() { + void environmentPropertiesAppend() { Map config = getEnvironmentProperties(AppendConfig.class); assertKey(config, "key", "myValue"); assertKey(config, "otherKey", "otherValue"); } @Test - public void environmentPropertiesSeparatorInValue() { + void environmentPropertiesSeparatorInValue() { Map config = getEnvironmentProperties(SameSeparatorInValue.class); assertKey(config, "key", "my=Value"); assertKey(config, "anotherKey", "another:Value"); } @Test - public void environmentPropertiesAnotherSeparatorInValue() { + void environmentPropertiesAnotherSeparatorInValue() { Map config = getEnvironmentProperties(AnotherSeparatorInValue.class); assertKey(config, "key", "my:Value"); assertKey(config, "anotherKey", "another=Value"); @@ -81,7 +81,7 @@ public class SpringBootContextLoaderTests { @Test @Disabled - public void environmentPropertiesNewLineInValue() { + void environmentPropertiesNewLineInValue() { // gh-4384 Map config = getEnvironmentProperties(NewLineInValue.class); assertKey(config, "key", "myValue"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java index f6251bd130b..9e15cf12223 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestActiveProfileTests.java @@ -34,13 +34,13 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @SpringBootTest("spring.config.name=enableother") @ActiveProfiles("override") -public class SpringBootTestActiveProfileTests { +class SpringBootTestActiveProfileTests { @Autowired private ApplicationContext context; @Test - public void profiles() { + void profiles() { assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java index c8a0d8c469a..48d9b936ef4 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestArgsTests.java @@ -31,13 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @SpringBootTest(args = { "--option.foo=foo-value", "other.bar=other-bar-value" }) -public class SpringBootTestArgsTests { +class SpringBootTestArgsTests { @Autowired private ApplicationArguments args; @Test - public void applicationArgumentsPopulated() { + void applicationArgumentsPopulated() { assertThat(this.args.getOptionNames()).containsOnly("option.foo"); assertThat(this.args.getOptionValues("option.foo")).containsOnly("foo-value"); assertThat(this.args.getNonOptionArgs()).containsOnly("other.bar=other-bar-value"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestContextHierarchyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestContextHierarchyTests.java index 22e626f151a..ffcc9dcf278 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestContextHierarchyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestContextHierarchyTests.java @@ -34,10 +34,10 @@ import org.springframework.test.context.ContextHierarchy; @SpringBootTest @ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class), @ContextConfiguration(classes = ChildConfiguration.class) }) -public class SpringBootTestContextHierarchyTests { +class SpringBootTestContextHierarchyTests { @Test - public void contextLoads() { + void contextLoads() { } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomConfigNameTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomConfigNameTests.java index 021c5516428..00da22941db 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomConfigNameTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomConfigNameTests.java @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @SpringBootTest(properties = "spring.config.name=custom-config-name") -public class SpringBootTestCustomConfigNameTests { +class SpringBootTestCustomConfigNameTests { @Value("${test.foo}") private String foo; @Test - public void propertyIsLoadedFromConfigFileWithCustomName() { + void propertyIsLoadedFromConfigFileWithCustomName() { assertThat(this.foo).isEqualTo("bar"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomPortTests.java index 429226833c4..8357a780dbc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestCustomPortTests.java @@ -31,13 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @SpringBootTest(properties = "server.port=12345") -public class SpringBootTestCustomPortTests { +class SpringBootTestCustomPortTests { @Autowired private Environment environment; @Test - public void validatePortIsNotOverwritten() { + void validatePortIsNotOverwritten() { String port = this.environment.getProperty("server.port"); assertThat(port).isEqualTo("12345"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestDefaultConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestDefaultConfigurationTests.java index 573c78e49aa..edc762ab058 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestDefaultConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestDefaultConfigurationTests.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @DirtiesContext -public class SpringBootTestDefaultConfigurationTests { +class SpringBootTestDefaultConfigurationTests { @Autowired private Config config; @Test - public void nestedConfigClasses() { + void nestedConfigClasses() { assertThat(this.config).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConfigurationTests.java index 8ea7d8c0c9a..e3407bdab7f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConfigurationTests.java @@ -32,13 +32,13 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @SpringBootTest @ContextConfiguration(locations = "classpath:test.groovy") -public class SpringBootTestGroovyConfigurationTests { +class SpringBootTestGroovyConfigurationTests { @Autowired private String foo; @Test - public void groovyConfigLoaded() { + void groovyConfigLoaded() { assertThat(this.foo).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConventionConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConventionConfigurationTests.java index 51f819a5a55..4cf46860505 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConventionConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestGroovyConventionConfigurationTests.java @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest @DirtiesContext -public class SpringBootTestGroovyConventionConfigurationTests { +class SpringBootTestGroovyConventionConfigurationTests { @Autowired private String foo; @Test - public void groovyConfigLoaded() { + void groovyConfigLoaded() { assertThat(this.foo).isEqualTo("World"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestJmxTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestJmxTests.java index 60d9acdd6c8..2735aa1dc2c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestJmxTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestJmxTests.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest -public class SpringBootTestJmxTests { +class SpringBootTestJmxTests { @Value("${spring.jmx.enabled}") private boolean jmx; @Test - public void disabledByDefault() { + void disabledByDefault() { assertThat(this.jmx).isFalse(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestMixedConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestMixedConfigurationTests.java index eccc66789cf..fcbc42e0742 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestMixedConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestMixedConfigurationTests.java @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @SpringBootTest @ContextConfiguration(classes = Config.class, locations = "classpath:test.groovy") -public class SpringBootTestMixedConfigurationTests { +class SpringBootTestMixedConfigurationTests { @Autowired private String foo; @@ -43,7 +43,7 @@ public class SpringBootTestMixedConfigurationTests { private Config config; @Test - public void mixedConfigClasses() { + void mixedConfigClasses() { assertThat(this.foo).isNotNull(); assertThat(this.config).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java index 679747ec6cf..469db855545 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests.java @@ -37,11 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat; @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.main.web-application-type=reactive", "value=123" }) -public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests +class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTests extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { @Test - public void restTemplateIsUserDefined() { + void restTemplateIsUserDefined() { assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java index 421d3907b98..c8b7215d9d8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestUserDefinedTestRestTemplateTests.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { +class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Test - public void restTemplateIsUserDefined() { + void restTemplateIsUserDefined() { assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java index f5b4ee494be..60bbf6700c5 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentContextHierarchyTests.java @@ -45,13 +45,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" }) @ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class), @ContextConfiguration(classes = ChildConfiguration.class) }) -public class SpringBootTestWebEnvironmentContextHierarchyTests { +class SpringBootTestWebEnvironmentContextHierarchyTests { @Autowired private ApplicationContext context; @Test - public void testShouldOnlyStartSingleServer() { + void testShouldOnlyStartSingleServer() { ApplicationContext parent = this.context.getParent(); assertThat(this.context).isInstanceOf(WebApplicationContext.class); assertThat(parent).isNotInstanceOf(WebApplicationContext.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java index c9de8d0b648..6c3577aa168 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest("value=123") @DirtiesContext -public class SpringBootTestWebEnvironmentMockTests { +class SpringBootTestWebEnvironmentMockTests { @Value("${value}") private int value = 0; @@ -56,25 +56,25 @@ public class SpringBootTestWebEnvironmentMockTests { private ServletContext servletContext; @Test - public void annotationAttributesOverridePropertiesFile() { + void annotationAttributesOverridePropertiesFile() { assertThat(this.value).isEqualTo(123); } @Test - public void validateWebApplicationContextIsSet() { + void validateWebApplicationContextIsSet() { WebApplicationContext fromServletContext = WebApplicationContextUtils .getWebApplicationContext(this.servletContext); assertThat(fromServletContext).isSameAs(this.context); } @Test - public void setsRequestContextHolder() { + void setsRequestContextHolder() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); assertThat(attributes).isNotNull(); } @Test - public void resourcePath() { + void resourcePath() { assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/main/webapp"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java index d0cda0129ab..ba3ed36f034 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests.java @@ -41,13 +41,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @DirtiesContext @WebAppConfiguration("src/mymain/mywebapp") -public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests { +class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests { @Autowired private ServletContext servletContext; @Test - public void resourcePath() { + void resourcePath() { assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/mymain/mywebapp"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java index f81d0329f51..9745ea8dcba 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortCustomPortTests.java @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" }) -public class SpringBootTestWebEnvironmentRandomPortCustomPortTests { +class SpringBootTestWebEnvironmentRandomPortCustomPortTests { @Autowired private Environment environment; @Test - public void validatePortIsNotOverwritten() { + void validatePortIsNotOverwritten() { String port = this.environment.getProperty("server.port"); assertThat(port).isEqualTo("0"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java index 2b326609ca1..c7e09e5a0e1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java @@ -38,10 +38,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { +class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Test - public void testRestTemplateShouldUseBuilder() { + void testRestTemplateShouldUseBuilder() { assertThat(getRestTemplate().getRestTemplate().getMessageConverters()) .hasAtLeastOneElementOfType(MyConverter.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java index ea3bf4ac987..c2a32af3fbf 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java @@ -34,13 +34,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ @DirtiesContext @SpringBootTest(classes = SpringBootTestWithClassesIntegrationTests.Config.class) -public class SpringBootTestWithClassesIntegrationTests { +class SpringBootTestWithClassesIntegrationTests { @Autowired private ApplicationContext context; @Test - public void injectsOnlyConfig() { + void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index 446a1d2d030..a52fd7b8311 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @DirtiesContext @SpringBootTest @ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) -public class SpringBootTestWithContextConfigurationIntegrationTests { +class SpringBootTestWithContextConfigurationIntegrationTests { @Autowired private ApplicationContext context; @Test - public void injectsOnlyConfig() { + void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java index 20945e3e1c1..c0fba0bdceb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java @@ -42,39 +42,39 @@ import static org.assertj.core.api.Assertions.assertThat; @TestPropertySource( properties = { "property-source-inlined=bar", "a=property-source-inlined", "c=property-source-inlined" }, locations = "classpath:/test-property-source-annotation.properties") -public class SpringBootTestWithTestPropertySourceTests { +class SpringBootTestWithTestPropertySourceTests { @Autowired private Config config; @Test - public void propertyFromSpringBootTestProperties() { + void propertyFromSpringBootTestProperties() { assertThat(this.config.bootTestInlined).isEqualTo("foo"); } @Test - public void propertyFromTestPropertySourceProperties() { + void propertyFromTestPropertySourceProperties() { assertThat(this.config.propertySourceInlined).isEqualTo("bar"); } @Test - public void propertyFromTestPropertySourceLocations() { + void propertyFromTestPropertySourceLocations() { assertThat(this.config.propertySourceLocation).isEqualTo("baz"); } @Test - public void propertyFromPropertySourcePropertiesOverridesPropertyFromPropertySourceLocations() { + void propertyFromPropertySourcePropertiesOverridesPropertyFromPropertySourceLocations() { assertThat(this.config.propertySourceInlinedOverridesPropertySourceLocation) .isEqualTo("property-source-inlined"); } @Test - public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() { + void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() { assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation).isEqualTo("boot-test-inlined"); } @Test - public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() { + void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() { assertThat(this.config.propertySourceInlinedOverridesBootTestInlined).isEqualTo("property-source-inlined"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestXmlConventionConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestXmlConventionConfigurationTests.java index c5d76d362b1..2006824a3c7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestXmlConventionConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestXmlConventionConfigurationTests.java @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @DirtiesContext @SpringBootTest -public class SpringBootTestXmlConventionConfigurationTests { +class SpringBootTestXmlConventionConfigurationTests { @Autowired private String foo; @Test - public void xmlConfigLoaded() { + void xmlConfigLoaded() { assertThat(this.foo).isEqualTo("World"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java index f7c17ea6d84..d5a651ebbe1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ApplicationContextAssertProviderTests { +class ApplicationContextAssertProviderTests { @Mock private ConfigurableApplicationContext mockContext; @@ -60,21 +60,21 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getWhenTypeIsNullShouldThrowException() { + void getWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("Type must not be null"); } @Test - public void getWhenTypeIsClassShouldThrowException() { + void getWhenTypeIsClassShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("Type must not be null"); } @Test - public void getWhenContextTypeIsNullShouldThrowException() { + void getWhenContextTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, ApplicationContext.class, this.mockContextSupplier)) @@ -82,14 +82,14 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getWhenContextTypeIsClassShouldThrowException() { + void getWhenContextTypeIsClassShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider .get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier)) .withMessageContaining("ContextType must not be null"); } @Test - public void getWhenSupplierIsNullShouldThrowException() { + void getWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, StaticApplicationContext.class, this.mockContextSupplier)) @@ -97,7 +97,7 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() { + void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat((Object) context).isNotNull(); context.getBean("foo"); @@ -105,7 +105,7 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { + void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure) @@ -113,26 +113,26 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getSourceContextWhenContextStartsShouldReturnSourceContext() { + void getSourceContextWhenContextStartsShouldReturnSourceContext() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext); } @Test - public void getSourceContextWhenContextFailsShouldThrowException() { + void getSourceContextWhenContextFailsShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext) .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test - public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() { + void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext); } @Test - public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { + void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException() .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) @@ -140,19 +140,19 @@ public class ApplicationContextAssertProviderTests { } @Test - public void getStartupFailureWhenContextStartsShouldReturnNull() { + void getStartupFailureWhenContextStartsShouldReturnNull() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.getStartupFailure()).isNull(); } @Test - public void getStartupFailureWhenContextFailsToStartShouldReturnException() { + void getStartupFailureWhenContextFailsToStartShouldReturnException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure); } @Test - public void assertThatWhenContextStartsShouldReturnAssertions() { + void assertThatWhenContextStartsShouldReturnAssertions() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); ApplicationContextAssert contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); @@ -160,7 +160,7 @@ public class ApplicationContextAssertProviderTests { } @Test - public void assertThatWhenContextFailsShouldReturnAssertions() { + void assertThatWhenContextFailsShouldReturnAssertions() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); ApplicationContextAssert contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); @@ -168,21 +168,21 @@ public class ApplicationContextAssertProviderTests { } @Test - public void toStringWhenContextStartsShouldReturnSimpleString() { + void toStringWhenContextStartsShouldReturnSimpleString() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock") .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); } @Test - public void toStringWhenContextFailsToStartShouldReturnSimpleString() { + void toStringWhenContextFailsToStartShouldReturnSimpleString() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat(context.toString()).isEqualTo("Unstarted application context " + "org.springframework.context.ApplicationContext" + "[startupFailure=java.lang.RuntimeException]"); } @Test - public void closeShouldCloseContext() { + void closeShouldCloseContext() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); context.close(); verify(this.mockContext).close(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java index f980e299f94..8fa6ca0e214 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Andy Wilkinson */ -public class ApplicationContextAssertTests { +class ApplicationContextAssertTests { private StaticApplicationContext parent; @@ -60,56 +60,56 @@ public class ApplicationContextAssertTests { } @Test - public void createWhenApplicationContextIsNullShouldThrowException() { + void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null)) .withMessageContaining("ApplicationContext must not be null"); } @Test - public void createWhenHasApplicationContextShouldSetActual() { + void createWhenHasApplicationContextShouldSetActual() { assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context); } @Test - public void createWhenHasExceptionShouldSetFailure() { + void createWhenHasExceptionShouldSetFailure() { assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure); } @Test - public void hasBeanWhenHasBeanShouldPass() { + void hasBeanWhenHasBeanShouldPass() { this.context.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).hasBean("foo"); } @Test - public void hasBeanWhenHasNoBeanShouldFail() { + void hasBeanWhenHasNoBeanShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) .withMessageContaining("no such bean"); } @Test - public void hasBeanWhenNotStartedShouldFail() { + void hasBeanWhenNotStartedShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test - public void hasSingleBeanWhenHasSingleBeanShouldPass() { + void hasSingleBeanWhenHasSingleBeanShouldPass() { this.context.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).hasSingleBean(Foo.class); } @Test - public void hasSingleBeanWhenHasNoBeansShouldFail() { + void hasSingleBeanWhenHasNoBeansShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) .withMessageContaining("to have a single bean of type"); } @Test - public void hasSingleBeanWhenHasMultipleShouldFail() { + void hasSingleBeanWhenHasMultipleShouldFail() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) @@ -118,7 +118,7 @@ public class ApplicationContextAssertTests { } @Test - public void hasSingleBeanWhenFailedToStartShouldFail() { + void hasSingleBeanWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) .withMessageContaining("to have a single bean of type") @@ -126,7 +126,7 @@ public class ApplicationContextAssertTests { } @Test - public void hasSingleBeanWhenInParentShouldFail() { + void hasSingleBeanWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) @@ -135,19 +135,19 @@ public class ApplicationContextAssertTests { } @Test - public void hasSingleBeanWithLimitedScopeWhenInParentShouldPass() { + void hasSingleBeanWithLimitedScopeWhenInParentShouldPass() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).hasSingleBean(Foo.class, Scope.NO_ANCESTORS); } @Test - public void doesNotHaveBeanOfTypeWhenHasNoBeanOfTypeShouldPass() { + void doesNotHaveBeanOfTypeWhenHasNoBeanOfTypeShouldPass() { assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class); } @Test - public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { + void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) @@ -155,7 +155,7 @@ public class ApplicationContextAssertTests { } @Test - public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { + void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) .withMessageContaining("not to have any beans of type") @@ -163,7 +163,7 @@ public class ApplicationContextAssertTests { } @Test - public void doesNotHaveBeanOfTypeWhenInParentShouldFail() { + void doesNotHaveBeanOfTypeWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) @@ -171,18 +171,18 @@ public class ApplicationContextAssertTests { } @Test - public void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() { + void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() { this.parent.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS); } @Test - public void doesNotHaveBeanOfNameWhenHasNoBeanOfTypeShouldPass() { + void doesNotHaveBeanOfNameWhenHasNoBeanOfTypeShouldPass() { assertThat(getAssert(this.context)).doesNotHaveBean("foo"); } @Test - public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { + void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) @@ -190,26 +190,26 @@ public class ApplicationContextAssertTests { } @Test - public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { + void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) .withMessageContaining("not to have any beans of name").withMessageContaining("failed to start"); } @Test - public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() { + void getBeanNamesWhenHasNamesShouldReturnNamesAssert() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", "bar"); } @Test - public void getBeanNamesWhenHasNoNamesShouldReturnEmptyAssert() { + void getBeanNamesWhenHasNoNamesShouldReturnEmptyAssert() { assertThat(getAssert(this.context)).getBeanNames(Foo.class).isEmpty(); } @Test - public void getBeanNamesWhenFailedToStartShouldFail() { + void getBeanNamesWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) .withMessageContaining("not to have any beans of name") @@ -217,18 +217,18 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfTypeWhenHasBeanShouldReturnBeanAssert() { + void getBeanOfTypeWhenHasBeanShouldReturnBeanAssert() { this.context.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).getBean(Foo.class).isNotNull(); } @Test - public void getBeanOfTypeWhenHasNoBeanShouldReturnNullAssert() { + void getBeanOfTypeWhenHasNoBeanShouldReturnNullAssert() { assertThat(getAssert(this.context)).getBean(Foo.class).isNull(); } @Test - public void getBeanOfTypeWhenHasMultipleBeansShouldFail() { + void getBeanOfTypeWhenHasMultipleBeansShouldFail() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) @@ -237,14 +237,14 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() { + void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrimaryFooConfig.class); assertThat(getAssert(context)).getBean(Foo.class).isInstanceOf(Bar.class); context.close(); } @Test - public void getBeanOfTypeWhenFailedToStartShouldFail() { + void getBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) .withMessageContaining("to contain bean of type") @@ -252,19 +252,19 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfTypeWhenInParentShouldReturnBeanAssert() { + void getBeanOfTypeWhenInParentShouldReturnBeanAssert() { this.parent.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).getBean(Foo.class).isNotNull(); } @Test - public void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() { + void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() { this.parent.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNull(); } @Test - public void getBeanOfTypeWhenHasMultipleBeansIncludingParentShouldFail() { + void getBeanOfTypeWhenHasMultipleBeansIncludingParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) @@ -273,25 +273,25 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() { + void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNotNull(); } @Test - public void getBeanOfNameWhenHasBeanShouldReturnBeanAssert() { + void getBeanOfNameWhenHasBeanShouldReturnBeanAssert() { this.context.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).getBean("foo").isNotNull(); } @Test - public void getBeanOfNameWhenHasNoBeanOfNameShouldReturnNullAssert() { + void getBeanOfNameWhenHasNoBeanOfNameShouldReturnNullAssert() { assertThat(getAssert(this.context)).getBean("foo").isNull(); } @Test - public void getBeanOfNameWhenFailedToStartShouldFail() { + void getBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) .withMessageContaining("to contain a bean of name") @@ -299,18 +299,18 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfNameAndTypeWhenHasBeanShouldReturnBeanAssert() { + void getBeanOfNameAndTypeWhenHasBeanShouldReturnBeanAssert() { this.context.registerSingleton("foo", Foo.class); assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNotNull(); } @Test - public void getBeanOfNameAndTypeWhenHasNoBeanOfNameShouldReturnNullAssert() { + void getBeanOfNameAndTypeWhenHasNoBeanOfNameShouldReturnNullAssert() { assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNull(); } @Test - public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { + void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) @@ -318,7 +318,7 @@ public class ApplicationContextAssertTests { } @Test - public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { + void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) .withMessageContaining("to contain a bean of name") @@ -326,19 +326,19 @@ public class ApplicationContextAssertTests { } @Test - public void getBeansWhenHasBeansShouldReturnMapAssert() { + void getBeansWhenHasBeansShouldReturnMapAssert() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar"); } @Test - public void getBeansWhenHasNoBeansShouldReturnEmptyMapAssert() { + void getBeansWhenHasNoBeansShouldReturnEmptyMapAssert() { assertThat(getAssert(this.context)).getBeans(Foo.class).isEmpty(); } @Test - public void getBeansWhenFailedToStartShouldFail() { + void getBeansWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) .withMessageContaining("to get beans of type") @@ -346,45 +346,45 @@ public class ApplicationContextAssertTests { } @Test - public void getBeansShouldIncludeBeansFromParentScope() { + void getBeansShouldIncludeBeansFromParentScope() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar"); } @Test - public void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() { + void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS).hasSize(1).containsKeys("bar"); } @Test - public void getFailureWhenFailedShouldReturnFailure() { + void getFailureWhenFailedShouldReturnFailure() { assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure); } @Test - public void getFailureWhenDidNotFailShouldFail() { + void getFailureWhenDidNotFailShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) .withMessageContaining("context started"); } @Test - public void hasFailedWhenFailedShouldPass() { + void hasFailedWhenFailedShouldPass() { assertThat(getAssert(this.failure)).hasFailed(); } @Test - public void hasFailedWhenNotFailedShouldFail() { + void hasFailedWhenNotFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) .withMessageContaining("to have failed"); } @Test - public void hasNotFailedWhenFailedShouldFail() { + void hasNotFailedWhenFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) .withMessageContaining("to have not failed") @@ -392,7 +392,7 @@ public class ApplicationContextAssertTests { } @Test - public void hasNotFailedWhenNotFailedShouldPass() { + void hasNotFailedWhenNotFailedShouldPass() { assertThat(getAssert(this.context)).hasNotFailed(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java index 61128fcb973..7ab204f96fa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @see ApplicationContextAssertProviderTests */ -public class AssertableApplicationContextTests { +class AssertableApplicationContextTests { @Test - public void getShouldReturnProxy() { + void getShouldReturnProxy() { AssertableApplicationContext context = AssertableApplicationContext .get(() -> mock(ConfigurableApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableApplicationContext.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java index d9600c99452..8e84cbf9b0d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @see ApplicationContextAssertProviderTests */ -public class AssertableReactiveWebApplicationContextTests { +class AssertableReactiveWebApplicationContextTests { @Test - public void getShouldReturnProxy() { + void getShouldReturnProxy() { AssertableReactiveWebApplicationContext context = AssertableReactiveWebApplicationContext .get(() -> mock(ConfigurableReactiveWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableReactiveWebApplicationContext.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java index c30d2b345e3..2387d7f4198 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @see ApplicationContextAssertProviderTests */ -public class AssertableWebApplicationContextTests { +class AssertableWebApplicationContextTests { @Test - public void getShouldReturnProxy() { + void getShouldReturnProxy() { AssertableWebApplicationContext context = AssertableWebApplicationContext .get(() -> mock(ConfigurableWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableWebApplicationContext.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java index b7baac07130..7111268cd19 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperIntegrationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @BootstrapWith(SpringBootTestContextBootstrapper.class) -public class SpringBootTestContextBootstrapperIntegrationTests { +class SpringBootTestContextBootstrapperIntegrationTests { @Autowired private ApplicationContext context; @@ -48,22 +48,22 @@ public class SpringBootTestContextBootstrapperIntegrationTests { boolean defaultTestExecutionListenersPostProcessorCalled = false; @Test - public void findConfigAutomatically() { + void findConfigAutomatically() { assertThat(this.config).isNotNull(); } @Test - public void contextWasCreatedViaSpringApplication() { + void contextWasCreatedViaSpringApplication() { assertThat(this.context.getId()).startsWith("application"); } @Test - public void testConfigurationWasApplied() { + void testConfigurationWasApplied() { assertThat(this.context.getBean(ExampleBean.class)).isNotNull(); } @Test - public void defaultTestExecutionListenersPostProcessorShouldBeCalled() { + void defaultTestExecutionListenersPostProcessorShouldBeCalled() { assertThat(this.defaultTestExecutionListenersPostProcessorCalled).isTrue(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index 64d1e33ad70..ff95793d0a4 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -34,10 +34,10 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class SpringBootTestContextBootstrapperTests { +class SpringBootTestContextBootstrapperTests { @Test - public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { + void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { assertThatIllegalStateException() .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) .withMessageContaining("@WebAppConfiguration should only be used with " @@ -46,7 +46,7 @@ public class SpringBootTestContextBootstrapperTests { } @Test - public void springBootTestWithAMockWebEnvironmentCanBeUsedWithWebAppConfiguration() { + void springBootTestWithAMockWebEnvironmentCanBeUsedWithWebAppConfiguration() { buildTestContext(SpringBootTestMockWebEnvironmentAndWebAppConfiguration.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithContextConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithContextConfigurationTests.java index 04bcf0053f5..ff981020205 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithContextConfigurationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @BootstrapWith(SpringBootTestContextBootstrapper.class) @ContextConfiguration -public class SpringBootTestContextBootstrapperWithContextConfigurationTests { +class SpringBootTestContextBootstrapperWithContextConfigurationTests { @Autowired private ApplicationContext context; @@ -46,12 +46,12 @@ public class SpringBootTestContextBootstrapperWithContextConfigurationTests { private SpringBootTestContextBootstrapperExampleConfig config; @Test - public void findConfigAutomatically() { + void findConfigAutomatically() { assertThat(this.config).isNotNull(); } @Test - public void contextWasCreatedViaSpringApplication() { + void contextWasCreatedViaSpringApplication() { assertThat(this.context.getId()).startsWith("application"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java index 1ef87351b57..652714e5dc9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperWithInitializersTests.java @@ -40,13 +40,13 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @BootstrapWith(SpringBootTestContextBootstrapper.class) @ContextConfiguration(initializers = CustomInitializer.class) -public class SpringBootTestContextBootstrapperWithInitializersTests { +class SpringBootTestContextBootstrapperWithInitializersTests { @Autowired private ApplicationContext context; @Test - public void foundConfiguration() { + void foundConfiguration() { Object bean = this.context.getBean(SpringBootTestContextBootstrapperExampleConfig.class); assertThat(bean).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/ExampleConfig.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/ExampleConfig.java index efad3b89ba6..4364d052a6a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/ExampleConfig.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/ExampleConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,9 @@ package org.springframework.boot.test.context.example; import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.test.context.AnnotatedClassFinderTests; /** - * Example config used in {@link AnnotatedClassFinderTests}. + * Example config used in {@code AnnotatedClassFinderTests}. * * @author Phillip Webb */ diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/Example.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/Example.java index af5edb4b4d5..ba4854f95f2 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/Example.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/Example.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,8 @@ package org.springframework.boot.test.context.example.scan; -import org.springframework.boot.test.context.AnnotatedClassFinderTests; - /** - * Example class used in {@link AnnotatedClassFinderTests}. + * Example class used in {@code AnnotatedClassFinderTests}. * * @author Phillip Webb */ diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/sub/SubExampleConfig.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/sub/SubExampleConfig.java index 55ef0d0e2a7..30253f570cc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/sub/SubExampleConfig.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/example/scan/sub/SubExampleConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,9 @@ package org.springframework.boot.test.context.example.scan.sub; import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.test.context.AnnotatedClassFinderTests; /** - * Example config used in {@link AnnotatedClassFinderTests}. Should not be found since + * Example config used in {@code AnnotatedClassFinderTests}. Should not be found since * scanner should only search upwards. * * @author Phillip Webb diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterRepeatedTestExample.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterRepeatedTestExample.java index d5e9e034615..0df9e75d1c6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterRepeatedTestExample.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterRepeatedTestExample.java @@ -18,10 +18,10 @@ package org.springframework.boot.test.context.filter; import org.junit.jupiter.api.RepeatedTest; -public class JupiterRepeatedTestExample { +class JupiterRepeatedTestExample { @RepeatedTest(5) - public void repeatedTest() { + void repeatedTest() { } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestExample.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestExample.java index 1d2073dbf6e..fa3632aadaa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestExample.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestExample.java @@ -18,10 +18,10 @@ package org.springframework.boot.test.context.filter; import org.junit.jupiter.api.Test; -public class JupiterTestExample { +class JupiterTestExample { @Test - public void repeatedTest() { + void repeatedTest() { } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestFactoryExample.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestFactoryExample.java index ca29ab0261d..2f5f04bbb61 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestFactoryExample.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/JupiterTestFactoryExample.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.DynamicNode; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; -public class JupiterTestFactoryExample { +class JupiterTestFactoryExample { @TestFactory - public Collection testFactory() { + Collection testFactory() { return Arrays.asList(DynamicTest.dynamicTest("Some dynamic test", () -> { // Test })); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java index e02e786d34c..8cef961b7e1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java @@ -33,64 +33,64 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class TestTypeExcludeFilterTests { +class TestTypeExcludeFilterTests { private TestTypeExcludeFilter filter = new TestTypeExcludeFilter(); private MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); @Test - public void matchesJUnit4TestClass() throws Exception { + void matchesJUnit4TestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory)) .isTrue(); } @Test - public void matchesJUnitJupiterTestClass() throws Exception { + void matchesJUnitJupiterTestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesJUnitJupiterRepeatedTestClass() throws Exception { + void matchesJUnitJupiterRepeatedTestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory)) .isTrue(); } @Test - public void matchesJUnitJupiterTestFactoryClass() throws Exception { + void matchesJUnitJupiterTestFactoryClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory)) .isTrue(); } @Test - public void matchesNestedConfiguration() throws Exception { + void matchesNestedConfiguration() throws Exception { assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { + void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception { + void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class), this.metadataReaderFactory)).isTrue(); } @Test - public void matchesTestConfiguration() throws Exception { + void matchesTestConfiguration() throws Exception { assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue(); } @Test - public void doesNotMatchRegularConfiguration() throws Exception { + void doesNotMatchRegularConfiguration() throws Exception { assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse(); } @Test - public void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception { + void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class), this.metadataReaderFactory)).isTrue(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java index 329ed7bff45..b49dc873e8c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java @@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThatIOException; * @author Stephane Nicoll * @author Phillip Webb */ -public abstract class AbstractApplicationContextRunnerTests, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider> { +abstract class AbstractApplicationContextRunnerTests, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider> { @Test - public void runWithInitializerShouldInitialize() { + void runWithInitializerShouldInitialize() { AtomicBoolean called = new AtomicBoolean(); get().withInitializer((context) -> called.set(true)).run((context) -> { }); @@ -60,7 +60,7 @@ public abstract class AbstractApplicationContextRunnerTests { Environment environment = context.getEnvironment(); assertThat(environment.getProperty("test.foo")).isEqualTo("1"); @@ -117,7 +117,7 @@ public abstract class AbstractApplicationContextRunnerTests { Environment environment = context.getEnvironment(); assertThat(environment.getProperty("test.foo")).isEqualTo("2"); @@ -125,22 +125,22 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(context).hasBean("foo")); } @Test - public void runWithUserNamedBeanShouldRegisterBean() { + void runWithUserNamedBeanShouldRegisterBean() { get().withBean("foo", String.class, () -> "foo").run((context) -> assertThat(context).hasBean("foo")); } @Test - public void runWithUserBeanShouldRegisterBeanWithDefaultName() { + void runWithUserBeanShouldRegisterBeanWithDefaultName() { get().withBean(String.class, () -> "foo").run((context) -> assertThat(context).hasBean("string")); } @Test - public void runWithUserBeanShouldBeRegisteredInOrder() { + void runWithUserBeanShouldBeRegisteredInOrder() { get().withBean(String.class, () -> "one").withBean(String.class, () -> "two") .withBean(String.class, () -> "three").run((context) -> { assertThat(context).hasBean("string"); @@ -149,7 +149,7 @@ public abstract class AbstractApplicationContextRunnerTests "overridden") .run((context) -> { assertThat(context).hasBean("foo"); @@ -158,32 +158,32 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(context).hasBean("foo").hasBean("bar")); } @Test - public void runWithFailedContextShouldReturnFailedAssertableContext() { + void runWithFailedContextShouldReturnFailedAssertableContext() { get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed()); } @Test - public void runWithClassLoaderShouldSetClassLoaderOnContext() { + void runWithClassLoaderShouldSetClassLoaderOnContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) .run((context) -> assertThatExceptionOfType(ClassNotFoundException.class) .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); } @Test - public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() { + void runWithClassLoaderShouldSetClassLoaderOnConditionContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) .withUserConfiguration(ConditionalConfig.class) .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); } @Test - public void thrownRuleWorksWithCheckedException() { + void thrownRuleWorksWithCheckedException() { get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message")) .withMessageContaining("Expected message")); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java index b8c3ee54280..edf448ff07b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/WebApplicationContextRunnerTests.java @@ -30,11 +30,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Phillip Webb */ -public class WebApplicationContextRunnerTests extends +class WebApplicationContextRunnerTests extends AbstractApplicationContextRunnerTests { @Test - public void contextShouldHaveMockServletContext() { + void contextShouldHaveMockServletContext() { get().run((context) -> assertThat(context.getServletContext()).isInstanceOf(MockServletContext.class)); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index 225b956955f..8762a000f69 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public abstract class AbstractJsonMarshalTesterTests { +abstract class AbstractJsonMarshalTesterTests { private static final String JSON = "{\"name\":\"Spring\",\"age\":123}"; @@ -58,13 +58,13 @@ public abstract class AbstractJsonMarshalTesterTests { private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test - public void writeShouldReturnJsonContent() throws Exception { + void writeShouldReturnJsonContent() throws Exception { JsonContent content = createTester(TYPE).write(OBJECT); assertThat(content).isEqualToJson(JSON); } @Test - public void writeListShouldReturnJsonContent() throws Exception { + void writeListShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); List value = Collections.singletonList(OBJECT); JsonContent content = createTester(type).write(value); @@ -72,7 +72,7 @@ public abstract class AbstractJsonMarshalTesterTests { } @Test - public void writeArrayShouldReturnJsonContent() throws Exception { + void writeArrayShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); ExampleObject[] value = new ExampleObject[] { OBJECT }; JsonContent content = createTester(type).write(value); @@ -80,7 +80,7 @@ public abstract class AbstractJsonMarshalTesterTests { } @Test - public void writeMapShouldReturnJsonContent() throws Exception { + void writeMapShouldReturnJsonContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); Map value = new LinkedHashMap<>(); value.put("a", OBJECT); @@ -89,38 +89,38 @@ public abstract class AbstractJsonMarshalTesterTests { } @Test - public void createWhenResourceLoadClassIsNullShouldThrowException() { + void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) .withMessageContaining("ResourceLoadClass must not be null"); } @Test - public void createWhenTypeIsNullShouldThrowException() { + void createWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null)) .withMessageContaining("Type must not be null"); } @Test - public void parseBytesShouldReturnObject() throws Exception { + void parseBytesShouldReturnObject() throws Exception { AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.parse(JSON.getBytes())).isEqualTo(OBJECT); } @Test - public void parseStringShouldReturnObject() throws Exception { + void parseStringShouldReturnObject() throws Exception { AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.parse(JSON)).isEqualTo(OBJECT); } @Test - public void readResourcePathShouldReturnObject() throws Exception { + void readResourcePathShouldReturnObject() throws Exception { AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.read("example.json")).isEqualTo(OBJECT); } @Test - public void readFileShouldReturnObject(@TempDir Path temp) throws Exception { + void readFileShouldReturnObject(@TempDir Path temp) throws Exception { File file = new File(temp.toFile(), "example.json"); FileCopyUtils.copy(JSON.getBytes(), file); AbstractJsonMarshalTester tester = createTester(TYPE); @@ -128,42 +128,42 @@ public abstract class AbstractJsonMarshalTesterTests { } @Test - public void readInputStreamShouldReturnObject() throws Exception { + void readInputStreamShouldReturnObject() throws Exception { InputStream stream = new ByteArrayInputStream(JSON.getBytes()); AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.read(stream)).isEqualTo(OBJECT); } @Test - public void readResourceShouldReturnObject() throws Exception { + void readResourceShouldReturnObject() throws Exception { Resource resource = new ByteArrayResource(JSON.getBytes()); AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.read(resource)).isEqualTo(OBJECT); } @Test - public void readReaderShouldReturnObject() throws Exception { + void readReaderShouldReturnObject() throws Exception { Reader reader = new StringReader(JSON); AbstractJsonMarshalTester tester = createTester(TYPE); assertThat(tester.read(reader)).isEqualTo(OBJECT); } @Test - public void parseListShouldReturnContent() throws Exception { + void parseListShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("listOfExampleObject"); AbstractJsonMarshalTester tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asList().containsOnly(OBJECT); } @Test - public void parseArrayShouldReturnContent() throws Exception { + void parseArrayShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("arrayOfExampleObject"); AbstractJsonMarshalTester tester = createTester(type); assertThat(tester.parse(ARRAY_JSON)).asArray().containsOnly(OBJECT); } @Test - public void parseMapShouldReturnContent() throws Exception { + void parseMapShouldReturnContent() throws Exception { ResolvableType type = ResolvableTypes.get("mapOfExampleObject"); AbstractJsonMarshalTester tester = createTester(type); assertThat(tester.parse(MAP_JSON)).asMap().containsEntry("a", OBJECT); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java index b66819506e5..463d90c142b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java @@ -36,53 +36,53 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class BasicJsonTesterTests { +class BasicJsonTesterTests { private static final String JSON = "{\"spring\":[\"boot\",\"framework\"]}"; private BasicJsonTester json = new BasicJsonTester(getClass()); @Test - public void createWhenResourceLoadClassIsNullShouldThrowException() { + void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BasicJsonTester(null)) .withMessageContaining("ResourceLoadClass must not be null"); } @Test - public void fromJsonStringShouldReturnJsonContent() { + void fromJsonStringShouldReturnJsonContent() { assertThat(this.json.from(JSON)).isEqualToJson("source.json"); } @Test - public void fromResourceStringShouldReturnJsonContent() { + void fromResourceStringShouldReturnJsonContent() { assertThat(this.json.from("source.json")).isEqualToJson(JSON); } @Test - public void fromResourceStringWithClassShouldReturnJsonContent() { + void fromResourceStringWithClassShouldReturnJsonContent() { assertThat(this.json.from("source.json", getClass())).isEqualToJson(JSON); } @Test - public void fromByteArrayShouldReturnJsonContent() { + void fromByteArrayShouldReturnJsonContent() { assertThat(this.json.from(JSON.getBytes())).isEqualToJson("source.json"); } @Test - public void fromFileShouldReturnJsonContent(@TempDir Path temp) throws Exception { + void fromFileShouldReturnJsonContent(@TempDir Path temp) throws Exception { File file = new File(temp.toFile(), "file.json"); FileCopyUtils.copy(JSON.getBytes(), file); assertThat(this.json.from(file)).isEqualToJson("source.json"); } @Test - public void fromInputStreamShouldReturnJsonContent() { + void fromInputStreamShouldReturnJsonContent() { InputStream inputStream = new ByteArrayInputStream(JSON.getBytes()); assertThat(this.json.from(inputStream)).isEqualToJson("source.json"); } @Test - public void fromResourceShouldReturnJsonContent() { + void fromResourceShouldReturnJsonContent() { Resource resource = new ByteArrayResource(JSON.getBytes()); assertThat(this.json.from(resource)).isEqualToJson("source.json"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java index 12e5d7c6a60..c4286b6afd7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Diego Berrueta */ -public class GsonTesterIntegrationTests { +class GsonTesterIntegrationTests { private GsonTester simpleJson; @@ -53,20 +53,20 @@ public class GsonTesterIntegrationTests { } @Test - public void typicalTest() throws Exception { + void typicalTest() throws Exception { String example = JSON; assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring"); } @Test - public void typicalListTest() throws Exception { + void typicalListTest() throws Exception { String example = "[" + JSON + "]"; assertThat(this.listJson.parse(example)).asList().hasSize(1); assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring"); } @Test - public void typicalMapTest() throws Exception { + void typicalMapTest() throws Exception { Map map = new LinkedHashMap<>(); map.put("a", 1); map.put("b", 2); @@ -74,7 +74,7 @@ public class GsonTesterIntegrationTests { } @Test - public void stringLiteral() throws Exception { + void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") .isEqualTo(stringWithSpecialCharacters); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index f08166da0fe..7ca858e7f02 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -32,23 +32,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class GsonTesterTests extends AbstractJsonMarshalTesterTests { +class GsonTesterTests extends AbstractJsonMarshalTesterTests { @Test - public void initFieldsWhenTestIsNullShouldThrowException() { + void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) .withMessageContaining("TestInstance must not be null"); } @Test - public void initFieldsWhenMarshallerIsNullShouldThrowException() { + void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) .withMessageContaining("Marshaller must not be null"); } @Test - public void initFieldsShouldSetNullFields() { + void initFieldsShouldSetNullFields() { InitFieldsTestClass test = new InitFieldsTestClass(); assertThat(test.test).isNull(); assertThat(test.base).isNull(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java index a2d37fae8e6..5e558135624 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Diego Berrueta */ -public class JacksonTesterIntegrationTests { +class JacksonTesterIntegrationTests { private JacksonTester simpleJson; @@ -61,20 +61,20 @@ public class JacksonTesterIntegrationTests { } @Test - public void typicalTest() throws Exception { + void typicalTest() throws Exception { String example = JSON; assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring"); } @Test - public void typicalListTest() throws Exception { + void typicalListTest() throws Exception { String example = "[" + JSON + "]"; assertThat(this.listJson.parse(example)).asList().hasSize(1); assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring"); } @Test - public void typicalMapTest() throws Exception { + void typicalMapTest() throws Exception { Map map = new LinkedHashMap<>(); map.put("a", 1); map.put("b", 2); @@ -82,14 +82,14 @@ public class JacksonTesterIntegrationTests { } @Test - public void stringLiteral() throws Exception { + void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") .isEqualTo(stringWithSpecialCharacters); } @Test - public void parseSpecialCharactersTest() throws Exception { + void parseSpecialCharactersTest() throws Exception { // Confirms that the handling of special characters is symmetrical between // the serialization (via the JacksonTester) and the parsing (via json-path). By // default json-path uses SimpleJson as its parser, which has a slightly different @@ -102,7 +102,7 @@ public class JacksonTesterIntegrationTests { } @Test - public void writeWithView() throws Exception { + void writeWithView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); ExampleObjectWithView object = new ExampleObjectWithView(); object.setName("Spring"); @@ -114,7 +114,7 @@ public class JacksonTesterIntegrationTests { } @Test - public void readWithResourceAndView() throws Exception { + void readWithResourceAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); ByteArrayResource resource = new ByteArrayResource(JSON.getBytes()); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) @@ -124,7 +124,7 @@ public class JacksonTesterIntegrationTests { } @Test - public void readWithReaderAndView() throws Exception { + void readWithReaderAndView() throws Exception { this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); Reader reader = new StringReader(JSON); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index 9c9d4db511c..67f240ba43f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -31,23 +31,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { +class JacksonTesterTests extends AbstractJsonMarshalTesterTests { @Test - public void initFieldsWhenTestIsNullShouldThrowException() { + void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) .withMessageContaining("TestInstance must not be null"); } @Test - public void initFieldsWhenMarshallerIsNullShouldThrowException() { + void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) .withMessageContaining("Marshaller must not be null"); } @Test - public void initFieldsShouldSetNullFields() { + void initFieldsShouldSetNullFields() { InitFieldsTestClass test = new InitFieldsTestClass(); assertThat(test.test).isNull(); assertThat(test.base).isNull(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 89f90b37332..9cd5082a5ec 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.entry; * * @author Phillip Webb */ -public class JsonContentAssertTests { +class JsonContentAssertTests { private static final String SOURCE = loadJson("source.json"); @@ -71,796 +71,796 @@ public class JsonContentAssertTests { } @Test - public void isEqualToWhenStringIsMatchingShouldPass() { + void isEqualToWhenStringIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualTo(LENIENT_SAME); } @Test - public void isEqualToWhenNullActualShouldFail() { + void isEqualToWhenNullActualShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(null)).isEqualTo(SOURCE)); } @Test - public void isEqualToWhenStringIsNotMatchingShouldFail() { + void isEqualToWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT)); } @Test - public void isEqualToWhenResourcePathIsMatchingShouldPass() { + void isEqualToWhenResourcePathIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualTo("lenient-same.json"); } @Test - public void isEqualToWhenResourcePathIsNotMatchingShouldFail() { + void isEqualToWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); } @Test - public void isEqualToWhenBytesAreMatchingShouldPass() { + void isEqualToWhenBytesAreMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualTo(LENIENT_SAME.getBytes()); } @Test - public void isEqualToWhenBytesAreNotMatchingShouldFail() { + void isEqualToWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); } @Test - public void isEqualToWhenFileIsMatchingShouldPass() throws Exception { + void isEqualToWhenFileIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualTo(createFile(LENIENT_SAME)); } @Test - public void isEqualToWhenFileIsNotMatchingShouldFail() throws Exception { + void isEqualToWhenFileIsNotMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); } @Test - public void isEqualToWhenInputStreamIsMatchingShouldPass() { + void isEqualToWhenInputStreamIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualTo(createInputStream(LENIENT_SAME)); } @Test - public void isEqualToWhenInputStreamIsNotMatchingShouldFail() { + void isEqualToWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); } @Test - public void isEqualToWhenResourceIsMatchingShouldPass() { + void isEqualToWhenResourceIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualTo(createResource(LENIENT_SAME)); } @Test - public void isEqualToWhenResourceIsNotMatchingShouldFail() { + void isEqualToWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); } @Test - public void isEqualToJsonWhenStringIsMatchingShouldPass() { + void isEqualToJsonWhenStringIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME); } @Test - public void isEqualToJsonWhenNullActualShouldFail() { + void isEqualToJsonWhenNullActualShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(null)).isEqualToJson(SOURCE)); } @Test - public void isEqualToJsonWhenStringIsNotMatchingShouldFail() { + void isEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT)); } @Test - public void isEqualToJsonWhenResourcePathIsMatchingShouldPass() { + void isEqualToJsonWhenResourcePathIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json"); } @Test - public void isEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { + void isEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); } @Test - public void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() { + void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass()); } @Test - public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { + void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); } @Test - public void isEqualToJsonWhenBytesAreMatchingShouldPass() { + void isEqualToJsonWhenBytesAreMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes()); } @Test - public void isEqualToJsonWhenBytesAreNotMatchingShouldFail() { + void isEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); } @Test - public void isEqualToJsonWhenFileIsMatchingShouldPass() throws Exception { + void isEqualToJsonWhenFileIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME)); } @Test - public void isEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { + void isEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); } @Test - public void isEqualToJsonWhenInputStreamIsMatchingShouldPass() { + void isEqualToJsonWhenInputStreamIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME)); } @Test - public void isEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { + void isEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); } @Test - public void isEqualToJsonWhenResourceIsMatchingShouldPass() { + void isEqualToJsonWhenResourceIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME)); } @Test - public void isEqualToJsonWhenResourceIsNotMatchingShouldFail() { + void isEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); } @Test - public void isStrictlyEqualToJsonWhenStringIsMatchingShouldPass() { + void isStrictlyEqualToJsonWhenStringIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(SOURCE); } @Test - public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); } @Test - public void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass() { + void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json"); } @Test - public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); } @Test - public void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() { + void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json", getClass()); } @Test - public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); } @Test - public void isStrictlyEqualToJsonWhenBytesAreMatchingShouldPass() { + void isStrictlyEqualToJsonWhenBytesAreMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(SOURCE.getBytes()); } @Test - public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); } @Test - public void isStrictlyEqualToJsonWhenFileIsMatchingShouldPass() throws Exception { + void isStrictlyEqualToJsonWhenFileIsMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(SOURCE)); } @Test - public void isStrictlyEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { + void isStrictlyEqualToJsonWhenFileIsNotMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); } @Test - public void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass() { + void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(SOURCE)); } @Test - public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); } @Test - public void isStrictlyEqualToJsonWhenResourceIsMatchingShouldPass() { + void isStrictlyEqualToJsonWhenResourceIsMatchingShouldPass() { assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(SOURCE)); } @Test - public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() { + void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); } @Test - public void isEqualToJsonWhenStringIsMatchingAndLenientShouldPass() { + void isEqualToJsonWhenStringIsMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() { + void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() { + void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() { + void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception { + void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() { + void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() { + void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT); } @Test - public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() { + void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT)); } @Test - public void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME, COMPARATOR); } @Test - public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); } @Test - public void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", COMPARATOR); } @Test - public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); } @Test - public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR); } @Test - public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); } @Test - public void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR); } @Test - public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); } @Test - public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception { + void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR); } @Test - public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception { + void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); } @Test - public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR); } @Test - public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); } @Test - public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() { + void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR); } @Test - public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() { + void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); } @Test - public void isNotEqualToWhenStringIsMatchingShouldFail() { + void isNotEqualToWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME)); } @Test - public void isNotEqualToWhenNullActualShouldPass() { + void isNotEqualToWhenNullActualShouldPass() { assertThat(forJson(null)).isNotEqualTo(SOURCE); } @Test - public void isNotEqualToWhenStringIsNotMatchingShouldPass() { + void isNotEqualToWhenStringIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualTo(DIFFERENT); } @Test - public void isNotEqualToWhenResourcePathIsMatchingShouldFail() { + void isNotEqualToWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); } @Test - public void isNotEqualToWhenResourcePathIsNotMatchingShouldPass() { + void isNotEqualToWhenResourcePathIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualTo("different.json"); } @Test - public void isNotEqualToWhenBytesAreMatchingShouldFail() { + void isNotEqualToWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); } @Test - public void isNotEqualToWhenBytesAreNotMatchingShouldPass() { + void isNotEqualToWhenBytesAreNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualTo(DIFFERENT.getBytes()); } @Test - public void isNotEqualToWhenFileIsMatchingShouldFail() throws Exception { + void isNotEqualToWhenFileIsMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); } @Test - public void isNotEqualToWhenFileIsNotMatchingShouldPass() throws Exception { + void isNotEqualToWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualTo(createFile(DIFFERENT)); } @Test - public void isNotEqualToWhenInputStreamIsMatchingShouldFail() { + void isNotEqualToWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); } @Test - public void isNotEqualToWhenInputStreamIsNotMatchingShouldPass() { + void isNotEqualToWhenInputStreamIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(DIFFERENT)); } @Test - public void isNotEqualToWhenResourceIsMatchingShouldFail() { + void isNotEqualToWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); } @Test - public void isNotEqualToWhenResourceIsNotMatchingShouldPass() { + void isNotEqualToWhenResourceIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualTo(createResource(DIFFERENT)); } @Test - public void isNotEqualToJsonWhenStringIsMatchingShouldFail() { + void isNotEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); } @Test - public void isNotEqualToJsonWhenNullActualShouldPass() { + void isNotEqualToJsonWhenNullActualShouldPass() { assertThat(forJson(null)).isNotEqualToJson(SOURCE); } @Test - public void isNotEqualToJsonWhenStringIsNotMatchingShouldPass() { + void isNotEqualToJsonWhenStringIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT); } @Test - public void isNotEqualToJsonWhenResourcePathIsMatchingShouldFail() { + void isNotEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass() { + void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json"); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { + void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { + void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass()); } @Test - public void isNotEqualToJsonWhenBytesAreMatchingShouldFail() { + void isNotEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); } @Test - public void isNotEqualToJsonWhenBytesAreNotMatchingShouldPass() { + void isNotEqualToJsonWhenBytesAreNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes()); } @Test - public void isNotEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { + void isNotEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { + void isNotEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT)); } @Test - public void isNotEqualToJsonWhenInputStreamIsMatchingShouldFail() { + void isNotEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { + void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT)); } @Test - public void isNotEqualToJsonWhenResourceIsMatchingShouldFail() { + void isNotEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); } @Test - public void isNotEqualToJsonWhenResourceIsNotMatchingShouldPass() { + void isNotEqualToJsonWhenResourceIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT)); } @Test - public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); } @Test - public void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json"); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); } @Test - public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass()); } @Test - public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); } @Test - public void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME.getBytes()); } @Test - public void isNotStrictlyEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { + void isNotStrictlyEqualToJsonWhenFileIsMatchingShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); } @Test - public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { + void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME)); } @Test - public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); } @Test - public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test - public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() { + void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); } @Test - public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() { + void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); } @Test - public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception { + void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception { + void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { + void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test - public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() { + void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT); } @Test - public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); } @Test - public void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); } @Test - public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR); } @Test - public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), COMPARATOR); } @Test - public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception { + void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception { + void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), COMPARATOR); } @Test - public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR); } @Test - public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { + void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy( () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); } @Test - public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() { + void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() { assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR); } @Test - public void hasJsonPathValue() { + void hasJsonPathValue() { assertThat(forJson(TYPES)).hasJsonPathValue("$.str"); } @Test - public void hasJsonPathValueForAnEmptyArray() { + void hasJsonPathValueForAnEmptyArray() { assertThat(forJson(TYPES)).hasJsonPathValue("$.emptyArray"); } @Test - public void hasJsonPathValueForAnEmptyMap() { + void hasJsonPathValueForAnEmptyMap() { assertThat(forJson(TYPES)).hasJsonPathValue("$.emptyMap"); } @Test - public void hasJsonPathValueForIndefinitePathWithResults() { + void hasJsonPathValueForIndefinitePathWithResults() { assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test - public void hasJsonPathValueForIndefinitePathWithEmptyResults() { + void hasJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) @@ -868,12 +868,12 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveJsonPathValue() { + void doesNotHaveJsonPathValue() { assertThat(forJson(TYPES)).doesNotHaveJsonPathValue("$.bogus"); } @Test - public void doesNotHaveJsonPathValueForAnEmptyArray() { + void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) @@ -881,7 +881,7 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveJsonPathValueForAnEmptyMap() { + void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) @@ -889,7 +889,7 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveJsonPathValueForIndefinitePathWithResults() { + void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) @@ -898,32 +898,32 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() { + void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() { assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test - public void hasEmptyJsonPathValueForAnEmptyString() { + void hasEmptyJsonPathValueForAnEmptyString() { assertThat(forJson(TYPES)).hasEmptyJsonPathValue("$.emptyString"); } @Test - public void hasEmptyJsonPathValueForAnEmptyArray() { + void hasEmptyJsonPathValueForAnEmptyArray() { assertThat(forJson(TYPES)).hasEmptyJsonPathValue("$.emptyArray"); } @Test - public void hasEmptyJsonPathValueForAnEmptyMap() { + void hasEmptyJsonPathValueForAnEmptyMap() { assertThat(forJson(TYPES)).hasEmptyJsonPathValue("$.emptyMap"); } @Test - public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() { + void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() { assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test - public void hasEmptyJsonPathValueForIndefinitePathWithResults() { + void hasEmptyJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) @@ -932,7 +932,7 @@ public class JsonContentAssertTests { } @Test - public void hasEmptyJsonPathValueForWhitespace() { + void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) @@ -940,37 +940,37 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveEmptyJsonPathValueForString() { + void doesNotHaveEmptyJsonPathValueForString() { assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue("$.str"); } @Test - public void doesNotHaveEmptyJsonPathValueForNumber() { + void doesNotHaveEmptyJsonPathValueForNumber() { assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue("$.num"); } @Test - public void doesNotHaveEmptyJsonPathValueForBoolean() { + void doesNotHaveEmptyJsonPathValueForBoolean() { assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue("$.bool"); } @Test - public void doesNotHaveEmptyJsonPathValueForArray() { + void doesNotHaveEmptyJsonPathValueForArray() { assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue("$.arr"); } @Test - public void doesNotHaveEmptyJsonPathValueForMap() { + void doesNotHaveEmptyJsonPathValueForMap() { assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue("$.colorMap"); } @Test - public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() { + void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() { assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test - public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { + void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) @@ -978,7 +978,7 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveEmptyJsonPathValueForAnEmptyString() { + void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) @@ -986,7 +986,7 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { + void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) @@ -994,7 +994,7 @@ public class JsonContentAssertTests { } @Test - public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { + void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) @@ -1002,17 +1002,17 @@ public class JsonContentAssertTests { } @Test - public void hasJsonPathStringValue() { + void hasJsonPathStringValue() { assertThat(forJson(TYPES)).hasJsonPathStringValue("$.str"); } @Test - public void hasJsonPathStringValueForAnEmptyString() { + void hasJsonPathStringValueForAnEmptyString() { assertThat(forJson(TYPES)).hasJsonPathStringValue("$.emptyString"); } @Test - public void hasJsonPathStringValueForNonString() { + void hasJsonPathStringValueForNonString() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) @@ -1020,12 +1020,12 @@ public class JsonContentAssertTests { } @Test - public void hasJsonPathNumberValue() { + void hasJsonPathNumberValue() { assertThat(forJson(TYPES)).hasJsonPathNumberValue("$.num"); } @Test - public void hasJsonPathNumberValueForNonNumber() { + void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) @@ -1033,12 +1033,12 @@ public class JsonContentAssertTests { } @Test - public void hasJsonPathBooleanValue() { + void hasJsonPathBooleanValue() { assertThat(forJson(TYPES)).hasJsonPathBooleanValue("$.bool"); } @Test - public void hasJsonPathBooleanValueForNonBoolean() { + void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) @@ -1046,17 +1046,17 @@ public class JsonContentAssertTests { } @Test - public void hasJsonPathArrayValue() { + void hasJsonPathArrayValue() { assertThat(forJson(TYPES)).hasJsonPathArrayValue("$.arr"); } @Test - public void hasJsonPathArrayValueForAnEmptyArray() { + void hasJsonPathArrayValueForAnEmptyArray() { assertThat(forJson(TYPES)).hasJsonPathArrayValue("$.emptyArray"); } @Test - public void hasJsonPathArrayValueForNonArray() { + void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) @@ -1064,17 +1064,17 @@ public class JsonContentAssertTests { } @Test - public void hasJsonPathMapValue() { + void hasJsonPathMapValue() { assertThat(forJson(TYPES)).hasJsonPathMapValue("$.colorMap"); } @Test - public void hasJsonPathMapValueForAnEmptyMap() { + void hasJsonPathMapValueForAnEmptyMap() { assertThat(forJson(TYPES)).hasJsonPathMapValue("$.emptyMap"); } @Test - public void hasJsonPathMapValueForNonMap() { + void hasJsonPathMapValueForNonMap() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) @@ -1082,32 +1082,32 @@ public class JsonContentAssertTests { } @Test - public void extractingJsonPathValue() { + void extractingJsonPathValue() { assertThat(forJson(TYPES)).extractingJsonPathValue("@.str").isEqualTo("foo"); } @Test - public void extractingJsonPathValueForMissing() { + void extractingJsonPathValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathValue("@.bogus").isNull(); } @Test - public void extractingJsonPathStringValue() { + void extractingJsonPathStringValue() { assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo"); } @Test - public void extractingJsonPathStringValueForMissing() { + void extractingJsonPathStringValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.bogus").isNull(); } @Test - public void extractingJsonPathStringValueForEmptyString() { + void extractingJsonPathStringValueForEmptyString() { assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty(); } @Test - public void extractingJsonPathStringValueForWrongType() { + void extractingJsonPathStringValueForWrongType() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) @@ -1115,17 +1115,17 @@ public class JsonContentAssertTests { } @Test - public void extractingJsonPathNumberValue() { + void extractingJsonPathNumberValue() { assertThat(forJson(TYPES)).extractingJsonPathNumberValue("@.num").isEqualTo(5); } @Test - public void extractingJsonPathNumberValueForMissing() { + void extractingJsonPathNumberValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathNumberValue("@.bogus").isNull(); } @Test - public void extractingJsonPathNumberValueForWrongType() { + void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) @@ -1133,17 +1133,17 @@ public class JsonContentAssertTests { } @Test - public void extractingJsonPathBooleanValue() { + void extractingJsonPathBooleanValue() { assertThat(forJson(TYPES)).extractingJsonPathBooleanValue("@.bool").isTrue(); } @Test - public void extractingJsonPathBooleanValueForMissing() { + void extractingJsonPathBooleanValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathBooleanValue("@.bogus").isNull(); } @Test - public void extractingJsonPathBooleanValueForWrongType() { + void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) @@ -1151,22 +1151,22 @@ public class JsonContentAssertTests { } @Test - public void extractingJsonPathArrayValue() { + void extractingJsonPathArrayValue() { assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42); } @Test - public void extractingJsonPathArrayValueForMissing() { + void extractingJsonPathArrayValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.bogus").isNull(); } @Test - public void extractingJsonPathArrayValueForEmpty() { + void extractingJsonPathArrayValueForEmpty() { assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.emptyArray").isEmpty(); } @Test - public void extractingJsonPathArrayValueForWrongType() { + void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) @@ -1174,22 +1174,22 @@ public class JsonContentAssertTests { } @Test - public void extractingJsonPathMapValue() { + void extractingJsonPathMapValue() { assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo")); } @Test - public void extractingJsonPathMapValueForMissing() { + void extractingJsonPathMapValueForMissing() { assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.bogus").isNull(); } @Test - public void extractingJsonPathMapValueForEmpty() { + void extractingJsonPathMapValueForEmpty() { assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.emptyMap").isEmpty(); } @Test - public void extractingJsonPathMapValueForWrongType() { + void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) @@ -1197,7 +1197,7 @@ public class JsonContentAssertTests { } @Test - public void isNullWhenActualIsNullShouldPass() { + void isNullWhenActualIsNullShouldPass() { assertThat(forJson(null)).isNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index ab2e3e74215..e6338feba36 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -29,14 +29,14 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class JsonContentTests { +class JsonContentTests { private static final String JSON = "{\"name\":\"spring\", \"age\":100}"; private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test - public void createWhenResourceLoadClassIsNullShouldThrowException() { + void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) @@ -44,21 +44,21 @@ public class JsonContentTests { } @Test - public void createWhenJsonIsNullShouldThrowException() { + void createWhenJsonIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) .withMessageContaining("JSON must not be null"); } @Test - public void createWhenConfigurationIsNullShouldThrowException() { + void createWhenConfigurationIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) .withMessageContaining("Configuration must not be null"); } @Test - public void createWhenTypeIsNullShouldCreateContent() { + void createWhenTypeIsNullShouldCreateContent() { JsonContent content = new JsonContent<>(getClass(), null, JSON, Configuration.defaultConfiguration()); assertThat(content).isNotNull(); @@ -66,14 +66,14 @@ public class JsonContentTests { @Test @SuppressWarnings("deprecation") - public void assertThatShouldReturnJsonContentAssert() { + void assertThatShouldReturnJsonContentAssert() { JsonContent content = new JsonContent<>(getClass(), TYPE, JSON, Configuration.defaultConfiguration()); assertThat(content.assertThat()).isInstanceOf(JsonContentAssert.class); } @Test - public void getJsonShouldReturnJson() { + void getJsonShouldReturnJson() { JsonContent content = new JsonContent<>(getClass(), TYPE, JSON, Configuration.defaultConfiguration()); assertThat(content.getJson()).isEqualTo(JSON); @@ -81,14 +81,14 @@ public class JsonContentTests { } @Test - public void toStringWhenHasTypeShouldReturnString() { + void toStringWhenHasTypeShouldReturnString() { JsonContent content = new JsonContent<>(getClass(), TYPE, JSON, Configuration.defaultConfiguration()); assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE); } @Test - public void toStringWhenHasNoTypeShouldReturnString() { + void toStringWhenHasNoTypeShouldReturnString() { JsonContent content = new JsonContent<>(getClass(), null, JSON, Configuration.defaultConfiguration()); assertThat(content.toString()).isEqualTo("JsonContent " + JSON); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java index 51aa1d10b14..29892aeb8fe 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java @@ -33,23 +33,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Eddú Meléndez */ -public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { +class JsonbTesterTests extends AbstractJsonMarshalTesterTests { @Test - public void initFieldsWhenTestIsNullShouldThrowException() { + void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) .withMessageContaining("TestInstance must not be null"); } @Test - public void initFieldsWhenMarshallerIsNullShouldThrowException() { + void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) .withMessageContaining("Marshaller must not be null"); } @Test - public void initFieldsShouldSetNullFields() { + void initFieldsShouldSetNullFields() { InitFieldsTestClass test = new InitFieldsTestClass(); assertThat(test.test).isNull(); assertThat(test.base).isNull(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java index fd8e8c46b0a..6fe815d3b4f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -public class ObjectContentAssertTests { +class ObjectContentAssertTests { private static final ExampleObject SOURCE = new ExampleObject(); @@ -42,35 +42,35 @@ public class ObjectContentAssertTests { } @Test - public void isEqualToWhenObjectsAreEqualShouldPass() { + void isEqualToWhenObjectsAreEqualShouldPass() { assertThat(forObject(SOURCE)).isEqualTo(SOURCE); } @Test - public void isEqualToWhenObjectsAreDifferentShouldFail() { + void isEqualToWhenObjectsAreDifferentShouldFail() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT)); } @Test - public void asArrayForArrayShouldReturnObjectArrayAssert() { + void asArrayForArrayShouldReturnObjectArrayAssert() { ExampleObject[] source = new ExampleObject[] { SOURCE }; assertThat(forObject(source)).asArray().containsExactly(SOURCE); } @Test - public void asArrayForNonArrayShouldFail() { + void asArrayForNonArrayShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asArray()); } @Test - public void asMapForMapShouldReturnMapAssert() { + void asMapForMapShouldReturnMapAssert() { Map source = Collections.singletonMap("a", SOURCE); assertThat(forObject(source)).asMap().containsEntry("a", SOURCE); } @Test - public void asMapForNonMapShouldFail() { + void asMapForNonMapShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asMap()); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index c71fee903ca..9d183335f8b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -28,44 +28,44 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ObjectContentTests { +class ObjectContentTests { private static final ExampleObject OBJECT = new ExampleObject(); private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class); @Test - public void createWhenObjectIsNullShouldThrowException() { + void createWhenObjectIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent(TYPE, null)) .withMessageContaining("Object must not be null"); } @Test - public void createWhenTypeIsNullShouldCreateContent() { + void createWhenTypeIsNullShouldCreateContent() { ObjectContent content = new ObjectContent<>(null, OBJECT); assertThat(content).isNotNull(); } @Test - public void assertThatShouldReturnObjectContentAssert() { + void assertThatShouldReturnObjectContentAssert() { ObjectContent content = new ObjectContent<>(TYPE, OBJECT); assertThat(content.assertThat()).isInstanceOf(ObjectContentAssert.class); } @Test - public void getObjectShouldReturnObject() { + void getObjectShouldReturnObject() { ObjectContent content = new ObjectContent<>(TYPE, OBJECT); assertThat(content.getObject()).isEqualTo(OBJECT); } @Test - public void toStringWhenHasTypeShouldReturnString() { + void toStringWhenHasTypeShouldReturnString() { ObjectContent content = new ObjectContent<>(TYPE, OBJECT); assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE); } @Test - public void toStringWhenHasNoTypeShouldReturnString() { + void toStringWhenHasNoTypeShouldReturnString() { ObjectContent content = new ObjectContent<>(null, OBJECT); assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index 33203f2866f..0b8cb7ea2b9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -37,19 +37,19 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class DefinitionsParserTests { +class DefinitionsParserTests { private DefinitionsParser parser = new DefinitionsParser(); @Test - public void parseSingleMockBean() { + void parseSingleMockBean() { this.parser.parse(SingleMockBean.class); assertThat(getDefinitions()).hasSize(1); assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test - public void parseRepeatMockBean() { + void parseRepeatMockBean() { this.parser.parse(RepeatMockBean.class); assertThat(getDefinitions()).hasSize(2); assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); @@ -57,7 +57,7 @@ public class DefinitionsParserTests { } @Test - public void parseMockBeanAttributes() { + void parseMockBeanAttributes() { this.parser.parse(MockBeanAttributes.class); assertThat(getDefinitions()).hasSize(1); MockDefinition definition = getMockDefinition(0); @@ -71,7 +71,7 @@ public class DefinitionsParserTests { } @Test - public void parseMockBeanOnClassAndField() { + void parseMockBeanOnClassAndField() { this.parser.parse(MockBeanOnClassAndField.class); assertThat(getDefinitions()).hasSize(2); MockDefinition classDefinition = getMockDefinition(0); @@ -85,20 +85,20 @@ public class DefinitionsParserTests { } @Test - public void parseMockBeanInferClassToMock() { + void parseMockBeanInferClassToMock() { this.parser.parse(MockBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); } @Test - public void parseMockBeanMissingClassToMock() { + void parseMockBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) .withMessageContaining("Unable to deduce type to mock"); } @Test - public void parseMockBeanMultipleClasses() { + void parseMockBeanMultipleClasses() { this.parser.parse(MockBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); @@ -106,20 +106,20 @@ public class DefinitionsParserTests { } @Test - public void parseMockBeanMultipleClassesWithName() { + void parseMockBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class)) .withMessageContaining("The name attribute can only be used when mocking a single class"); } @Test - public void parseSingleSpyBean() { + void parseSingleSpyBean() { this.parser.parse(SingleSpyBean.class); assertThat(getDefinitions()).hasSize(1); assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test - public void parseRepeatSpyBean() { + void parseRepeatSpyBean() { this.parser.parse(RepeatSpyBean.class); assertThat(getDefinitions()).hasSize(2); assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); @@ -127,7 +127,7 @@ public class DefinitionsParserTests { } @Test - public void parseSpyBeanAttributes() { + void parseSpyBeanAttributes() { this.parser.parse(SpyBeanAttributes.class); assertThat(getDefinitions()).hasSize(1); SpyDefinition definition = getSpyDefinition(0); @@ -138,7 +138,7 @@ public class DefinitionsParserTests { } @Test - public void parseSpyBeanOnClassAndField() { + void parseSpyBeanOnClassAndField() { this.parser.parse(SpyBeanOnClassAndField.class); assertThat(getDefinitions()).hasSize(2); SpyDefinition classDefinition = getSpyDefinition(0); @@ -152,20 +152,20 @@ public class DefinitionsParserTests { } @Test - public void parseSpyBeanInferClassToMock() { + void parseSpyBeanInferClassToMock() { this.parser.parse(SpyBeanInferClassToMock.class); assertThat(getDefinitions()).hasSize(1); assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); } @Test - public void parseSpyBeanMissingClassToMock() { + void parseSpyBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) .withMessageContaining("Unable to deduce type to spy"); } @Test - public void parseSpyBeanMultipleClasses() { + void parseSpyBeanMultipleClasses() { this.parser.parse(SpyBeanMultipleClasses.class); assertThat(getDefinitions()).hasSize(2); assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); @@ -173,7 +173,7 @@ public class DefinitionsParserTests { } @Test - public void parseSpyBeanMultipleClassesWithName() { + void parseSpyBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) .withMessageContaining("The name attribute can only be used when spying a single class"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java index a1e904f043f..1a97129588f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanForBeanFactoryIntegrationTests { +class MockBeanForBeanFactoryIntegrationTests { // gh-7439 @@ -48,7 +48,7 @@ public class MockBeanForBeanFactoryIntegrationTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testName() { + void testName() { TestBean testBean = mock(TestBean.class); given(testBean.hello()).willReturn("amock"); given(this.testFactoryBean.getObjectType()).willReturn((Class) TestBean.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java index e71cac96636..a4f0c22649c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java @@ -37,13 +37,13 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnConfigurationClassForExistingBeanIntegrationTests { +class MockBeanOnConfigurationClassForExistingBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java index 57ee6ece55b..4a30ac7aabc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java @@ -36,13 +36,13 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnConfigurationClassForNewBeanIntegrationTests { +class MockBeanOnConfigurationClassForNewBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java index 14fd0645996..3d05a2d8656 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java @@ -37,7 +37,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnConfigurationFieldForExistingBeanIntegrationTests { +class MockBeanOnConfigurationFieldForExistingBeanIntegrationTests { @Autowired private Config config; @@ -46,7 +46,7 @@ public class MockBeanOnConfigurationFieldForExistingBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.config.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java index 604e74ebcd6..2ce964fa923 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnConfigurationFieldForNewBeanIntegrationTests { +class MockBeanOnConfigurationFieldForNewBeanIntegrationTests { @Autowired private Config config; @@ -45,7 +45,7 @@ public class MockBeanOnConfigurationFieldForNewBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.config.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java index 53eb20a9816..e9b7ab1fe42 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java @@ -43,13 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class), @ContextConfiguration(classes = ChildConfig.class) }) -public class MockBeanOnContextHierarchyIntegrationTests { +class MockBeanOnContextHierarchyIntegrationTests { @Autowired private ChildConfig childConfig; @Test - public void testMocking() { + void testMocking() { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java index c266d490103..ad60c9afdb9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java @@ -40,7 +40,7 @@ import static org.mockito.BDDMockito.given; * @see gh-5724 */ @ExtendWith(SpringExtension.class) -public class MockBeanOnScopedProxyTests { +class MockBeanOnScopedProxyTests { @MockBean private ExampleService exampleService; @@ -49,7 +49,7 @@ public class MockBeanOnScopedProxyTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java index 7c876d00ee4..792ef94185d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java @@ -37,13 +37,13 @@ import static org.mockito.BDDMockito.given; */ @ExtendWith(SpringExtension.class) @MockBean(ExampleService.class) -public class MockBeanOnTestClassForExistingBeanIntegrationTests { +class MockBeanOnTestClassForExistingBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java index 9e6db48b8bd..b0fd27d908e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java @@ -37,13 +37,13 @@ import static org.mockito.BDDMockito.given; */ @ExtendWith(SpringExtension.class) @MockBean(ExampleService.class) -public class MockBeanOnTestClassForNewBeanIntegrationTests { +class MockBeanOnTestClassForNewBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java index d85b801de84..f603a86aa71 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java @@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.given; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class) -public class MockBeanOnTestFieldForExistingBeanCacheIntegrationTests { +class MockBeanOnTestFieldForExistingBeanCacheIntegrationTests { @MockBean private ExampleService exampleService; @@ -48,7 +48,7 @@ public class MockBeanOnTestFieldForExistingBeanCacheIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java index fa4a72bba7a..2168ac1f301 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java @@ -37,7 +37,7 @@ import static org.mockito.BDDMockito.given; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class) -public class MockBeanOnTestFieldForExistingBeanIntegrationTests { +class MockBeanOnTestFieldForExistingBeanIntegrationTests { @MockBean private ExampleService exampleService; @@ -46,7 +46,7 @@ public class MockBeanOnTestFieldForExistingBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java index e20da695328..ad5d7ca2f83 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java @@ -41,7 +41,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { +class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { @MockBean @CustomQualifier @@ -54,13 +54,13 @@ public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { private ApplicationContext applicationContext; @Test - public void testMocking() { + void testMocking() { this.caller.sayGreeting(); verify(this.service).greeting(); } @Test - public void onlyQualifiedBeanIsReplaced() { + void onlyQualifiedBeanIsReplaced() { assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); assertThat(anotherService.greeting()).isEqualTo("Another"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java index 7a90a705ae0..9d0d08e3cca 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanOnTestFieldForNewBeanIntegrationTests { +class MockBeanOnTestFieldForNewBeanIntegrationTests { @MockBean private ExampleService exampleService; @@ -45,7 +45,7 @@ public class MockBeanOnTestFieldForNewBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java index 0313210c40f..dfbf0fc212c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java @@ -47,13 +47,13 @@ import static org.mockito.Mockito.verify; * @see 5837 */ @ExtendWith(SpringExtension.class) -public class MockBeanWithAopProxyTests { +class MockBeanWithAopProxyTests { @MockBean private DateService dateService; @Test - public void verifyShouldUseProxyTarget() { + void verifyShouldUseProxyTarget() { given(this.dateService.getDate(false)).willReturn(1L); Long d1 = this.dateService.getDate(false); assertThat(d1).isEqualTo(1L); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java index ca34d8bf378..1f6fb6e3faa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java @@ -35,7 +35,7 @@ import static org.mockito.BDDMockito.given; * @author Andy Wilkinson */ @ExtendWith(SpringExtension.class) -public class MockBeanWithAsyncInterfaceMethodIntegrationTests { +class MockBeanWithAsyncInterfaceMethodIntegrationTests { @MockBean private Transformer transformer; @@ -44,7 +44,7 @@ public class MockBeanWithAsyncInterfaceMethodIntegrationTests { private MyService service; @Test - public void mockedMethodsAreNotAsync() { + void mockedMethodsAreNotAsync() { given(this.transformer.transform("foo")).willReturn("bar"); assertThat(this.service.transform("foo")).isEqualTo("bar"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java index 9f3d0662911..d7f58040a31 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java @@ -39,7 +39,7 @@ import static org.mockito.BDDMockito.given; */ @ExtendWith(SpringExtension.class) @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) -public class MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { +class MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { @MockBean private ExampleService exampleService; @@ -48,7 +48,7 @@ public class MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { private ExampleServiceCaller caller; @Test - public void testMocking() throws Exception { + void testMocking() throws Exception { given(this.exampleService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java index feeebb91c39..877aa4e4076 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests { +class MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests { @MockBean private ExampleGenericService exampleIntegerService; @@ -48,7 +48,7 @@ public class MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests { private ExampleGenericServiceCaller caller; @Test - public void testMocking() { + void testMocking() { given(this.exampleIntegerService.greeting()).willReturn(200); given(this.exampleStringService.greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say 200 Boot"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java index f2edda64ff7..3a585ca29b0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java @@ -33,13 +33,13 @@ import static org.mockito.BDDMockito.given; * @author Andy Wilkinson */ @ExtendWith(SpringExtension.class) -public class MockBeanWithInjectedFieldIntegrationTests { +class MockBeanWithInjectedFieldIntegrationTests { @MockBean private MyService myService; @Test - public void fieldInjectionIntoMyServiceMockIsNotAttempted() { + void fieldInjectionIntoMyServiceMockIsNotAttempted() { given(this.myService.getCount()).willReturn(5); assertThat(this.myService.getCount()).isEqualTo(5); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index 3db91e84387..53a6f51a5d5 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -34,19 +34,19 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class MockDefinitionTests { +class MockDefinitionTests { private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class); @Test - public void classToMockMustNotBeNull() { + void classToMockMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) .withMessageContaining("TypeToMock must not be null"); } @Test - public void createWithDefaults() { + void createWithDefaults() { MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); @@ -58,7 +58,7 @@ public class MockDefinitionTests { } @Test - public void createExplicit() { + void createExplicit() { QualifierDefinition qualifier = mock(QualifierDefinition.class); MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, @@ -74,7 +74,7 @@ public class MockDefinitionTests { } @Test - public void createMock() { + void createMock() { MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java index f96c7886c31..1ac65776a39 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java @@ -29,40 +29,40 @@ import static org.mockito.Mockito.withSettings; * * @author Phillip Webb */ -public class MockResetTests { +class MockResetTests { @Test - public void noneAttachesReset() { + void noneAttachesReset() { ExampleService mock = mock(ExampleService.class); assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); } @Test - public void withSettingsOfNoneAttachesReset() { + void withSettingsOfNoneAttachesReset() { ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); } @Test - public void beforeAttachesReset() { + void beforeAttachesReset() { ExampleService mock = mock(ExampleService.class, MockReset.before()); assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); } @Test - public void afterAttachesReset() { + void afterAttachesReset() { ExampleService mock = mock(ExampleService.class, MockReset.after()); assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); } @Test - public void withSettingsAttachesReset() { + void withSettingsAttachesReset() { ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE)); assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); } @Test - public void apply() { + void apply() { ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings())); assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java index c4d43584c0e..bb796fd2df0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MockitoContextCustomizerFactoryTests { +class MockitoContextCustomizerFactoryTests { private final MockitoContextCustomizerFactory factory = new MockitoContextCustomizerFactory(); @@ -39,19 +39,19 @@ public class MockitoContextCustomizerFactoryTests { } @Test - public void getContextCustomizerWithoutAnnotationReturnsCustomizer() { + void getContextCustomizerWithoutAnnotationReturnsCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test - public void getContextCustomizerWithAnnotationReturnsCustomizer() { + void getContextCustomizerWithAnnotationReturnsCustomizer() { ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); } @Test - public void getContextCustomizerUsesMocksAsCacheKey() { + void getContextCustomizerUsesMocksAsCacheKey() { ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); assertThat(customizer).isNotNull(); ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java index 8fa8c891aad..06b15a1f576 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java @@ -34,12 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MockitoContextCustomizerTests { +class MockitoContextCustomizerTests { private static final Set NO_DEFINITIONS = Collections.emptySet(); @Test - public void hashCodeAndEquals() { + void hashCodeAndEquals() { MockDefinition d1 = createTestMockDefinition(ExampleService.class); MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class); MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index 2d64d28c6a7..fe9719e3d1b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -40,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Andy Wilkinson * @author Andreas Neiser */ -public class MockitoPostProcessorTests { +class MockitoPostProcessorTests { @Test - public void cannotMockMultipleBeans() { + void cannotMockMultipleBeans() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MultipleBeans.class); @@ -53,7 +53,7 @@ public class MockitoPostProcessorTests { } @Test - public void cannotMockMultipleQualifiedBeans() { + void cannotMockMultipleQualifiedBeans() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); @@ -63,7 +63,7 @@ public class MockitoPostProcessorTests { } @Test - public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() { + void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class); @@ -75,7 +75,7 @@ public class MockitoPostProcessorTests { } @Test - public void canMockPrimaryBean() { + void canMockPrimaryBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MockPrimaryBean.class); @@ -88,7 +88,7 @@ public class MockitoPostProcessorTests { } @Test - public void canMockQualifiedBeanWithPrimaryBeanPresent() { + void canMockQualifiedBeanWithPrimaryBeanPresent() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MockQualifiedBean.class); @@ -100,7 +100,7 @@ public class MockitoPostProcessorTests { } @Test - public void canSpyPrimaryBean() { + void canSpyPrimaryBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(SpyPrimaryBean.class); @@ -112,7 +112,7 @@ public class MockitoPostProcessorTests { } @Test - public void canSpyQualifiedBeanWithPrimaryBeanPresent() { + void canSpyQualifiedBeanWithPrimaryBeanPresent() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(SpyQualifiedBean.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java index 716324fb416..db2327de28a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * * @author Phillip Webb */ -public class MockitoTestExecutionListenerTests { +class MockitoTestExecutionListenerTests { private MockitoTestExecutionListener listener = new MockitoTestExecutionListener(); @@ -63,7 +63,7 @@ public class MockitoTestExecutionListenerTests { } @Test - public void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception { + void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception { WithMockitoAnnotations instance = new WithMockitoAnnotations(); this.listener.prepareTestInstance(mockTestContext(instance)); assertThat(instance.mock).isNotNull(); @@ -71,7 +71,7 @@ public class MockitoTestExecutionListenerTests { } @Test - public void prepareTestInstanceShouldInjectMockBean() throws Exception { + void prepareTestInstanceShouldInjectMockBean() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.prepareTestInstance(mockTestContext(instance)); verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class)); @@ -79,14 +79,14 @@ public class MockitoTestExecutionListenerTests { } @Test - public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { + void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { WithMockBean instance = new WithMockBean(); this.listener.beforeTestMethod(mockTestContext(instance)); verifyNoMoreInteractions(this.postProcessor); } @Test - public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { + void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { WithMockBean instance = new WithMockBean(); TestContext mockTestContext = mockTestContext(instance); given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java index 03a07a809e0..dcf00a5040c 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class QualifierDefinitionTests { +class QualifierDefinitionTests { @Mock private ConfigurableListableBeanFactory beanFactory; @@ -57,31 +57,31 @@ public class QualifierDefinitionTests { } @Test - public void forElementFieldIsNullShouldReturnNull() { + void forElementFieldIsNullShouldReturnNull() { assertThat(QualifierDefinition.forElement((Field) null)).isNull(); } @Test - public void forElementWhenElementIsNotFieldShouldReturnNull() { + void forElementWhenElementIsNotFieldShouldReturnNull() { assertThat(QualifierDefinition.forElement(getClass())).isNull(); } @Test - public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() { + void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() { QualifierDefinition definition = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); assertThat(definition).isNull(); } @Test - public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() { + void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() { QualifierDefinition definition = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); assertThat(definition).isNotNull(); } @Test - public void matchesShouldCallBeanFactory() { + void matchesShouldCallBeanFactory() { Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); qualifierDefinition.matches(this.beanFactory, "bean"); @@ -90,7 +90,7 @@ public class QualifierDefinitionTests { } @Test - public void applyToShouldSetQualifierElement() { + void applyToShouldSetQualifierElement() { Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); RootBeanDefinition definition = new RootBeanDefinition(); @@ -99,7 +99,7 @@ public class QualifierDefinitionTests { } @Test - public void hashCodeAndEqualsShouldWorkOnDifferentClasses() { + void hashCodeAndEqualsShouldWorkOnDifferentClasses() { QualifierDefinition directQualifier1 = QualifierDefinition .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); QualifierDefinition directQualifier2 = QualifierDefinition diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java index 2c26bf54e6a..83c1e817525 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java @@ -16,10 +16,10 @@ package org.springframework.boot.test.mock.mockito; -import org.junit.FixMethodOrder; +import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runners.MethodSorters; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; @@ -41,21 +41,21 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson */ @ExtendWith(SpringExtension.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class ResetMocksTestExecutionListenerTests { +@TestMethodOrder(MethodOrderer.Alphanumeric.class) +class ResetMocksTestExecutionListenerTests { @Autowired private ApplicationContext context; @Test - public void test001() { + void test001() { given(getMock("none").greeting()).willReturn("none"); given(getMock("before").greeting()).willReturn("before"); given(getMock("after").greeting()).willReturn("after"); } @Test - public void test002() { + void test002() { assertThat(getMock("none").greeting()).isEqualTo("none"); assertThat(getMock("before").greeting()).isNull(); assertThat(getMock("after").greeting()).isNull(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java index 3a1d3ba316a..924a39b7cfc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java @@ -36,13 +36,13 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnConfigurationClassForExistingBeanIntegrationTests { +class SpyBeanOnConfigurationClassForExistingBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java index 8b817515ba9..312de6761c7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java @@ -36,13 +36,13 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnConfigurationClassForNewBeanIntegrationTests { +class SpyBeanOnConfigurationClassForNewBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java index cb21818984e..bab4a639350 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests { +class SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests { @Autowired private Config config; @@ -46,7 +46,7 @@ public class SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.config.exampleService).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java index a1a8fb24f00..4faca40b216 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnConfigurationFieldForNewBeanIntegrationTests { +class SpyBeanOnConfigurationFieldForNewBeanIntegrationTests { @Autowired private Config config; @@ -45,7 +45,7 @@ public class SpyBeanOnConfigurationFieldForNewBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.config.exampleService).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java index 53eff34a0f7..5069c79cd88 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java @@ -44,13 +44,13 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextHierarchy({ @ContextConfiguration(classes = ParentConfig.class), @ContextConfiguration(classes = ChildConfig.class) }) -public class SpyBeanOnContextHierarchyIntegrationTests { +class SpyBeanOnContextHierarchyIntegrationTests { @Autowired private ChildConfig childConfig; @Test - public void testSpying() { + void testSpying() { ApplicationContext context = this.childConfig.getContext(); ApplicationContext parentContext = context.getParent(); assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java index d9d7c68d5fd..702d6b642ca 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java @@ -36,13 +36,13 @@ import static org.mockito.Mockito.verify; */ @ExtendWith(SpringExtension.class) @SpyBean(SimpleExampleService.class) -public class SpyBeanOnTestClassForExistingBeanIntegrationTests { +class SpyBeanOnTestClassForExistingBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java index 98188a566a3..1e73eb29823 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java @@ -36,13 +36,13 @@ import static org.mockito.Mockito.verify; */ @ExtendWith(SpringExtension.class) @SpyBean(SimpleExampleService.class) -public class SpyBeanOnTestClassForNewBeanIntegrationTests { +class SpyBeanOnTestClassForNewBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java index 0358df2364e..83392ea4b59 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.verify; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SpyBeanOnTestFieldForExistingBeanConfig.class) -public class SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests { +class SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests { @SpyBean private ExampleService exampleService; @@ -48,7 +48,7 @@ public class SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java index e8064a6dce9..e66f3518099 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.verify; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SpyBeanOnTestFieldForExistingBeanConfig.class) -public class SpyBeanOnTestFieldForExistingBeanIntegrationTests { +class SpyBeanOnTestFieldForExistingBeanIntegrationTests { @SpyBean private ExampleService exampleService; @@ -46,7 +46,7 @@ public class SpyBeanOnTestFieldForExistingBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java index 2484cdf1b5a..f94daa8b157 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java @@ -40,7 +40,7 @@ import static org.mockito.Mockito.verify; * @author Andreas Neiser */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { +class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { @SpyBean @CustomQualifier @@ -53,13 +53,13 @@ public class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { private ApplicationContext applicationContext; @Test - public void testMocking() throws Exception { + void testMocking() throws Exception { this.caller.sayGreeting(); verify(this.service).greeting(); } @Test - public void onlyQualifiedBeanIsReplaced() { + void onlyQualifiedBeanIsReplaced() { assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); assertThat(anotherService.greeting()).isEqualTo("Another"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java index d7808285b37..6e00d58b70f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java @@ -40,7 +40,7 @@ import static org.mockito.Mockito.verify; * @see SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { +class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { // gh-7625 @@ -51,7 +51,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { private ExampleGenericServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say 123 simple"); verify(this.exampleService).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java index 4b5d093e68d..9667ea37f44 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java @@ -39,7 +39,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests { +class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests { @SpyBean private SimpleExampleStringGenericService spy; @@ -48,7 +48,7 @@ public class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegration private ExampleGenericStringServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say two"); assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings().getMockName().toString()) .isEqualTo("two"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java index ac471a2a1ad..91a1b8f59cc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @ExtendWith(SpringExtension.class) -public class SpyBeanOnTestFieldForNewBeanIntegrationTests { +class SpyBeanOnTestFieldForNewBeanIntegrationTests { @SpyBean private SimpleExampleService exampleService; @@ -45,7 +45,7 @@ public class SpyBeanOnTestFieldForNewBeanIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() { + void testSpying() { assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); verify(this.caller.getService()).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java index b2a4b6ee2aa..fc36314fd60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java @@ -46,13 +46,13 @@ import static org.mockito.Mockito.verify; * @see 5837 */ @ExtendWith(SpringExtension.class) -public class SpyBeanWithAopProxyAndNotProxyTargetAwareTests { +class SpyBeanWithAopProxyAndNotProxyTargetAwareTests { @SpyBean(proxyTargetAware = false) private DateService dateService; @Test - public void verifyShouldUseProxyTarget() { + void verifyShouldUseProxyTarget() { this.dateService.getDate(false); verify(this.dateService, times(1)).getDate(false); assertThatExceptionOfType(UnfinishedVerificationException.class).isThrownBy(() -> reset(this.dateService)); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java index 7cbfeb1759a..a7c812d2a62 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java @@ -46,13 +46,13 @@ import static org.mockito.Mockito.verify; * @see 5837 */ @ExtendWith(SpringExtension.class) -public class SpyBeanWithAopProxyTests { +class SpyBeanWithAopProxyTests { @SpyBean private DateService dateService; @Test - public void verifyShouldUseProxyTarget() throws Exception { + void verifyShouldUseProxyTarget() throws Exception { Long d1 = this.dateService.getDate(false); Thread.sleep(200); Long d2 = this.dateService.getDate(false); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java index 73fc34772a3..d141dcbf426 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.verify; */ @ExtendWith(SpringExtension.class) @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) -public class SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { +class SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { @SpyBean private SimpleExampleService exampleService; @@ -47,7 +47,7 @@ public class SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { private ExampleServiceCaller caller; @Test - public void testSpying() throws Exception { + void testSpying() throws Exception { this.caller.sayGreeting(); verify(this.exampleService).greeting(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java index 1c425a692bb..36cae182a33 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @ExtendWith(SpringExtension.class) -public class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests { +class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests { @SpyBean(name = "two") private SimpleExampleStringGenericService spy; @Test - public void testSpying() { + void testSpying() { MockingDetails mockingDetails = Mockito.mockingDetails(this.spy); assertThat(mockingDetails.isSpy()).isTrue(); assertThat(mockingDetails.getMockCreationSettings().getMockName().toString()).isEqualTo("two"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index e65abb3f96c..06883177c85 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -35,18 +35,18 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class SpyDefinitionTests { +class SpyDefinitionTests { private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType.forClass(RealExampleService.class); @Test - public void classToSpyMustNotBeNull() { + void classToSpyMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) .withMessageContaining("TypeToSpy must not be null"); } @Test - public void createWithDefaults() { + void createWithDefaults() { SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, null); assertThat(definition.getName()).isNull(); assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); @@ -56,7 +56,7 @@ public class SpyDefinitionTests { } @Test - public void createExplicit() { + void createExplicit() { QualifierDefinition qualifier = mock(QualifierDefinition.class); SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, false, qualifier); assertThat(definition.getName()).isEqualTo("name"); @@ -67,7 +67,7 @@ public class SpyDefinitionTests { } @Test - public void createSpy() { + void createSpy() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); RealExampleService spy = definition.createSpy(new RealExampleService("hello")); MockCreationSettings settings = Mockito.mockingDetails(spy).getMockCreationSettings(); @@ -78,21 +78,21 @@ public class SpyDefinitionTests { } @Test - public void createSpyWhenNullInstanceShouldThrowException() { + void createSpyWhenNullInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) .withMessageContaining("Instance must not be null"); } @Test - public void createSpyWhenWrongInstanceShouldThrowException() { + void createSpyWhenWrongInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) .withMessageContaining("must be an instance of"); } @Test - public void createSpyTwice() { + void createSpyTwice() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); Object instance = new RealExampleService("hello"); instance = definition.createSpy(instance); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java index 88b16817fa9..f83ad21c6bd 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java @@ -46,7 +46,7 @@ import static org.hamcrest.Matchers.nullValue; @ExtendWith(SpringExtension.class) @ContextConfiguration(loader = SpringBootContextLoader.class) @WebAppConfiguration("src/test/webapp") -public class SpringBootMockServletContextTests implements ServletContextAware { +class SpringBootMockServletContextTests implements ServletContextAware { private ServletContext servletContext; @@ -56,7 +56,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { } @Test - public void getResourceLocation() throws Exception { + void getResourceLocation() throws Exception { testResource("/inwebapp", "src/test/webapp"); testResource("/inmetainfresources", "/META-INF/resources"); testResource("/inresources", "/resources"); @@ -72,7 +72,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware { // gh-2654 @Test - public void getRootUrlExistsAndIsEmpty() throws Exception { + void getRootUrlExistsAndIsEmpty() throws Exception { SpringBootMockServletContext context = new SpringBootMockServletContext("src/test/doesntexist") { @Override protected String getResourceLocation(String path) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java index 6c0af1308ab..68e2c5ba5d9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java @@ -30,21 +30,21 @@ import static org.mockito.Mockito.verify; * * @author Stephane Nicoll */ -public class ApplicationContextTestUtilsTests { +class ApplicationContextTestUtilsTests { @Test - public void closeNull() { + void closeNull() { ApplicationContextTestUtils.closeAll(null); } @Test - public void closeNonClosableContext() { + void closeNonClosableContext() { ApplicationContext mock = mock(ApplicationContext.class); ApplicationContextTestUtils.closeAll(mock); } @Test - public void closeContextAndParent() { + void closeContextAndParent() { ConfigurableApplicationContext mock = mock(ConfigurableApplicationContext.class); ConfigurableApplicationContext parent = mock(ConfigurableApplicationContext.class); given(mock.getParent()).willReturn(parent); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java index d23d6467c9e..d99b49a068a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java @@ -32,26 +32,26 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Phillip Webb */ -public class TestPropertyValuesTests { +class TestPropertyValuesTests { private final ConfigurableEnvironment environment = new StandardEnvironment(); @Test - public void applyToEnvironmentShouldAttachConfigurationPropertySource() { + void applyToEnvironmentShouldAttachConfigurationPropertySource() { TestPropertyValues.of("foo.bar=baz").applyTo(this.environment); PropertySource source = this.environment.getPropertySources().get("configurationProperties"); assertThat(source).isNotNull(); } @Test - public void applyToDefaultPropertySource() { + void applyToDefaultPropertySource() { TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi"); } @Test - public void applyToSystemPropertySource() { + void applyToSystemPropertySource() { TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); assertThat(this.environment.getPropertySources() @@ -59,14 +59,14 @@ public class TestPropertyValuesTests { } @Test - public void applyToWithSpecificName() { + void applyToWithSpecificName() { TestPropertyValues.of("foo.bar=baz").applyTo(this.environment, Type.MAP, "other"); assertThat(this.environment.getPropertySources().get("other")).isNotNull(); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); } @Test - public void applyToExistingNameAndDifferentTypeShouldOverrideExistingOne() { + void applyToExistingNameAndDifferentTypeShouldOverrideExistingOne() { TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other"); TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other"); assertThat(this.environment.getPropertySources().get("other")) @@ -76,7 +76,7 @@ public class TestPropertyValuesTests { } @Test - public void applyToExistingNameAndSameTypeShouldMerge() { + void applyToExistingNameAndSameTypeShouldMerge() { TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP); TestPropertyValues.of("foo.bar=new").applyTo(this.environment, Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("new"); @@ -84,7 +84,7 @@ public class TestPropertyValuesTests { } @Test - public void andShouldChainAndAddSingleKeyValue() { + void andShouldChainAndAddSingleKeyValue() { TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment, Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); @@ -93,7 +93,7 @@ public class TestPropertyValuesTests { } @Test - public void applyToSystemPropertiesShouldSetSystemProperties() { + void applyToSystemPropertiesShouldSetSystemProperties() { TestPropertyValues.of("foo=bar").applyToSystemProperties(() -> { assertThat(System.getProperty("foo")).isEqualTo("bar"); return null; @@ -101,7 +101,7 @@ public class TestPropertyValuesTests { } @Test - public void applyToSystemPropertiesShouldRestoreSystemProperties() { + void applyToSystemPropertiesShouldRestoreSystemProperties() { System.setProperty("foo", "bar1"); System.clearProperty("baz"); try { @@ -119,7 +119,7 @@ public class TestPropertyValuesTests { } @Test - public void applyToSystemPropertiesWhenValueIsNullShouldRemoveProperty() { + void applyToSystemPropertiesWhenValueIsNullShouldRemoveProperty() { System.setProperty("foo", "bar1"); try { TestPropertyValues.of("foo").applyToSystemProperties(() -> { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java index 0bd059bd36e..aa6d0269952 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Madhura Bhave * @author Andy Wilkinson */ -public class SpringBootTestRandomPortEnvironmentPostProcessorTests { +class SpringBootTestRandomPortEnvironmentPostProcessorTests { private SpringBootTestRandomPortEnvironmentPostProcessor postProcessor = new SpringBootTestRandomPortEnvironmentPostProcessor(); @@ -51,7 +51,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenServerAndManagementPortIsZeroInTestPropertySource() { + void postProcessWhenServerAndManagementPortIsZeroInTestPropertySource() { addTestPropertySource("0", "0"); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); @@ -59,7 +59,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenServerPortAndManagementPortIsZeroInDifferentPropertySources() { + void postProcessWhenServerPortAndManagementPortIsZeroInDifferentPropertySources() { addTestPropertySource("0", null); Map source = new HashMap<>(); source.put("management.server.port", "0"); @@ -70,7 +70,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerAndTestManagementPortAreNonZero() { + void postProcessWhenTestServerAndTestManagementPortAreNonZero() { addTestPropertySource("8080", "8081"); this.environment.setProperty("server.port", "8080"); this.environment.setProperty("management.server.port", "8081"); @@ -80,7 +80,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndTestManagementPortIsNotNull() { + void postProcessWhenTestServerPortIsZeroAndTestManagementPortIsNotNull() { addTestPropertySource("0", "8080"); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); @@ -88,7 +88,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNull() { + void postProcessWhenTestServerPortIsZeroAndManagementPortIsNull() { addTestPropertySource("0", null); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); @@ -96,7 +96,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndSameInProduction() { + void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndSameInProduction() { addTestPropertySource("0", null); Map other = new HashMap<>(); other.put("server.port", "8081"); @@ -109,7 +109,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDefaultSameInProduction() { + void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDefaultSameInProduction() { // mgmt port is 8080 which means it's on the same port as main server since that // is null in app properties addTestPropertySource("0", null); @@ -121,7 +121,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() { + void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() { addTestPropertySource("0", null); this.propertySources .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); @@ -131,7 +131,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() { + void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() { addTestPropertySource("0", null); this.propertySources .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); @@ -141,7 +141,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() { + void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() { addTestPropertySource("0", null); this.propertySources .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); @@ -151,7 +151,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenManagementServerPortPlaceholderPresentShouldResolvePlaceholder() { + void postProcessWhenManagementServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); @@ -164,7 +164,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() { + void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() { addTestPropertySource("0", null); this.propertySources .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); @@ -174,7 +174,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenServerPortPlaceholderPresentShouldResolvePlaceholder() { + void postProcessWhenServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); @@ -189,7 +189,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests { } @Test - public void postProcessWhenServerPortPlaceholderAbsentShouldFail() { + void postProcessWhenServerPortPlaceholderAbsentShouldFail() { addTestPropertySource("0", null); Map source = new HashMap<>(); source.put("server.port", "${port}"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index a6aca9e317c..ad1f67f2ebc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -38,30 +38,30 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Eddú Meléndez */ -public class LocalHostUriTemplateHandlerTests { +class LocalHostUriTemplateHandlerTests { @Test - public void createWhenEnvironmentIsNullShouldThrowException() { + void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostUriTemplateHandler(null)) .withMessageContaining("Environment must not be null"); } @Test - public void createWhenSchemeIsNullShouldThrowException() { + void createWhenSchemeIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) .withMessageContaining("Scheme must not be null"); } @Test - public void createWhenHandlerIsNullShouldThrowException() { + void createWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) .withMessageContaining("Handler must not be null"); } @Test - public void getRootUriShouldUseLocalServerPort() { + void getRootUriShouldUseLocalServerPort() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "1234"); LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); @@ -69,21 +69,21 @@ public class LocalHostUriTemplateHandlerTests { } @Test - public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() { + void getRootUriWhenLocalServerPortMissingShouldUsePort8080() { MockEnvironment environment = new MockEnvironment(); LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080"); } @Test - public void getRootUriUsesCustomScheme() { + void getRootUriUsesCustomScheme() { MockEnvironment environment = new MockEnvironment(); LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https"); assertThat(handler.getRootUri()).isEqualTo("https://localhost:8080"); } @Test - public void getRootUriShouldUseContextPath() { + void getRootUriShouldUseContextPath() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("server.servlet.context-path", "/foo"); LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment); @@ -91,7 +91,7 @@ public class LocalHostUriTemplateHandlerTests { } @Test - public void expandShouldUseCustomHandler() { + void expandShouldUseCustomHandler() { MockEnvironment environment = new MockEnvironment(); UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); Map uriVariables = new HashMap<>(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index 98ecf641847..89697f17c94 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -36,7 +36,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -public class MockServerRestTemplateCustomizerTests { +class MockServerRestTemplateCustomizerTests { private MockServerRestTemplateCustomizer customizer; @@ -46,7 +46,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void createShouldUseSimpleRequestExpectationManager() { + void createShouldUseSimpleRequestExpectationManager() { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer(); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") @@ -54,13 +54,13 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void createWhenExpectationManagerClassIsNullShouldThrowException() { + void createWhenExpectationManagerClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new MockServerRestTemplateCustomizer(null)) .withMessageContaining("ExpectationManager must not be null"); } @Test - public void createShouldUseExpectationManagerClass() { + void createShouldUseExpectationManagerClass() { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer( UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplate()); @@ -69,7 +69,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void detectRootUriShouldDefaultToTrue() { + void detectRootUriShouldDefaultToTrue() { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer( UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); @@ -78,7 +78,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void setDetectRootUriShouldDisableRootUriDetection() { + void setDetectRootUriShouldDisableRootUriDetection() { this.customizer.setDetectRootUri(false); this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") @@ -87,7 +87,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void customizeShouldBindServer() { + void customizeShouldBindServer() { RestTemplate template = new RestTemplateBuilder(this.customizer).build(); this.customizer.getServer().expect(requestTo("/test")).andRespond(withSuccess()); template.getForEntity("/test", String.class); @@ -95,14 +95,14 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getServerWhenNoServersAreBoundShouldThrowException() { + void getServerWhenNoServersAreBoundShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.customizer::getServer) .withMessageContaining("Unable to return a single MockRestServiceServer since " + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); } @Test - public void getServerWhenMultipleServersAreBoundShouldThrowException() { + void getServerWhenMultipleServersAreBoundShouldThrowException() { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); assertThatIllegalStateException().isThrownBy(this.customizer::getServer) @@ -111,14 +111,14 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getServerWhenSingleServerIsBoundShouldReturnServer() { + void getServerWhenSingleServerIsBoundShouldReturnServer() { RestTemplate template = new RestTemplate(); this.customizer.customize(template); assertThat(this.customizer.getServer()).isEqualTo(this.customizer.getServer(template)); } @Test - public void getServerWhenRestTemplateIsFoundShouldReturnServer() { + void getServerWhenRestTemplateIsFoundShouldReturnServer() { RestTemplate template1 = new RestTemplate(); RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); @@ -128,7 +128,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getServerWhenRestTemplateIsNotFoundShouldReturnNull() { + void getServerWhenRestTemplateIsNotFoundShouldReturnNull() { RestTemplate template1 = new RestTemplate(); RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); @@ -137,7 +137,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getServersShouldReturnServers() { + void getServersShouldReturnServers() { RestTemplate template1 = new RestTemplate(); RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); @@ -146,7 +146,7 @@ public class MockServerRestTemplateCustomizerTests { } @Test - public void getExpectationManagersShouldReturnExpectationManagers() { + void getExpectationManagersShouldReturnExpectationManagers() { RestTemplate template1 = new RestTemplate(); RestTemplate template2 = new RestTemplate(); this.customizer.customize(template1); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index c4765df68eb..06ed862fe41 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -49,7 +49,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ -public class RootUriRequestExpectationManagerTests { +class RootUriRequestExpectationManagerTests { private String uri = "https://example.com"; @@ -68,19 +68,19 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void createWhenRootUriIsNullShouldThrowException() { + void createWhenRootUriIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(null, this.delegate)) .withMessageContaining("RootUri must not be null"); } @Test - public void createWhenExpectationManagerIsNullShouldThrowException() { + void createWhenExpectationManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) .withMessageContaining("ExpectationManager must not be null"); } @Test - public void expectRequestShouldDelegateToExpectationManager() { + void expectRequestShouldDelegateToExpectationManager() { ExpectedCount count = ExpectedCount.once(); RequestMatcher requestMatcher = mock(RequestMatcher.class); this.manager.expectRequest(count, requestMatcher); @@ -88,7 +88,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception { + void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI("https://spring.io/test")); this.manager.validateRequest(request); @@ -96,7 +96,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception { + void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); this.manager.validateRequest(request); @@ -107,7 +107,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() throws Exception { + void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() throws Exception { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); given(this.delegate.validateRequest(any(ClientHttpRequest.class))) @@ -117,27 +117,27 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void resetRequestShouldDelegateToExpectationManager() { + void resetRequestShouldDelegateToExpectationManager() { this.manager.reset(); verify(this.delegate).reset(); } @Test - public void bindToShouldReturnMockRestServiceServer() { + void bindToShouldReturnMockRestServiceServer() { RestTemplate restTemplate = new RestTemplateBuilder().build(); MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate); assertThat(bound).isNotNull(); } @Test - public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() { + void bindToWithExpectationManagerShouldReturnMockRestServiceServer() { RestTemplate restTemplate = new RestTemplateBuilder().build(); MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate, this.delegate); assertThat(bound).isNotNull(); } @Test - public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() { + void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() { RestTemplate restTemplate = new RestTemplateBuilder().rootUri(this.uri).build(); RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, this.delegate); @@ -146,7 +146,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() { + void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() { RestTemplate restTemplate = new RestTemplateBuilder().build(); RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate, this.delegate); @@ -154,7 +154,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void boundRestTemplateShouldPrefixRootUri() { + void boundRestTemplateShouldPrefixRootUri() { RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); @@ -162,7 +162,7 @@ public class RootUriRequestExpectationManagerTests { } @Test - public void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() { + void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() { RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build(); MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java index 42807606eb1..80106793a39 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerIntegrationTests.java @@ -44,13 +44,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class TestRestTemplateContextCustomizerIntegrationTests { +class TestRestTemplateContextCustomizerIntegrationTests { @Autowired private TestRestTemplate restTemplate; @Test - public void test() { + void test() { assertThat(this.restTemplate.getForObject("/", String.class)).contains("hello"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java index 990c18d6185..b033cee4a47 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java @@ -36,11 +36,11 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class TestRestTemplateContextCustomizerTests { +class TestRestTemplateContextCustomizerTests { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void whenContextIsNotABeanDefinitionRegistryTestRestTemplateIsRegistered() { + void whenContextIsNotABeanDefinitionRegistryTestRestTemplateIsRegistered() { new ApplicationContextRunner(TestApplicationContext::new).withInitializer((context) -> { MergedContextConfiguration configuration = mock(MergedContextConfiguration.class); given(configuration.getTestClass()).willReturn((Class) TestClass.class); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java index 08f2f14fe0b..e71d6a17973 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithFactoryBeanTests.java @@ -38,13 +38,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = TestRestTemplateContextCustomizerWithFactoryBeanTests.TestClassWithFactoryBean.class, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class TestRestTemplateContextCustomizerWithFactoryBeanTests { +class TestRestTemplateContextCustomizerWithFactoryBeanTests { @Autowired private TestRestTemplate restTemplate; @Test - public void test() { + void test() { assertThat(this.restTemplate).isNotNull(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java index 4e143cd23b0..e66f47e6035 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java @@ -45,13 +45,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext -public class TestRestTemplateContextCustomizerWithOverrideIntegrationTests { +class TestRestTemplateContextCustomizerWithOverrideIntegrationTests { @Autowired private TestRestTemplate restTemplate; @Test - public void test() { + void test() { assertThat(this.restTemplate).isInstanceOf(CustomTestRestTemplate.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index e4d7c0745bc..c22a89eded8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -66,10 +66,10 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Kristine Jetzke */ -public class TestRestTemplateTests { +class TestRestTemplateTests { @Test - public void fromRestTemplateBuilder() { + void fromRestTemplateBuilder() { RestTemplateBuilder builder = mock(RestTemplateBuilder.class); RestTemplate delegate = new RestTemplate(); given(builder.build()).willReturn(delegate); @@ -77,14 +77,14 @@ public class TestRestTemplateTests { } @Test - public void simple() { + void simple() { // The Apache client is on the classpath so we get the fully-fledged factory assertThat(new TestRestTemplate().getRestTemplate().getRequestFactory()) .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test - public void doNotReplaceCustomRequestFactory() { + void doNotReplaceCustomRequestFactory() { RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(OkHttp3ClientHttpRequestFactory.class); TestRestTemplate testRestTemplate = new TestRestTemplate(builder); assertThat(testRestTemplate.getRestTemplate().getRequestFactory()) @@ -92,7 +92,7 @@ public class TestRestTemplateTests { } @Test - public void useTheSameRequestFactoryClassWithBasicAuth() { + void useTheSameRequestFactoryClassWithBasicAuth() { OkHttp3ClientHttpRequestFactory customFactory = new OkHttp3ClientHttpRequestFactory(); RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(() -> customFactory); TestRestTemplate testRestTemplate = new TestRestTemplate(builder).withBasicAuth("test", "test"); @@ -103,14 +103,14 @@ public class TestRestTemplateTests { } @Test - public void getRootUriRootUriSetViaRestTemplateBuilder() { + void getRootUriRootUriSetViaRestTemplateBuilder() { String rootUri = "https://example.com"; RestTemplateBuilder delegate = new RestTemplateBuilder().rootUri(rootUri); assertThat(new TestRestTemplate(delegate).getRootUri()).isEqualTo(rootUri); } @Test - public void getRootUriRootUriSetViaLocalHostUriTemplateHandler() { + void getRootUriRootUriSetViaLocalHostUriTemplateHandler() { String rootUri = "https://example.com"; TestRestTemplate template = new TestRestTemplate(); LocalHostUriTemplateHandler templateHandler = mock(LocalHostUriTemplateHandler.class); @@ -120,19 +120,19 @@ public class TestRestTemplateTests { } @Test - public void getRootUriRootUriNotSet() { + void getRootUriRootUriNotSet() { assertThat(new TestRestTemplate().getRootUri()).isEqualTo(""); } @Test - public void authenticated() { + void authenticated() { RestTemplate restTemplate = new TestRestTemplate("user", "password").getRestTemplate(); ClientHttpRequestFactory factory = restTemplate.getRequestFactory(); assertThat(factory.getClass().getName()).contains("BasicAuthentication"); } @Test - public void options() { + void options() { TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template .getRestTemplate().getRequestFactory(); @@ -141,7 +141,7 @@ public class TestRestTemplateTests { } @Test - public void restOperationsAreAvailable() { + void restOperationsAreAvailable() { RestTemplate delegate = mock(RestTemplate.class); given(delegate.getRequestFactory()).willReturn(new SimpleClientHttpRequestFactory()); given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriBuilderFactory()); @@ -201,7 +201,7 @@ public class TestRestTemplateTests { } @Test - public void withBasicAuthAddsBasicAuthClientFactoryWhenNotAlreadyPresent() { + void withBasicAuthAddsBasicAuthClientFactoryWhenNotAlreadyPresent() { TestRestTemplate original = new TestRestTemplate(); TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); assertThat(getConverterClasses(original)).containsExactlyElementsOf(getConverterClasses(basicAuth)); @@ -213,7 +213,7 @@ public class TestRestTemplateTests { } @Test - public void withBasicAuthReplacesBasicAuthClientFactoryWhenAlreadyPresent() { + void withBasicAuthReplacesBasicAuthClientFactoryWhenAlreadyPresent() { TestRestTemplate original = new TestRestTemplate("foo", "bar").withBasicAuth("replace", "replace"); TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); assertThat(getConverterClasses(basicAuth)).containsExactlyElementsOf(getConverterClasses(original)); @@ -230,7 +230,7 @@ public class TestRestTemplateTests { } @Test - public void withBasicAuthShouldUseNoOpErrorHandler() throws Exception { + void withBasicAuthShouldUseNoOpErrorHandler() throws Exception { TestRestTemplate originalTemplate = new TestRestTemplate("foo", "bar"); ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); originalTemplate.getRestTemplate().setErrorHandler(errorHandler); @@ -240,90 +240,90 @@ public class TestRestTemplateTests { } @Test - public void deleteHandlesRelativeUris() throws IOException { + void deleteHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(TestRestTemplate::delete); } @Test - public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { + void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); } @Test - public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { + void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange( new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { })); } @Test - public void exchangeHandlesRelativeUris() throws IOException { + void exchangeHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class)); } @Test - public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException { + void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<>(new byte[0]), new ParameterizedTypeReference() { })); } @Test - public void executeHandlesRelativeUris() throws IOException { + void executeHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null)); } @Test - public void getForEntityHandlesRelativeUris() throws IOException { + void getForEntityHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.getForEntity(relativeUri, String.class)); } @Test - public void getForObjectHandlesRelativeUris() throws IOException { + void getForObjectHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.getForObject(relativeUri, String.class)); } @Test - public void headForHeadersHandlesRelativeUris() throws IOException { + void headForHeadersHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(TestRestTemplate::headForHeaders); } @Test - public void optionsForAllowHandlesRelativeUris() throws IOException { + void optionsForAllowHandlesRelativeUris() throws IOException { verifyRelativeUriHandling(TestRestTemplate::optionsForAllow); } @Test - public void patchForObjectHandlesRelativeUris() throws IOException { + void patchForObjectHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.patchForObject(relativeUri, "hello", String.class)); } @Test - public void postForEntityHandlesRelativeUris() throws IOException { + void postForEntityHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.postForEntity(relativeUri, "hello", String.class)); } @Test - public void postForLocationHandlesRelativeUris() throws IOException { + void postForLocationHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.postForLocation(relativeUri, "hello")); } @Test - public void postForObjectHandlesRelativeUris() throws IOException { + void postForObjectHandlesRelativeUris() throws IOException { verifyRelativeUriHandling( (testRestTemplate, relativeUri) -> testRestTemplate.postForObject(relativeUri, "hello", String.class)); } @Test - public void putHandlesRelativeUris() throws IOException { + void putHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.put(relativeUri, "hello")); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index d5b514e1121..ff9dfabc57e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @SuppressWarnings("resource") -public class LocalHostWebClientTests { +class LocalHostWebClientTests { @Captor private ArgumentCaptor requestCaptor; @@ -54,13 +54,13 @@ public class LocalHostWebClientTests { } @Test - public void createWhenEnvironmentIsNullWillThrowException() { + void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null)) .withMessageContaining("Environment must not be null"); } @Test - public void getPageWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { + void getPageWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { MockEnvironment environment = new MockEnvironment(); WebClient client = new LocalHostWebClient(environment); WebConnection connection = mockConnection(); @@ -71,7 +71,7 @@ public class LocalHostWebClientTests { } @Test - public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { + void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); WebClient client = new LocalHostWebClient(environment); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index 52e78017283..09c82005f3b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -45,7 +45,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class LocalHostWebConnectionHtmlUnitDriverTests { +class LocalHostWebConnectionHtmlUnitDriverTests { @Mock private WebClient webClient; @@ -57,26 +57,26 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { } @Test - public void createWhenEnvironmentIsNullWillThrowException() { + void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) .withMessageContaining("Environment must not be null"); } @Test - public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { + void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) .withMessageContaining("Environment must not be null"); } @Test - public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { + void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) .withMessageContaining("Environment must not be null"); } @Test - public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() { + void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() { Capabilities capabilities = mock(Capabilities.class); given(capabilities.getBrowserName()).willReturn("htmlunit"); given(capabilities.getVersion()).willReturn("chrome"); @@ -86,7 +86,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { } @Test - public void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { + void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception { MockEnvironment environment = new MockEnvironment(); LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); @@ -94,7 +94,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { } @Test - public void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { + void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("local.server.port", "8181"); LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java index 16d679a0143..03d157ba975 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerIntegrationTests.java @@ -41,13 +41,13 @@ import org.springframework.test.web.reactive.server.WebTestClient; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") @DirtiesContext -public class WebTestClientContextCustomizerIntegrationTests { +class WebTestClientContextCustomizerIntegrationTests { @Autowired private WebTestClient webTestClient; @Test - public void test() { + void test() { this.webTestClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java index f2213f5c758..3d223008f1d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerWithOverrideIntegrationTests.java @@ -45,13 +45,13 @@ import static org.mockito.Mockito.mock; */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") @DirtiesContext -public class WebTestClientContextCustomizerWithOverrideIntegrationTests { +class WebTestClientContextCustomizerWithOverrideIntegrationTests { @Autowired private WebTestClient webTestClient; @Test - public void test() { + void test() { assertThat(this.webTestClient).isInstanceOf(CustomWebTestClient.class); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java index c498b6f6189..8272c99875e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java @@ -16,15 +16,15 @@ package org.springframework.boot.autoconfigureprocessor; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.testsupport.compiler.TestCompiler; @@ -35,20 +35,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class AutoConfigureAnnotationProcessorTests { +class AutoConfigureAnnotationProcessorTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private TestCompiler compiler; - @Before + @BeforeEach public void createCompiler() throws IOException { - this.compiler = new TestCompiler(this.temporaryFolder); + this.compiler = new TestCompiler(this.tempDir); } @Test - public void annotatedClass() throws Exception { + void annotatedClass() throws Exception { Properties properties = compile(TestClassConfiguration.class); assertThat(properties).hasSize(6); assertThat(properties).containsEntry( @@ -71,7 +71,7 @@ public class AutoConfigureAnnotationProcessorTests { } @Test - public void annotatedClassWithOnBeanThatHasName() throws Exception { + void annotatedClassWithOnBeanThatHasName() throws Exception { Properties properties = compile(TestOnBeanWithNameClassConfiguration.class); assertThat(properties).hasSize(3); assertThat(properties).containsEntry( @@ -80,7 +80,7 @@ public class AutoConfigureAnnotationProcessorTests { } @Test - public void annotatedMethod() throws Exception { + void annotatedMethod() throws Exception { Properties properties = compile(TestMethodConfiguration.class); List matching = new ArrayList<>(); for (Object key : properties.keySet()) { @@ -94,7 +94,7 @@ public class AutoConfigureAnnotationProcessorTests { } @Test - public void annotatedClassWithOrder() throws Exception { + void annotatedClassWithOrder() throws Exception { Properties properties = compile(TestOrderedClassConfiguration.class); assertThat(properties).containsEntry( "org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.ConditionalOnClass", diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java index 422a6b155e3..4204d3332f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/CompoundConfigurationTableEntryTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationdocs; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java index 735341049a5..a09e84d0733 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/ConfigurationTableTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationdocs; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java index 2e9a06de839..217e1df2078 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-docs/src/test/java/org/springframework/boot/configurationdocs/SingleConfigurationTableEntryTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationdocs; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index aa496c37cdb..6863f408b43 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -20,7 +20,7 @@ import java.io.IOException; import java.io.InputStream; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -30,16 +30,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Stephane Nicoll */ -public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests { +class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests { @Test - public void nullResource() throws IOException { + void nullResource() throws IOException { assertThatIllegalArgumentException() .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); } @Test - public void simpleRepository() throws IOException { + void simpleRepository() throws IOException { try (InputStream foo = getInputStreamFor("foo")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo).build(); validateFoo(repo); @@ -50,7 +50,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void hintsOnMaps() throws IOException { + void hintsOnMaps() throws IOException { try (InputStream map = getInputStreamFor("map")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(map).build(); validateMap(repo); @@ -62,7 +62,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void severalRepositoriesNoConflict() throws IOException { + void severalRepositoriesNoConflict() throws IOException { try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, bar).build(); validateFoo(repo); @@ -75,7 +75,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void repositoryWithRoot() throws IOException { + void repositoryWithRoot() throws IOException { try (InputStream foo = getInputStreamFor("foo"); InputStream root = getInputStreamFor("root")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, root).build(); validateFoo(repo); @@ -88,7 +88,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void severalRepositoriesIdenticalGroups() throws IOException { + void severalRepositoriesIdenticalGroups() throws IOException { try (InputStream foo = getInputStreamFor("foo"); InputStream foo2 = getInputStreamFor("foo2")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, foo2).build(); assertThat(repo.getAllGroups()).hasSize(1); @@ -105,7 +105,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void emptyGroups() throws IOException { + void emptyGroups() throws IOException { try (InputStream in = getInputStreamFor("empty-groups")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build(); validateEmptyGroup(repo); @@ -116,7 +116,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void multiGroups() throws IOException { + void multiGroups() throws IOException { try (InputStream in = getInputStreamFor("multi-groups")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build(); assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry", "test.group.two.retry", @@ -134,7 +134,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon } @Test - public void builderInstancesAreIsolated() throws IOException { + void builderInstancesAreIsolated() throws IOException { try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) { ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo).build(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index e202e35eaa2..e7e232054a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import org.json.JSONException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -32,26 +32,26 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Stephane Nicoll */ -public class JsonReaderTests extends AbstractConfigurationMetadataTests { +class JsonReaderTests extends AbstractConfigurationMetadataTests { private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private final JsonReader reader = new JsonReader(); @Test - public void emptyMetadata() throws IOException { + void emptyMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("empty"); assertThat(rawMetadata.getSources()).isEmpty(); assertThat(rawMetadata.getItems()).isEmpty(); } @Test - public void invalidMetadata() throws IOException { + void invalidMetadata() throws IOException { assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")).withCauseInstanceOf(JSONException.class); } @Test - public void emptyGroupName() throws IOException { + void emptyGroupName() throws IOException { RawConfigurationMetadata rawMetadata = readFor("empty-groups"); List items = rawMetadata.getItems(); assertThat(items).hasSize(2); @@ -63,7 +63,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { } @Test - public void simpleMetadata() throws IOException { + void simpleMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("foo"); List sources = rawMetadata.getSources(); assertThat(sources).hasSize(2); @@ -104,7 +104,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { } @Test - public void metadataHints() throws IOException { + void metadataHints() throws IOException { RawConfigurationMetadata rawMetadata = readFor("bar"); List hints = rawMetadata.getHints(); assertThat(hints).hasSize(1); @@ -130,7 +130,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { } @Test - public void rootMetadata() throws IOException { + void rootMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("root"); List sources = rawMetadata.getSources(); assertThat(sources).isEmpty(); @@ -141,7 +141,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { } @Test - public void deprecatedMetadata() throws IOException { + void deprecatedMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("deprecated"); List items = rawMetadata.getItems(); assertThat(items).hasSize(5); @@ -185,7 +185,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { } @Test - public void multiGroupsMetadata() throws IOException { + void multiGroupsMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("multi-groups"); List items = rawMetadata.getItems(); assertThat(items).hasSize(3); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java index f8cc2bf271f..4c30673e523 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationmetadata; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,46 +25,46 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class SentenceExtractorTests { +class SentenceExtractorTests { private static final String NEW_LINE = System.lineSeparator(); private SentenceExtractor extractor = new SentenceExtractor(); @Test - public void extractFirstSentence() { + void extractFirstSentence() { String sentence = this.extractor.getFirstSentence("My short " + "description. More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test - public void extractFirstSentenceNewLineBeforeDot() { + void extractFirstSentenceNewLineBeforeDot() { String sentence = this.extractor .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test - public void extractFirstSentenceNewLineBeforeDotWithSpaces() { + void extractFirstSentenceNewLineBeforeDotWithSpaces() { String sentence = this.extractor .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test - public void extractFirstSentenceNoDot() { + void extractFirstSentenceNoDot() { String sentence = this.extractor.getFirstSentence("My short description"); assertThat(sentence).isEqualTo("My short description"); } @Test - public void extractFirstSentenceNoDotMultipleLines() { + void extractFirstSentenceNoDotMultipleLines() { String sentence = this.extractor.getFirstSentence("My short description " + NEW_LINE + " More stuff"); assertThat(sentence).isEqualTo("My short description"); } @Test - public void extractFirstSentenceNull() { + void extractFirstSentenceNull() { assertThat(this.extractor.getFirstSentence(null)).isNull(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java index bbd10ac9597..5637142e3d9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java @@ -16,11 +16,11 @@ package org.springframework.boot.configurationprocessor; +import java.io.File; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.test.TestConfigurationMetadataAnnotationProcessor; @@ -33,14 +33,14 @@ import org.springframework.boot.testsupport.compiler.TestCompiler; */ public abstract class AbstractMetadataGenerationTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private TestCompiler compiler; - @Before + @BeforeEach public void createCompiler() throws IOException { - this.compiler = new TestCompiler(this.temporaryFolder); + this.compiler = new TestCompiler(this.tempDir); } protected TestCompiler getCompiler() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index da20b1a979e..0b1509d318c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -62,16 +62,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Kris De Volder * @author Jonas Keßler */ -public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests { +class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests { @Test - public void notAnnotated() { + void notAnnotated() { ConfigurationMetadata metadata = compile(NotAnnotated.class); assertThat(metadata.getItems()).isEmpty(); } @Test - public void simpleProperties() { + void simpleProperties() { ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) @@ -85,7 +85,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void simplePrefixValueProperties() { + void simplePrefixValueProperties() { ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class)); assertThat(metadata) @@ -93,7 +93,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void simpleTypeProperties() { + void simpleTypeProperties() { ConfigurationMetadata metadata = compile(SimpleTypeProperties.class); assertThat(metadata).has(Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class)); @@ -122,7 +122,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void hierarchicalProperties() { + void hierarchicalProperties() { ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class); assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); @@ -135,7 +135,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void descriptionProperties() { + void descriptionProperties() { ConfigurationMetadata metadata = compile(DescriptionProperties.class); assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class)); assertThat(metadata).has(Metadata.withProperty("description.simple", String.class) @@ -147,7 +147,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad @Test @SuppressWarnings("deprecation") - public void deprecatedProperties() { + void deprecatedProperties() { Class type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); @@ -158,7 +158,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void singleDeprecatedProperty() { + void singleDeprecatedProperty() { Class type = DeprecatedSingleProperty.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); @@ -168,7 +168,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void deprecatedOnUnrelatedSetter() { + void deprecatedOnUnrelatedSetter() { Class type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); @@ -179,7 +179,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void boxingOnSetter() { + void boxingOnSetter() { Class type = BoxingPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); @@ -189,7 +189,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void parseCollectionConfig() { + void parseCollectionConfig() { ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class); // getter and setter assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names", @@ -206,7 +206,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void parseArrayConfig() throws Exception { + void parseArrayConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleArrayProperties.class); assertThat(metadata).has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class)); assertThat(metadata).has(Metadata.withProperty("array.primitive", "java.lang.Integer[]")); @@ -219,7 +219,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void annotatedGetter() { + void annotatedGetter() { ConfigurationMetadata metadata = compile(AnnotatedGetter.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class)); assertThat(metadata) @@ -227,7 +227,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void staticAccessor() { + void staticAccessor() { ConfigurationMetadata metadata = compile(StaticAccessor.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class)); assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class) @@ -238,13 +238,13 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void innerClassRootConfig() { + void innerClassRootConfig() { ConfigurationMetadata metadata = compile(InnerClassRootConfig.class); assertThat(metadata).has(Metadata.withProperty("config.name")); } @Test - public void innerClassProperties() { + void innerClassProperties() { ConfigurationMetadata metadata = compile(InnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) @@ -263,7 +263,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void innerClassPropertiesHierarchical() { + void innerClassPropertiesHierarchical() { ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class); assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class)); assertThat(metadata) @@ -275,7 +275,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void innerClassAnnotatedGetterConfig() { + void innerClassAnnotatedGetterConfig() { ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class); assertThat(metadata).has(Metadata.withProperty("specific.value")); assertThat(metadata).has(Metadata.withProperty("foo.name")); @@ -283,7 +283,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void nestedClassChildProperties() { + void nestedClassChildProperties() { ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class); assertThat(metadata).has( Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); @@ -294,13 +294,13 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void builderPojo() { + void builderPojo() { ConfigurationMetadata metadata = compile(BuilderPojo.class); assertThat(metadata).has(Metadata.withProperty("builder.name")); } @Test - public void excludedTypesPojo() { + void excludedTypesPojo() { ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class); assertThat(metadata).has(Metadata.withProperty("excluded.name")); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.class-loader")); @@ -311,14 +311,14 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void invalidAccessor() { + void invalidAccessor() { ConfigurationMetadata metadata = compile(InvalidAccessorProperties.class); assertThat(metadata).has(Metadata.withGroup("config")); assertThat(metadata.getItems()).hasSize(1); } @Test - public void doubleRegistration() { + void doubleRegistration() { ConfigurationMetadata metadata = compile(DoubleRegistrationProperties.class); assertThat(metadata).has(Metadata.withGroup("one")); assertThat(metadata).has(Metadata.withGroup("two")); @@ -328,25 +328,25 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad } @Test - public void invalidDoubleRegistration() { + void invalidDoubleRegistration() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) .withMessageContaining("Compilation failed"); } @Test - public void constructorParameterPropertyWithInvalidDefaultValueOnNumber() { + void constructorParameterPropertyWithInvalidDefaultValueOnNumber() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) .withMessageContaining("Compilation failed"); } @Test - public void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() { + void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class)) .withMessageContaining("Compilation failed"); } @Test - public void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() { + void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() { assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) .withMessageContaining("Compilation failed"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java index 94b9bc889b0..d3d6589315c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java @@ -26,7 +26,7 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationsample.immutable.ImmutableCollectionProperties; import org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties; @@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTests { +class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTests { @Test - public void constructorParameterSimpleProperty() throws IOException { + void constructorParameterSimpleProperty() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -58,7 +58,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterNestedPropertySameClass() throws IOException { + void constructorParameterNestedPropertySameClass() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -71,7 +71,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterNestedPropertyWithAnnotation() throws IOException { + void constructorParameterNestedPropertyWithAnnotation() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); @@ -84,7 +84,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException { + void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); @@ -97,7 +97,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterMetadataSimpleProperty() throws IOException { + void constructorParameterMetadataSimpleProperty() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); @@ -107,7 +107,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterMetadataNestedGroup() throws IOException { + void constructorParameterMetadataNestedGroup() throws IOException { process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -119,7 +119,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterDeprecatedPropertyOnGetter() throws IOException { + void constructorParameterDeprecatedPropertyOnGetter() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ExecutableElement getter = getMethod(ownerElement, "isFlag"); @@ -132,7 +132,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithDescription() throws IOException { + void constructorParameterPropertyWithDescription() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -142,7 +142,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithDefaultValue() throws IOException { + void constructorParameterPropertyWithDefaultValue() throws IOException { process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -151,7 +151,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithPrimitiveTypes() throws IOException { + void constructorParameterPropertyWithPrimitiveTypes() throws IOException { process(ImmutablePrimitiveProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(false); @@ -166,7 +166,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException { + void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException { process(ImmutablePrimitiveWithDefaultsProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); @@ -181,7 +181,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException { + void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException { process(ImmutablePrimitiveWrapperWithDefaultsProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); @@ -196,7 +196,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip } @Test - public void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException { + void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException { process(ImmutableCollectionProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java index 37b6489e89a..09c5f03d8fa 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.configurationprocessor; import java.time.Duration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { +class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void simpleEndpoint() { + void simpleEndpoint() { ConfigurationMetadata metadata = compile(SimpleEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class)); assertThat(metadata).has(enabledFlag("simple", true)); @@ -49,7 +49,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void disableEndpoint() { + void disableEndpoint() { ConfigurationMetadata metadata = compile(DisabledEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled").fromSource(DisabledEndpoint.class)); assertThat(metadata).has(enabledFlag("disabled", false)); @@ -57,7 +57,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void enabledEndpoint() { + void enabledEndpoint() { ConfigurationMetadata metadata = compile(EnabledEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled").fromSource(EnabledEndpoint.class)); assertThat(metadata).has(enabledFlag("enabled", true)); @@ -65,7 +65,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void customPropertiesEndpoint() { + void customPropertiesEndpoint() { ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); @@ -77,7 +77,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void specificEndpoint() { + void specificEndpoint() { ConfigurationMetadata metadata = compile(SpecificEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); assertThat(metadata).has(enabledFlag("specific", true)); @@ -86,7 +86,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void camelCaseEndpoint() { + void camelCaseEndpoint() { ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); @@ -95,8 +95,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class); + void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception { + TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); @@ -114,8 +114,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void incrementalEndpointBuildChangeCacheFlag() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class); + void incrementalEndpointBuildChangeCacheFlag() throws Exception { + TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); @@ -131,8 +131,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, SpecificEndpoint.class); + void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception { + TestProject project = new TestProject(this.tempDir, SpecificEndpoint.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); assertThat(metadata).has(enabledFlag("specific", true)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java index cdf294092de..0643c22cc0e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { +class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void simpleGenericProperties() { + void simpleGenericProperties() { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) @@ -50,7 +50,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void complexGenericProperties() { + void complexGenericProperties() { ConfigurationMetadata metadata = compile(ComplexGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) @@ -62,7 +62,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void unresolvedGenericProperties() { + void unresolvedGenericProperties() { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) @@ -75,7 +75,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void genericTypes() { + void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); assertThat(metadata).has(Metadata.withGroup("generic") .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); @@ -100,7 +100,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT } @Test - public void wildcardTypes() { + void wildcardTypes() { ConfigurationMetadata metadata = compile(WildcardConfig.class); assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java index 785bed5df1d..c2de06ba0c2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests { +class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void immutableSimpleProperties() { + void immutableSimpleProperties() { ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class)); assertThat(metadata).has( diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java index 7c4cf0aa36b..dd7b1b6e789 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -31,11 +31,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests { +class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void incrementalBuild() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); + void incrementalBuild() throws Exception { + TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse(); ConfigurationMetadata metadata = project.fullBuild(); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue(); @@ -61,8 +61,8 @@ public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGen } @Test - public void incrementalBuildAnnotationRemoved() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); + void incrementalBuildAnnotationRemoved() throws Exception { + TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0)); @@ -73,8 +73,8 @@ public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGen } @Test - public void incrementalBuildTypeRenamed() throws Exception { - TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); + void incrementalBuildTypeRenamed() throws Exception { + TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); assertThat(metadata) .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java index 9c2254dc055..a4ced722c79 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java @@ -22,7 +22,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationsample.simple.DeprecatedSingleProperty; import org.springframework.boot.configurationsample.simple.SimpleCollectionProperties; @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { +class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test - public void javaBeanSimpleProperty() throws IOException { + void javaBeanSimpleProperty() throws IOException { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); @@ -54,7 +54,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanCollectionProperty() throws IOException { + void javaBeanCollectionProperty() throws IOException { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); @@ -67,7 +67,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanNestedPropertySameClass() throws IOException { + void javaBeanNestedPropertySameClass() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -80,7 +80,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanNestedPropertyWithAnnotation() throws IOException { + void javaBeanNestedPropertyWithAnnotation() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); @@ -93,7 +93,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException { + void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); ExecutableElement getter = getMethod(ownerElement, "getSize"); @@ -110,7 +110,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException { + void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); VariableElement field = getField(ownerElement, "counter"); @@ -126,7 +126,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanMetadataSimpleProperty() throws IOException { + void javaBeanMetadataSimpleProperty() throws IOException { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); @@ -136,7 +136,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanMetadataCollectionProperty() throws IOException { + void javaBeanMetadataCollectionProperty() throws IOException { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); @@ -147,7 +147,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanMetadataNestedGroup() throws IOException { + void javaBeanMetadataNestedGroup() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -159,7 +159,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException { + void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); VariableElement field = getField(ownerElement, "counter"); @@ -171,7 +171,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { @Test @SuppressWarnings("deprecation") - public void javaBeanDeprecatedPropertyOnClass() throws IOException { + void javaBeanDeprecatedPropertyOnClass() throws IOException { process(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement( @@ -182,7 +182,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException { + void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException { process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); @@ -192,7 +192,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanDeprecatedPropertyOnGetter() throws IOException { + void javaBeanDeprecatedPropertyOnGetter() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "flag", "isFlag", "setFlag"); @@ -201,7 +201,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanDeprecatedPropertyOnSetter() throws IOException { + void javaBeanDeprecatedPropertyOnSetter() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -210,7 +210,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanPropertyWithDescription() throws IOException { + void javaBeanPropertyWithDescription() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -220,7 +220,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void javaBeanPropertyWithDefaultValue() throws IOException { + void javaBeanPropertyWithDefaultValue() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java index 73acdf3566b..943fcd1c433 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -38,56 +38,56 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { +class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void lombokDataProperties() { + void lombokDataProperties() { ConfigurationMetadata metadata = compile(LombokSimpleDataProperties.class); assertSimpleLombokProperties(metadata, LombokSimpleDataProperties.class, "data"); } @Test - public void lombokSimpleProperties() { + void lombokSimpleProperties() { ConfigurationMetadata metadata = compile(LombokSimpleProperties.class); assertSimpleLombokProperties(metadata, LombokSimpleProperties.class, "simple"); } @Test - public void lombokExplicitProperties() { + void lombokExplicitProperties() { ConfigurationMetadata metadata = compile(LombokExplicitProperties.class); assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit"); assertThat(metadata.getItems()).hasSize(6); } @Test - public void lombokAccessLevelProperties() { + void lombokAccessLevelProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelProperties.class); assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, "accesslevel", 2); } @Test - public void lombokAccessLevelOverwriteDataProperties() { + void lombokAccessLevelOverwriteDataProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDataProperties.class); assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDataProperties.class, "accesslevel.overwrite.data"); } @Test - public void lombokAccessLevelOverwriteExplicitProperties() { + void lombokAccessLevelOverwriteExplicitProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteExplicitProperties.class); assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteExplicitProperties.class, "accesslevel.overwrite.explicit"); } @Test - public void lombokAccessLevelOverwriteDefaultProperties() { + void lombokAccessLevelOverwriteDefaultProperties() { ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDefaultProperties.class); assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDefaultProperties.class, "accesslevel.overwrite.default"); } @Test - public void lombokInnerClassProperties() { + void lombokInnerClassProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) @@ -111,7 +111,7 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes } @Test - public void lombokInnerClassWithGetterProperties() { + void lombokInnerClassWithGetterProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class)); assertThat(metadata) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java index fd775fac688..21bddfaaaf2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java @@ -22,7 +22,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationsample.lombok.LombokDefaultValueProperties; import org.springframework.boot.configurationsample.lombok.LombokDeprecatedSingleProperty; @@ -40,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { +class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test - public void lombokSimpleProperty() throws IOException { + void lombokSimpleProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); @@ -56,7 +56,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokCollectionProperty() throws IOException { + void lombokCollectionProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); @@ -69,7 +69,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokNestedPropertySameClass() throws IOException { + void lombokNestedPropertySameClass() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -82,7 +82,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokNestedPropertyWithAnnotation() throws IOException { + void lombokNestedPropertyWithAnnotation() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third"); @@ -95,7 +95,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException { + void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); @@ -105,7 +105,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException { + void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException { process(LombokSimpleDataProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleDataProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); @@ -115,7 +115,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException { + void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException { process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlyGetter"); @@ -125,7 +125,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException { + void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException { process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlySetter"); @@ -135,7 +135,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokMetadataSimpleProperty() throws IOException { + void lombokMetadataSimpleProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); @@ -145,7 +145,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokMetadataCollectionProperty() throws IOException { + void lombokMetadataCollectionProperty() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); @@ -156,7 +156,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokMetadataNestedGroup() throws IOException { + void lombokMetadataNestedGroup() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); VariableElement field = getField(ownerElement, "third"); @@ -171,7 +171,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokMetadataNestedGroupNoGetter() throws IOException { + void lombokMetadataNestedGroupNoGetter() throws IOException { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); @@ -183,7 +183,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException { + void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored"); @@ -193,7 +193,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { @Test @SuppressWarnings("deprecation") - public void lombokDeprecatedPropertyOnClass() throws IOException { + void lombokDeprecatedPropertyOnClass() throws IOException { process(org.springframework.boot.configurationsample.lombok.LombokDeprecatedProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement( @@ -204,7 +204,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokDeprecatedPropertyOnField() throws IOException { + void lombokDeprecatedPropertyOnField() throws IOException { process(LombokDeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokDeprecatedSingleProperty.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); @@ -213,7 +213,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokPropertyWithDescription() throws IOException { + void lombokPropertyWithDescription() throws IOException { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); @@ -222,7 +222,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokPropertyWithDefaultValue() throws IOException { + void lombokPropertyWithDefaultValue() throws IOException { process(LombokDefaultValueProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokDefaultValueProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); @@ -231,7 +231,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokPropertyNotCandidate() throws IOException { + void lombokPropertyNotCandidate() throws IOException { process(SimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); @@ -241,7 +241,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests { } @Test - public void lombokNestedPropertyNotCandidate() throws IOException { + void lombokNestedPropertyNotCandidate() throws IOException { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java index 77313795f9f..d1f433e6d41 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java @@ -24,7 +24,7 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.json.JSONArray; import org.springframework.boot.configurationprocessor.json.JSONObject; @@ -47,10 +47,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Stephane Nicoll */ -public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { +class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void mergingOfAdditionalProperty() throws Exception { + void mergingOfAdditionalProperty() throws Exception { ItemMetadata property = ItemMetadata.newProperty(null, "foo", "java.lang.String", AdditionalMetadata.class.getName(), null, null, null, null); writeAdditionalMetadata(property); @@ -60,7 +60,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfAdditionalPropertyMatchingGroup() throws Exception { + void mergingOfAdditionalPropertyMatchingGroup() throws Exception { ItemMetadata property = ItemMetadata.newProperty(null, "simple", "java.lang.String", null, null, null, null, null); writeAdditionalMetadata(property); @@ -70,7 +70,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyDefaultValue() throws Exception { + void mergeExistingPropertyDefaultValue() throws Exception { ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); @@ -80,7 +80,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyWithSeveralCandidates() throws Exception { + void mergeExistingPropertyWithSeveralCandidates() throws Exception { ItemMetadata property = ItemMetadata.newProperty("simple", "flag", Boolean.class.getName(), null, null, null, true, null); writeAdditionalMetadata(property); @@ -104,7 +104,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyDescription() throws Exception { + void mergeExistingPropertyDescription() throws Exception { ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, "A nice comparator.", null, null); writeAdditionalMetadata(property); @@ -115,7 +115,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyDeprecation() throws Exception { + void mergeExistingPropertyDeprecation() throws Exception { ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, null, null, new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error")); writeAdditionalMetadata(property); @@ -127,7 +127,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyDeprecationOverride() throws Exception { + void mergeExistingPropertyDeprecationOverride() throws Exception { ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, new ItemDeprecation("Don't use this.", "single.name")); writeAdditionalMetadata(property); @@ -138,7 +138,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeExistingPropertyDeprecationOverrideLevel() throws Exception { + void mergeExistingPropertyDeprecationOverrideLevel() throws Exception { ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null, new ItemDeprecation(null, null, "error")); writeAdditionalMetadata(property); @@ -150,7 +150,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergeOfInvalidAdditionalMetadata() throws IOException { + void mergeOfInvalidAdditionalMetadata() throws IOException { File additionalMetadataFile = createAdditionalMetadataFile(); FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile)); assertThatIllegalStateException().isThrownBy(() -> compile(SimpleProperties.class)) @@ -158,7 +158,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfSimpleHint() throws Exception { + void mergingOfSimpleHint() throws Exception { writeAdditionalHints(ItemHint.newHint("simple.the-name", new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(SimpleProperties.class); @@ -170,7 +170,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfHintWithNonCanonicalName() throws Exception { + void mergingOfHintWithNonCanonicalName() throws Exception { writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) @@ -180,7 +180,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfHintWithProvider() throws Exception { + void mergingOfHintWithProvider() throws Exception { writeAdditionalHints(new ItemHint("simple.theName", Collections.emptyList(), Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "org.foo")), new ItemHint.ValueProvider("second", null)))); @@ -193,7 +193,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfAdditionalDeprecation() throws Exception { + void mergingOfAdditionalDeprecation() throws Exception { writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null, null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); @@ -202,7 +202,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest } @Test - public void mergingOfAdditionalMetadata() throws Exception { + void mergingOfAdditionalMetadata() throws Exception { File metaInfFolder = new File(getCompiler().getOutputLocation(), "META-INF"); metaInfFolder.mkdirs(); File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java index b18a324c7f6..ea284745c23 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java @@ -22,9 +22,8 @@ import java.util.Collections; import javax.annotation.processing.ProcessingEnvironment; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -35,18 +34,18 @@ import static org.mockito.Mockito.mock; * * @author Andy Wilkinson */ -public class MetadataStoreTests { +class MetadataStoreTests { - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; private final ProcessingEnvironment environment = mock(ProcessingEnvironment.class); private final MetadataStore metadataStore = new MetadataStore(this.environment); @Test - public void additionalMetadataIsLocatedInMavenBuild() throws IOException { - File app = this.temp.newFolder("app"); + void additionalMetadataIsLocatedInMavenBuild() throws IOException { + File app = new File(this.tempDir, "app"); File classesLocation = new File(app, "target/classes"); File metaInf = new File(classesLocation, "META-INF"); metaInf.mkdirs(); @@ -58,8 +57,8 @@ public class MetadataStoreTests { } @Test - public void additionalMetadataIsLocatedInGradle3Build() throws IOException { - File app = this.temp.newFolder("app"); + void additionalMetadataIsLocatedInGradle3Build() throws IOException { + File app = new File(this.tempDir, "app"); File classesLocation = new File(app, "build/classes/main"); File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); @@ -72,8 +71,8 @@ public class MetadataStoreTests { } @Test - public void additionalMetadataIsLocatedInGradle4Build() throws IOException { - File app = this.temp.newFolder("app"); + void additionalMetadataIsLocatedInGradle4Build() throws IOException { + File app = new File(this.tempDir, "app"); File classesLocation = new File(app, "build/classes/java/main"); File resourcesLocation = new File(app, "build/resources/main"); File metaInf = new File(resourcesLocation, "META-INF"); @@ -86,8 +85,8 @@ public class MetadataStoreTests { } @Test - public void additionalMetadataIsLocatedUsingLocationsOption() throws IOException { - File app = this.temp.newFolder("app"); + void additionalMetadataIsLocatedUsingLocationsOption() throws IOException { + File app = new File(this.tempDir, "app"); File location = new File(app, "src/main/resources"); File metaInf = new File(location, "META-INF"); metaInf.mkdirs(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java index c8dd32216c2..494dd531adc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.Metadata; @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests { +class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests { @Test - public void simpleMethodConfig() { + void simpleMethodConfig() { ConfigurationMetadata metadata = compile(SimpleMethodConfig.class); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); assertThat(metadata) @@ -46,7 +46,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati } @Test - public void invalidMethodConfig() { + void invalidMethodConfig() { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); assertThat(metadata) .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); @@ -54,7 +54,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati } @Test - public void methodAndClassConfig() { + void methodAndClassConfig() { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); assertThat(metadata) .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); @@ -65,13 +65,13 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati } @Test - public void emptyTypeMethodConfig() { + void emptyTypeMethodConfig() { ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class); assertThat(metadata).isNotEqualTo(Metadata.withProperty("something.foo")); } @Test - public void deprecatedMethodConfig() { + void deprecatedMethodConfig() { Class type = DeprecatedMethodConfig.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); @@ -83,7 +83,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati @Test @SuppressWarnings("deprecation") - public void deprecatedMethodConfigOnClass() { + void deprecatedMethodConfigOnClass() { Class type = org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java index 16d319c4559..677c0c2c5c9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java @@ -16,6 +16,7 @@ package org.springframework.boot.configurationprocessor; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -27,9 +28,8 @@ import java.util.stream.Stream; import javax.lang.model.element.TypeElement; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.configurationprocessor.metadata.ItemMetadata; import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester; @@ -52,19 +52,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class PropertyDescriptorResolverTests { +class PropertyDescriptorResolverTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void propertiesWithJavaBeanProperties() throws IOException { + void propertiesWithJavaBeanProperties() throws IOException { process(SimpleProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator"))); } @Test - public void propertiesWithJavaBeanHierarchicalProperties() throws IOException { + void propertiesWithJavaBeanHierarchicalProperties() throws IOException { process(HierarchicalProperties.class, Arrays.asList(HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class), (type, metadataEnv) -> { @@ -78,31 +78,31 @@ public class PropertyDescriptorResolverTests { } @Test - public void propertiesWithLombokGetterSetterAtClassLevel() throws IOException { + void propertiesWithLombokGetterSetterAtClassLevel() throws IOException { process(LombokSimpleProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test - public void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException { + void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException { process(LombokExplicitProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test - public void propertiesWithLombokDataClass() throws IOException { + void propertiesWithLombokDataClass() throws IOException { process(LombokSimpleDataProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items"))); } @Test - public void propertiesWithConstructorParameters() throws IOException { + void propertiesWithConstructorParameters() throws IOException { process(ImmutableSimpleProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter"))); } @Test - public void propertiesWithSeveralConstructors() throws IOException { + void propertiesWithSeveralConstructors() throws IOException { process(TwoConstructorsExample.class, propertyNames((stream) -> assertThat(stream).containsExactly("name"))); process(TwoConstructorsExample.class, properties((stream) -> assertThat(stream).element(0).isInstanceOf(JavaBeanPropertyDescriptor.class))); @@ -134,7 +134,7 @@ public class PropertyDescriptorResolverTests { }; TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>( internalConsumer, new MetadataGenerationEnvironmentFactory()); - TestCompiler compiler = new TestCompiler(this.temporaryFolder); + TestCompiler compiler = new TestCompiler(this.tempDir); ArrayList> allClasses = new ArrayList<>(); allClasses.add(target); allClasses.addAll(additionalClasses); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java index b715f2122bd..e1e885297ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java @@ -16,6 +16,7 @@ package org.springframework.boot.configurationprocessor; +import java.io.File; import java.io.IOException; import java.util.function.BiConsumer; @@ -25,8 +26,7 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.configurationprocessor.test.ItemMetadataAssert; import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester; @@ -40,8 +40,8 @@ import org.springframework.boot.testsupport.compiler.TestCompiler; */ public abstract class PropertyDescriptorTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; protected String createAccessorMethodName(String prefix, String name) { char[] chars = name.toCharArray(); @@ -70,7 +70,7 @@ public abstract class PropertyDescriptorTests { throws IOException { TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>( consumer, new MetadataGenerationEnvironmentFactory()); - TestCompiler compiler = new TestCompiler(this.temporaryFolder); + TestCompiler compiler = new TestCompiler(this.tempDir); compiler.getTask(target).call(processor); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java index 6b733b5d836..e96b14f3a8c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java @@ -28,15 +28,13 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Assert; -import org.junit.rules.TemporaryFolder; - import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.test.TestConfigurationMetadataAnnotationProcessor; import org.springframework.boot.configurationsample.ConfigurationProperties; import org.springframework.boot.configurationsample.NestedConfigurationProperty; import org.springframework.boot.testsupport.compiler.TestCompiler; import org.springframework.boot.testsupport.compiler.TestCompiler.TestCompilationTask; +import org.springframework.util.Assert; import org.springframework.util.FileCopyUtils; import org.springframework.util.FileSystemUtils; @@ -64,9 +62,9 @@ public class TestProject { private Set sourceFiles = new LinkedHashSet<>(); - public TestProject(TemporaryFolder tempFolder, Class... classes) throws IOException { - this.sourceFolder = tempFolder.newFolder(); - this.compiler = new TestCompiler(tempFolder) { + public TestProject(File tempFolder, Class... classes) throws IOException { + this.sourceFolder = new File(tempFolder, "src"); + this.compiler = new TestCompiler(new File(tempFolder, "build")) { @Override protected File getSourceFolder() { return TestProject.this.sourceFolder; @@ -123,7 +121,7 @@ public class TestProject { * @return the output file */ public File getOutputFile(String relativePath) { - Assert.assertFalse(new File(relativePath).isAbsolute()); + Assert.isTrue(!new File(relativePath).isAbsolute(), "'" + relativePath + "' was absolute"); return new File(this.compiler.getOutputLocation(), relativePath); } @@ -158,7 +156,7 @@ public class TestProject { * @throws IOException on IO error */ public void revert(Class type) throws IOException { - Assert.assertTrue(getSourceFile(type).exists()); + Assert.isTrue(getSourceFile(type).exists(), "Source file for type '" + type + "' does not exist"); copySources(type); } @@ -168,7 +166,7 @@ public class TestProject { * @throws IOException on IO error */ public void add(Class type) throws IOException { - Assert.assertFalse(getSourceFile(type).exists()); + Assert.isTrue(!getSourceFile(type).exists(), "Source file for type '" + type + "' already exists"); copySources(type); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java index f5c701ac003..4bc54fef592 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.configurationprocessor; +import java.io.File; import java.io.IOException; import java.time.Duration; import java.util.function.BiConsumer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.configurationprocessor.TypeUtils.TypeDescriptor; import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester; @@ -39,13 +39,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class TypeUtilsTests { +class TypeUtilsTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void resolveTypeDescriptorOnConcreteClass() throws IOException { + void resolveTypeDescriptorOnConcreteClass() throws IOException { process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); @@ -59,7 +59,7 @@ public class TypeUtilsTests { } @Test - public void resolveTypeDescriptorOnIntermediateClass() throws IOException { + void resolveTypeDescriptorOnIntermediateClass() throws IOException { process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); @@ -72,7 +72,7 @@ public class TypeUtilsTests { } @Test - public void resolveTypeDescriptorWithOnlyGenerics() throws IOException { + void resolveTypeDescriptorWithOnlyGenerics() throws IOException { process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); @@ -84,7 +84,7 @@ public class TypeUtilsTests { private void process(Class target, BiConsumer consumer) throws IOException { TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>(consumer, TypeUtils::new); - TestCompiler compiler = new TestCompiler(this.temporaryFolder); + TestCompiler compiler = new TestCompiler(this.tempDir); compiler.getTask(target).call(processor); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 0e7c733562c..01143f21a96 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -16,6 +16,7 @@ package org.springframework.boot.configurationprocessor.fieldvalues; +import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -29,9 +30,8 @@ import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.configurationsample.fieldvalues.FieldValues; import org.springframework.boot.testsupport.compiler.TestCompiler; @@ -46,15 +46,15 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractFieldValuesProcessorTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; protected abstract FieldValuesParser createProcessor(ProcessingEnvironment env); @Test - public void getFieldValues() throws Exception { + void getFieldValues() throws Exception { TestProcessor processor = new TestProcessor(); - TestCompiler compiler = new TestCompiler(this.temporaryFolder); + TestCompiler compiler = new TestCompiler(this.tempDir); compiler.getTask(FieldValues.class).call(processor); Map values = processor.getValues(); assertThat(values.get("string")).isEqualTo("1"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java index 5573ab9aef1..259bf3f6237 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/javac/JavaCompilerFieldValuesProcessorTests.java @@ -18,11 +18,11 @@ package org.springframework.boot.configurationprocessor.fieldvalues.javac; import javax.annotation.processing.ProcessingEnvironment; +import org.opentest4j.TestAbortedException; + import org.springframework.boot.configurationprocessor.fieldvalues.AbstractFieldValuesProcessorTests; import org.springframework.boot.configurationprocessor.fieldvalues.FieldValuesParser; -import static org.junit.Assume.assumeNoException; - /** * Tests for {@link JavaCompilerFieldValuesParser}. * @@ -36,8 +36,7 @@ public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesPr return new JavaCompilerFieldValuesParser(env); } catch (Throwable ex) { - assumeNoException(ex); - throw new IllegalStateException(); + throw new TestAbortedException(); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java index 1bdfa8ab66a..29300885721 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor.metadata; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,55 +25,55 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConfigurationMetadataTests { +class ConfigurationMetadataTests { @Test - public void toDashedCaseCamelCase() { + void toDashedCaseCamelCase() { assertThat(toDashedCase("simpleCamelCase")).isEqualTo("simple-camel-case"); } @Test - public void toDashedCaseUpperCamelCaseSuffix() { + void toDashedCaseUpperCamelCaseSuffix() { assertThat(toDashedCase("myDLQ")).isEqualTo("my-d-l-q"); } @Test - public void toDashedCaseUpperCamelCaseMiddle() { + void toDashedCaseUpperCamelCaseMiddle() { assertThat(toDashedCase("someDLQKey")).isEqualTo("some-d-l-q-key"); } @Test - public void toDashedCaseWordsUnderscore() { + void toDashedCaseWordsUnderscore() { assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore"); } @Test - public void toDashedCaseWordsSeveralUnderscores() { + void toDashedCaseWordsSeveralUnderscores() { assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore"); } @Test - public void toDashedCaseLowerCaseUnderscore() { + void toDashedCaseLowerCaseUnderscore() { assertThat(toDashedCase("lower_underscore")).isEqualTo("lower-underscore"); } @Test - public void toDashedCaseUpperUnderscoreSuffix() { + void toDashedCaseUpperUnderscoreSuffix() { assertThat(toDashedCase("my_DLQ")).isEqualTo("my-d-l-q"); } @Test - public void toDashedCaseUpperUnderscoreMiddle() { + void toDashedCaseUpperUnderscoreMiddle() { assertThat(toDashedCase("some_DLQ_key")).isEqualTo("some-d-l-q-key"); } @Test - public void toDashedCaseMultipleUnderscores() { + void toDashedCaseMultipleUnderscores() { assertThat(toDashedCase("super___crazy")).isEqualTo("super---crazy"); } @Test - public void toDashedCaseLowercase() { + void toDashedCaseLowercase() { assertThat(toDashedCase("lowercase")).isEqualTo("lowercase"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java index 02a1467c7f5..675a4bbf7dd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ItemMetadataTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.configurationprocessor.metadata; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,20 +25,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ItemMetadataTests { +class ItemMetadataTests { @Test - public void newItemMetadataPrefixWithCapitalizedPrefix() { + void newItemMetadataPrefixWithCapitalizedPrefix() { assertThat(newItemMetadataPrefix("Prefix.", "value")).isEqualTo("prefix.value"); } @Test - public void newItemMetadataPrefixWithCamelCaseSuffix() { + void newItemMetadataPrefixWithCamelCaseSuffix() { assertThat(newItemMetadataPrefix("prefix.", "myValue")).isEqualTo("prefix.my-value"); } @Test - public void newItemMetadataPrefixWithUpperCamelCaseSuffix() { + void newItemMetadataPrefixWithUpperCamelCaseSuffix() { assertThat(newItemMetadataPrefix("prefix.", "MyValue")).isEqualTo("prefix.my-value"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 3572079362e..4f3aa76175b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -23,7 +23,7 @@ import java.io.InputStream; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class JsonMarshallerTests { +class JsonMarshallerTests { @Test - public void marshallAndUnmarshal() throws Exception { + void marshallAndUnmarshal() throws Exception { ConfigurationMetadata metadata = new ConfigurationMetadata(); metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(), "sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d"))); @@ -69,7 +69,7 @@ public class JsonMarshallerTests { } @Test - public void marshallOrderItems() throws IOException { + void marshallOrderItems() throws IOException { ConfigurationMetadata metadata = new ConfigurationMetadata(); metadata.add(ItemHint.newHint("fff")); metadata.add(ItemHint.newHint("eee")); @@ -89,7 +89,7 @@ public class JsonMarshallerTests { } @Test - public void marshallPutDeprecatedItemsAtTheEnd() throws IOException { + void marshallPutDeprecatedItemsAtTheEnd() throws IOException { ConfigurationMetadata metadata = new ConfigurationMetadata(); metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null)); metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null, diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java index 989d6ba1900..f2aa45dcb09 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java @@ -16,7 +16,6 @@ package org.springframework.boot.gradle.docs; -import org.junit.Assume; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; @@ -25,6 +24,7 @@ import org.springframework.boot.gradle.testkit.Dsl; import org.springframework.boot.gradle.testkit.GradleBuild; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumingThat; /** * Tests for the managing dependencies documentation. @@ -56,10 +56,11 @@ public class ManagingDependenciesDocumentationTests { @TestTemplate public void dependencyManagementInIsolationWithPluginsBlock() { - Assume.assumeTrue(this.gradleBuild.getDsl() == Dsl.KOTLIN); - assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins") - .build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT"); + assumingThat(this.gradleBuild.getDsl() == Dsl.KOTLIN, + () -> assertThat( + this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins") + .build("dependencyManagement").getOutput()) + .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java index 94b7898bff6..47359738ff9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java @@ -21,9 +21,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.FileCopyUtils; @@ -36,100 +35,100 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Justin Rosenberg */ -public class DefaultLaunchScriptTests { +class DefaultLaunchScriptTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void loadsDefaultScript() throws Exception { + void loadsDefaultScript() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); assertThat(content).contains("Spring Boot Startup Script"); } @Test - public void logFilenameCanBeReplaced() throws Exception { + void logFilenameCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("logFilename"); } @Test - public void pidFilenameCanBeReplaced() throws Exception { + void pidFilenameCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("pidFilename"); } @Test - public void initInfoProvidesCanBeReplaced() throws Exception { + void initInfoProvidesCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoProvides"); } @Test - public void initInfoRequiredStartCanBeReplaced() throws Exception { + void initInfoRequiredStartCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoRequiredStart"); } @Test - public void initInfoRequiredStopCanBeReplaced() throws Exception { + void initInfoRequiredStopCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoRequiredStop"); } @Test - public void initInfoDefaultStartCanBeReplaced() throws Exception { + void initInfoDefaultStartCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoDefaultStart"); } @Test - public void initInfoDefaultStopCanBeReplaced() throws Exception { + void initInfoDefaultStopCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoDefaultStop"); } @Test - public void initInfoShortDescriptionCanBeReplaced() throws Exception { + void initInfoShortDescriptionCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoShortDescription"); } @Test - public void initInfoDescriptionCanBeReplaced() throws Exception { + void initInfoDescriptionCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoDescription"); } @Test - public void initInfoChkconfigCanBeReplaced() throws Exception { + void initInfoChkconfigCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("initInfoChkconfig"); } @Test - public void modeCanBeReplaced() throws Exception { + void modeCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("mode"); } @Test - public void useStartStopDaemonCanBeReplaced() throws Exception { + void useStartStopDaemonCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("useStartStopDaemon"); } @Test - public void logFolderCanBeReplaced() throws Exception { + void logFolderCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("logFolder"); } @Test - public void pidFolderCanBeReplaced() throws Exception { + void pidFolderCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("pidFolder"); } @Test - public void confFolderCanBeReplaced() throws Exception { + void confFolderCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("confFolder"); } @Test - public void stopWaitTimeCanBeReplaced() throws Exception { + void stopWaitTimeCanBeReplaced() throws Exception { assertThatPlaceholderCanBeReplaced("stopWaitTime"); } @Test - public void inlinedConfScriptFileLoad() throws IOException { + void inlinedConfScriptFileLoad() throws IOException { DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties("inlinedConfScript:src/test/resources/example.script")); String content = new String(script.toByteArray()); @@ -137,29 +136,29 @@ public class DefaultLaunchScriptTests { } @Test - public void defaultForUseStartStopDaemonIsTrue() throws Exception { + void defaultForUseStartStopDaemonIsTrue() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); assertThat(content).contains("USE_START_STOP_DAEMON=\"true\""); } @Test - public void defaultForModeIsAuto() throws Exception { + void defaultForModeIsAuto() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); assertThat(content).contains("MODE=\"auto\""); } @Test - public void defaultForStopWaitTimeIs60() throws Exception { + void defaultForStopWaitTimeIs60() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); assertThat(content).contains("STOP_WAIT_TIME=\"60\""); } @Test - public void loadFromFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void loadFromFile() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("ABC".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); @@ -167,8 +166,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariables() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariables() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); @@ -176,8 +175,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariablesMultiLine() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariablesMultiLine() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); @@ -185,8 +184,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariablesWithDefaults() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariablesWithDefaults() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); @@ -194,8 +193,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariablesCanDefaultToBlank() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariablesCanDefaultToBlank() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("s{{p:}}{{r:}}ing".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); @@ -203,8 +202,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariablesWithDefaultsOverride() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariablesWithDefaultsOverride() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a")); String content = new String(script.toByteArray()); @@ -212,8 +211,8 @@ public class DefaultLaunchScriptTests { } @Test - public void expandVariablesMissingAreUnchanged() throws Exception { - File file = this.temporaryFolder.newFile(); + void expandVariablesMissingAreUnchanged() throws Exception { + File file = new File(this.tempDir, "script"); FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java index abc3858f628..a3ca9de31db 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java @@ -21,12 +21,9 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import org.springframework.util.FileSystemUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -36,27 +33,25 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Phillip Webb */ -public class FileUtilsTests { +class FileUtilsTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private File outputDirectory; private File originDirectory; - @Before + @BeforeEach public void init() throws IOException { - this.outputDirectory = this.temporaryFolder.newFolder("remove"); - this.originDirectory = this.temporaryFolder.newFolder("keep"); - FileSystemUtils.deleteRecursively(this.outputDirectory); - FileSystemUtils.deleteRecursively(this.originDirectory); + this.outputDirectory = new File(this.tempDir, "remove"); + this.originDirectory = new File(this.tempDir, "keep"); this.outputDirectory.mkdirs(); this.originDirectory.mkdirs(); } @Test - public void simpleDuplicateFile() throws IOException { + void simpleDuplicateFile() throws IOException { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "logback.xml").createNewFile(); @@ -65,7 +60,7 @@ public class FileUtilsTests { } @Test - public void nestedDuplicateFile() throws IOException { + void nestedDuplicateFile() throws IOException { assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue(); assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue(); File file = new File(this.outputDirectory, "sub/logback.xml"); @@ -76,7 +71,7 @@ public class FileUtilsTests { } @Test - public void nestedNonDuplicateFile() throws IOException { + void nestedNonDuplicateFile() throws IOException { assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue(); assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue(); File file = new File(this.outputDirectory, "sub/logback.xml"); @@ -87,7 +82,7 @@ public class FileUtilsTests { } @Test - public void nonDuplicateFile() throws IOException { + void nonDuplicateFile() throws IOException { File file = new File(this.outputDirectory, "logback.xml"); file.createNewFile(); new File(this.originDirectory, "different.xml").createNewFile(); @@ -96,8 +91,8 @@ public class FileUtilsTests { } @Test - public void hash() throws Exception { - File file = this.temporaryFolder.newFile(); + void hash() throws Exception { + File file = new File(this.tempDir, "file"); try (OutputStream outputStream = new FileOutputStream(file)) { outputStream.write(new byte[] { 1, 2, 3 }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 46f39050281..6145db5e221 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.loader.tools; import java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Phillip Webb * @author Andy Wilkinson */ -public class LayoutsTests { +class LayoutsTests { @Test - public void jarFile() { + void jarFile() { assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class); assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class); @@ -40,7 +40,7 @@ public class LayoutsTests { } @Test - public void warFile() { + void warFile() { assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class); assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class); @@ -48,13 +48,13 @@ public class LayoutsTests { } @Test - public void unknownFile() { + void unknownFile() { assertThatIllegalStateException().isThrownBy(() -> Layouts.forFile(new File("test.txt"))) .withMessageContaining("Unable to deduce layout for 'test.txt'"); } @Test - public void jarLayout() { + void jarLayout() { Layout layout = new Layouts.Jar(); assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("BOOT-INF/lib/"); assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("BOOT-INF/lib/"); @@ -63,7 +63,7 @@ public class LayoutsTests { } @Test - public void warLayout() { + void warLayout() { Layout layout = new Layouts.War(); assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("WEB-INF/lib/"); assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("WEB-INF/lib/"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index 1b7682c985c..68df9e437c2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -16,14 +16,14 @@ package org.springframework.boot.loader.tools; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.tools.MainClassFinder.MainClass; import org.springframework.boot.loader.tools.MainClassFinder.MainClassCallback; @@ -39,20 +39,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Phillip Webb */ -public class MainClassFinderTests { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); +class MainClassFinderTests { private TestJarFile testJarFile; - @Before - public void setup() throws IOException { - this.testJarFile = new TestJarFile(this.temporaryFolder); + @BeforeEach + public void setup(@TempDir File tempDir) throws IOException { + this.testJarFile = new TestJarFile(tempDir); } @Test - public void findMainClassInJar() throws Exception { + void findMainClassInJar() throws Exception { this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); @@ -60,7 +57,7 @@ public class MainClassFinderTests { } @Test - public void findMainClassInJarSubFolder() throws Exception { + void findMainClassInJarSubFolder() throws Exception { this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); @@ -69,7 +66,7 @@ public class MainClassFinderTests { } @Test - public void usesBreadthFirstJarSearch() throws Exception { + void usesBreadthFirstJarSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); @@ -77,7 +74,7 @@ public class MainClassFinderTests { } @Test - public void findSingleJarSearch() throws Exception { + void findSingleJarSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() @@ -87,7 +84,7 @@ public class MainClassFinderTests { } @Test - public void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception { + void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "", @@ -96,7 +93,7 @@ public class MainClassFinderTests { } @Test - public void findMainClassInJarSubLocation() throws Exception { + void findMainClassInJarSubLocation() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/"); @@ -105,7 +102,7 @@ public class MainClassFinderTests { } @Test - public void findMainClassInFolder() throws Exception { + void findMainClassInFolder() throws Exception { this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); @@ -113,7 +110,7 @@ public class MainClassFinderTests { } @Test - public void findMainClassInSubFolder() throws Exception { + void findMainClassInSubFolder() throws Exception { this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); @@ -122,7 +119,7 @@ public class MainClassFinderTests { } @Test - public void usesBreadthFirstFolderSearch() throws Exception { + void usesBreadthFirstFolderSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); @@ -130,7 +127,7 @@ public class MainClassFinderTests { } @Test - public void findSingleFolderSearch() throws Exception { + void findSingleFolderSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() @@ -140,7 +137,7 @@ public class MainClassFinderTests { } @Test - public void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception { + void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class); String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource(), @@ -149,7 +146,7 @@ public class MainClassFinderTests { } @Test - public void doWithFolderMainMethods() throws Exception { + void doWithFolderMainMethods() throws Exception { this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); @@ -160,7 +157,7 @@ public class MainClassFinderTests { } @Test - public void doWithJarMainMethods() throws Exception { + void doWithJarMainMethods() throws Exception { this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index 6604db55711..14fda1bdbf7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -37,10 +37,9 @@ import java.util.zip.ZipOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.zeroturnaround.zip.ZipUtil; import org.springframework.boot.loader.tools.sample.ClassWithMainMethod; @@ -61,7 +60,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class RepackagerTests { +class RepackagerTests { private static final Libraries NO_LIBRARIES = (callback) -> { }; @@ -79,33 +78,33 @@ public class RepackagerTests { JAN_1_1985 = calendar.getTime().getTime(); } - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private TestJarFile testJarFile; - @Before + @BeforeEach public void setup() throws IOException { - this.testJarFile = new TestJarFile(this.temporaryFolder); + this.testJarFile = new TestJarFile(this.tempDir); } @Test - public void nullSource() { + void nullSource() { assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(null)); } @Test - public void missingSource() { + void missingSource() { assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(new File("missing"))); } @Test - public void directorySource() { - assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot())); + void directorySource() { + assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.tempDir)); } @Test - public void specificMainClass() throws Exception { + void specificMainClass() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -119,7 +118,7 @@ public class RepackagerTests { } @Test - public void mainClassFromManifest() throws Exception { + void mainClassFromManifest() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); @@ -136,7 +135,7 @@ public class RepackagerTests { } @Test - public void mainClassFound() throws Exception { + void mainClassFound() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -149,7 +148,7 @@ public class RepackagerTests { } @Test - public void jarIsOnlyRepackagedOnce() throws Exception { + void jarIsOnlyRepackagedOnce() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -163,7 +162,7 @@ public class RepackagerTests { } @Test - public void multipleMainClassFound() throws Exception { + void multipleMainClassFound() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); @@ -173,7 +172,7 @@ public class RepackagerTests { } @Test - public void noMainClass() throws Exception { + void noMainClass() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); assertThatIllegalStateException() .isThrownBy(() -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES)) @@ -181,7 +180,7 @@ public class RepackagerTests { } @Test - public void noMainClassAndLayoutIsNone() throws Exception { + void noMainClassAndLayoutIsNone() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -193,7 +192,7 @@ public class RepackagerTests { } @Test - public void noMainClassAndLayoutIsNoneWithNoMain() throws Exception { + void noMainClassAndLayoutIsNoneWithNoMain() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -205,7 +204,7 @@ public class RepackagerTests { } @Test - public void sameSourceAndDestinationWithBackup() throws Exception { + void sameSourceAndDestinationWithBackup() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -215,7 +214,7 @@ public class RepackagerTests { } @Test - public void sameSourceAndDestinationWithoutBackup() throws Exception { + void sameSourceAndDestinationWithoutBackup() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -226,10 +225,10 @@ public class RepackagerTests { } @Test - public void differentDestination() throws Exception { + void differentDestination() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("different.jar"); + File dest = new File(this.tempDir, "different.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist(); @@ -238,7 +237,7 @@ public class RepackagerTests { } @Test - public void nullDestination() throws Exception { + void nullDestination() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) @@ -246,26 +245,25 @@ public class RepackagerTests { } @Test - public void destinationIsDirectory() throws Exception { + void destinationIsDirectory() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - assertThatIllegalArgumentException() - .isThrownBy(() -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES)) + assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.tempDir, NO_LIBRARIES)) .withMessageContaining("Invalid destination"); } @Test - public void overwriteDestination() throws Exception { + void overwriteDestination() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); dest.createNewFile(); repackager.repackage(dest, NO_LIBRARIES); assertThat(hasLauncherClasses(dest)).isTrue(); } @Test - public void nullLibraries() throws Exception { + void nullLibraries() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -274,12 +272,12 @@ public class RepackagerTests { } @Test - public void libraries() throws Exception { - TestJarFile libJar = new TestJarFile(this.temporaryFolder); + void libraries() throws Exception { + TestJarFile libJar = new TestJarFile(this.tempDir); libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class, JAN_1_1985); File libJarFile = libJar.getFile(); File libJarFileToUnpack = libJar.getFile(); - File libNonJarFile = this.temporaryFolder.newFile(); + File libNonJarFile = new File(this.tempDir, "non-lib.jar"); FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack); @@ -302,8 +300,8 @@ public class RepackagerTests { } @Test - public void duplicateLibraries() throws Exception { - TestJarFile libJar = new TestJarFile(this.temporaryFolder); + void duplicateLibraries() throws Exception { + TestJarFile libJar = new TestJarFile(this.tempDir); libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class); File libJarFile = libJar.getFile(); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); @@ -316,8 +314,8 @@ public class RepackagerTests { } @Test - public void customLayout() throws Exception { - TestJarFile libJar = new TestJarFile(this.temporaryFolder); + void customLayout() throws Exception { + TestJarFile libJar = new TestJarFile(this.tempDir); libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class); File libJarFile = libJar.getFile(); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); @@ -336,8 +334,8 @@ public class RepackagerTests { } @Test - public void customLayoutNoBootLib() throws Exception { - TestJarFile libJar = new TestJarFile(this.temporaryFolder); + void customLayoutNoBootLib() throws Exception { + TestJarFile libJar = new TestJarFile(this.tempDir); libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class); File libJarFile = libJar.getFile(); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); @@ -353,7 +351,7 @@ public class RepackagerTests { } @Test - public void springBootVersion() throws Exception { + void springBootVersion() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -363,7 +361,7 @@ public class RepackagerTests { } @Test - public void executableJarLayoutAttributes() throws Exception { + void executableJarLayoutAttributes() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); @@ -376,7 +374,7 @@ public class RepackagerTests { } @Test - public void executableWarLayoutAttributes() throws Exception { + void executableWarLayoutAttributes() throws Exception { this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile("war"); Repackager repackager = new Repackager(file); @@ -389,7 +387,7 @@ public class RepackagerTests { } @Test - public void nullCustomLayout() throws Exception { + void nullCustomLayout() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); assertThatIllegalArgumentException().isThrownBy(() -> repackager.setLayout(null)) @@ -397,8 +395,8 @@ public class RepackagerTests { } @Test - public void dontRecompressZips() throws Exception { - TestJarFile nested = new TestJarFile(this.temporaryFolder); + void dontRecompressZips() throws Exception { + TestJarFile nested = new TestJarFile(this.tempDir); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); File nestedFile = nested.getFile(); this.testJarFile.addFile("test/nested.jar", nestedFile); @@ -414,10 +412,10 @@ public class RepackagerTests { } @Test - public void addLauncherScript() throws Exception { + void addLauncherScript() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); LaunchScript script = new MockLauncherScript("ABC"); repackager.repackage(dest, NO_LIBRARIES, script); @@ -434,8 +432,8 @@ public class RepackagerTests { } @Test - public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception { - TestJarFile nested = new TestJarFile(this.temporaryFolder); + void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception { + TestJarFile nested = new TestJarFile(this.tempDir); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); File nestedFile = nested.getFile(); String name = "BOOT-INF/lib/" + nestedFile.getName(); @@ -450,8 +448,8 @@ public class RepackagerTests { } @Test - public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception { - TestJarFile nested = new TestJarFile(this.temporaryFolder); + void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception { + TestJarFile nested = new TestJarFile(this.tempDir); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); File nestedFile = nested.getFile(); this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile()); @@ -461,7 +459,8 @@ public class RepackagerTests { long sourceLength = nestedFile.length(); repackager.repackage((callback) -> { nestedFile.delete(); - File toZip = RepackagerTests.this.temporaryFolder.newFile(); + File toZip = new File(this.tempDir, "to-zip"); + toZip.createNewFile(); ZipUtil.packEntry(toZip, nestedFile); callback.library(new Library(nestedFile, LibraryScope.COMPILE)); }); @@ -471,11 +470,13 @@ public class RepackagerTests { } @Test - public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception { + void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST")); + File indexList = new File(this.tempDir, "INDEX.LIST"); + indexList.createNewFile(); + this.testJarFile.addFile("META-INF/INDEX.LIST", indexList); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (JarFile jarFile = new JarFile(dest)) { @@ -484,7 +485,7 @@ public class RepackagerTests { } @Test - public void customLayoutFactoryWithoutLayout() throws Exception { + void customLayoutFactoryWithoutLayout() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); Repackager repackager = new Repackager(source, new TestLayoutFactory()); @@ -495,7 +496,7 @@ public class RepackagerTests { } @Test - public void customLayoutFactoryWithLayout() throws Exception { + void customLayoutFactoryWithLayout() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); Repackager repackager = new Repackager(source, new TestLayoutFactory()); @@ -507,11 +508,13 @@ public class RepackagerTests { } @Test - public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception { + void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml")); + File aopXml = new File(this.tempDir, "aop.xml"); + aopXml.createNewFile(); + this.testJarFile.addFile("META-INF/aop.xml", aopXml); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (JarFile jarFile = new JarFile(dest)) { @@ -521,10 +524,10 @@ public class RepackagerTests { } @Test - public void allEntriesUseUnixPlatformAndUtf8NameEncoding() throws IOException { + void allEntriesUseUnixPlatformAndUtf8NameEncoding() throws IOException { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (ZipFile zip = new ZipFile(dest)) { @@ -538,10 +541,10 @@ public class RepackagerTests { } @Test - public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException { + void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException { this.testJarFile.addClass("com/example/Application.class", ClassWithMainMethod.class); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); File libraryOne = createLibrary(); File libraryTwo = createLibrary(); File libraryThree = createLibrary(); @@ -557,12 +560,12 @@ public class RepackagerTests { } @Test - public void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException { + void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException { File library = createLibrary(); this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", ClassWithMainMethod.class); this.testJarFile.addFile("WEB-INF/lib/" + library.getName(), library); File source = this.testJarFile.getFile("war"); - File dest = this.temporaryFolder.newFile("dest.war"); + File dest = new File(this.tempDir, "dest.war"); Repackager repackager = new Repackager(source); repackager.setLayout(new Layouts.War()); repackager.repackage(dest, (callback) -> callback.library(new Library(library, LibraryScope.COMPILE, true))); @@ -573,8 +576,8 @@ public class RepackagerTests { } @Test - public void layoutCanOmitLibraries() throws IOException { - TestJarFile libJar = new TestJarFile(this.temporaryFolder); + void layoutCanOmitLibraries() throws IOException { + TestJarFile libJar = new TestJarFile(this.tempDir); libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class); File libJarFile = libJar.getFile(); this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); @@ -589,8 +592,8 @@ public class RepackagerTests { } @Test - public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException { - File source = this.temporaryFolder.newFile("source.jar"); + void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException { + File source = new File(this.tempDir, "source.jar"); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) { { this.def = new Deflater(Deflater.NO_COMPRESSION, true); @@ -603,18 +606,18 @@ public class RepackagerTests { output.write(data); output.closeEntry(); output.close(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.setMainClass("com.example.Main"); repackager.repackage(dest, NO_LIBRARIES); } @Test - public void moduleInfoClassRemainsInRootOfJarWhenRepackaged() throws Exception { + void moduleInfoClassRemainsInRootOfJarWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); this.testJarFile.addClass("module-info.class", ClassWithoutMainMethod.class); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (JarFile jarFile = new JarFile(dest)) { @@ -624,11 +627,13 @@ public class RepackagerTests { } @Test - public void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() throws Exception { + void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() throws Exception { this.testJarFile.addClass("A.class", ClassWithMainMethod.class); - this.testJarFile.addFile("META-INF/test.kotlin_module", this.temporaryFolder.newFile("test.kotlin_module")); + File kotlinModule = new File(this.tempDir, "test.kotlin_module"); + kotlinModule.createNewFile(); + this.testJarFile.addFile("META-INF/test.kotlin_module", kotlinModule); File source = this.testJarFile.getFile(); - File dest = this.temporaryFolder.newFile("dest.jar"); + File dest = new File(this.tempDir, "dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); try (JarFile jarFile = new JarFile(dest)) { @@ -638,7 +643,7 @@ public class RepackagerTests { } private File createLibrary() throws IOException { - TestJarFile library = new TestJarFile(this.temporaryFolder); + TestJarFile library = new TestJarFile(this.tempDir); library.addClass("com/example/library/Library.class", ClassWithoutMainMethod.class); return library.getFile(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index fc85fb10280..8ac35d9d89c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -24,10 +24,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.jar.JarFile; import java.util.jar.Manifest; -import org.junit.rules.TemporaryFolder; import org.zeroturnaround.zip.FileSource; import org.zeroturnaround.zip.ZipEntrySource; import org.zeroturnaround.zip.ZipUtil; @@ -40,15 +40,15 @@ public class TestJarFile { private final byte[] buffer = new byte[4096]; - private final TemporaryFolder temporaryFolder; + private final File temporaryFolder; private final File jarSource; private final List entries = new ArrayList<>(); - public TestJarFile(TemporaryFolder temporaryFolder) throws IOException { + public TestJarFile(File temporaryFolder) throws IOException { this.temporaryFolder = temporaryFolder; - this.jarSource = temporaryFolder.newFolder(); + this.jarSource = new File(temporaryFolder, "jar-source"); } public void addClass(String filename, Class classToCopy) throws IOException { @@ -120,8 +120,7 @@ public class TestJarFile { } public File getFile(String extension) throws IOException { - File file = this.temporaryFolder.newFile(); - file = new File(file.getParent(), file.getName() + "." + extension); + File file = new File(this.temporaryFolder, UUID.randomUUID() + "." + extension); ZipUtil.pack(this.entries.toArray(new ZipEntrySource[0]), file); return file; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java index 42460ebd4f3..0962fe01b2c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ZipHeaderPeekInputStreamTests.java @@ -24,16 +24,16 @@ package org.springframework.boot.loader.tools; import java.io.ByteArrayInputStream; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.loader.tools.JarWriter.ZipHeaderPeekInputStream; import static org.assertj.core.api.Assertions.assertThat; -public class ZipHeaderPeekInputStreamTests { +class ZipHeaderPeekInputStreamTests { @Test - public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException { + void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 }))) { assertThat(in.hasZipHeader()).isTrue(); @@ -41,7 +41,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() throws IOException { + void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { assertThat(in.hasZipHeader()).isFalse(); @@ -49,7 +49,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readIndividualBytes() throws IOException { + void readIndividualBytes() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { assertThat(in.read()).isEqualTo(0); @@ -62,7 +62,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMultipleBytes() throws IOException { + void readMultipleBytes() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { byte[] bytes = new byte[3]; @@ -75,7 +75,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException { + void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { byte[] bytes = new byte[8]; @@ -86,7 +86,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException { + void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) { byte[] bytes = new byte[8]; @@ -98,7 +98,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException { + void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 10 }))) { byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(1); @@ -107,7 +107,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException { + void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream( new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }))) { byte[] bytes = new byte[8]; @@ -117,7 +117,7 @@ public class ZipHeaderPeekInputStreamTests { } @Test - public void readMoreThanEntireStreamWhenStreamLengthIsZero() throws IOException { + void readMoreThanEntireStreamWhenStreamLengthIsZero() throws IOException { try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[0]))) { byte[] bytes = new byte[8]; assertThat(in.read(bytes)).isEqualTo(-1); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java index 857eedc0b6b..49449cf2438 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/AbstractExecutableArchiveLauncherTests.java @@ -32,8 +32,7 @@ import java.util.jar.JarOutputStream; import java.util.zip.CRC32; import java.util.zip.ZipEntry; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.archive.Archive; import org.springframework.util.FileCopyUtils; @@ -45,11 +44,11 @@ import org.springframework.util.FileCopyUtils; */ public abstract class AbstractExecutableArchiveLauncherTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; protected File createJarArchive(String name, String entryPrefix) throws IOException { - File archive = this.temp.newFile(name); + File archive = new File(this.tempDir, name); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive)); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/")); jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/classes/")); @@ -69,7 +68,8 @@ public abstract class AbstractExecutableArchiveLauncherTests { } protected File explode(File archive) throws IOException { - File exploded = this.temp.newFolder("exploded"); + File exploded = new File(this.tempDir, "exploded"); + exploded.mkdirs(); JarFile jarFile = new JarFile(archive); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java index 90fc5ca8ff8..554ea8f1e76 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/JarLauncherTests.java @@ -20,7 +20,7 @@ import java.io.File; import java.net.URL; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.loader.archive.Archive; import org.springframework.boot.loader.archive.ExplodedArchive; @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests { +class JarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { + void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.jar", "BOOT-INF")); JarLauncher launcher = new JarLauncher(new ExplodedArchive(explodedRoot, true)); List archives = launcher.getClassPathArchives(); @@ -46,7 +46,7 @@ public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests { } @Test - public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { + void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.jar", "BOOT-INF"); JarLauncher launcher = new JarLauncher(new JarFileArchive(jarRoot)); List archives = launcher.getClassPathArchives(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java index 90403793fa9..c6cc64c313a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java @@ -19,9 +19,8 @@ package org.springframework.boot.loader; import java.io.File; import java.net.URL; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.jar.JarFile; @@ -35,42 +34,42 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson */ @SuppressWarnings("resource") -public class LaunchedURLClassLoaderTests { +class LaunchedURLClassLoaderTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void resolveResourceFromArchive() throws Exception { + void resolveResourceFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("demo/Application.java")).isNotNull(); } @Test - public void resolveResourcesFromArchive() throws Exception { + void resolveResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResources("demo/Application.java").hasMoreElements()).isTrue(); } @Test - public void resolveRootPathFromArchive() throws Exception { + void resolveRootPathFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResource("")).isNotNull(); } @Test - public void resolveRootResourcesFromArchive() throws Exception { + void resolveRootResourcesFromArchive() throws Exception { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); assertThat(loader.getResources("").hasMoreElements()).isTrue(); } @Test - public void resolveFromNested() throws Exception { - File file = this.temporaryFolder.newFile(); + void resolveFromNested() throws Exception { + File file = new File(this.tempDir, "test.jar"); TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); @@ -81,8 +80,8 @@ public class LaunchedURLClassLoaderTests { } @Test - public void resolveFromNestedWhileThreadIsInterrupted() throws Exception { - File file = this.temporaryFolder.newFile(); + void resolveFromNestedWhileThreadIsInterrupted() throws Exception { + File file = new File(this.tempDir, "test.jar"); TestJarCreator.createTestJar(file); JarFile jarFile = new JarFile(file); URL url = jarFile.getUrl(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index 6dc3374c102..5aceb9f9714 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -28,16 +28,17 @@ import java.util.jar.Attributes; import java.util.jar.Manifest; import org.assertj.core.api.Condition; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.archive.Archive; import org.springframework.boot.loader.archive.ExplodedArchive; import org.springframework.boot.loader.archive.JarFileArchive; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.core.io.FileSystemResource; import org.springframework.test.util.ReflectionTestUtils; @@ -50,23 +51,24 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Dave Syer * @author Andy Wilkinson */ -public class PropertiesLauncherTests { +@ExtendWith(OutputCaptureExtension.class) +class PropertiesLauncherTests { - @Rule - public OutputCapture output = new OutputCapture(); - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private ClassLoader contextClassLoader; - @Before - public void setup() { + private CapturedOutput capturedOutput; + + @BeforeEach + public void setup(CapturedOutput capturedOutput) { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath()); + this.capturedOutput = capturedOutput; } - @After + @AfterEach public void close() { Thread.currentThread().setContextClassLoader(this.contextClassLoader); System.clearProperty("loader.home"); @@ -79,14 +81,14 @@ public class PropertiesLauncherTests { } @Test - public void testDefaultHome() { + void testDefaultHome() { System.clearProperty("loader.home"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("user.dir"))); } @Test - public void testAlternateHome() throws Exception { + void testAlternateHome() throws Exception { System.setProperty("loader.home", "src/test/resources/home"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("loader.home"))); @@ -94,21 +96,21 @@ public class PropertiesLauncherTests { } @Test - public void testNonExistentHome() { + void testNonExistentHome() { System.setProperty("loader.home", "src/test/resources/nonexistent"); assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new) .withMessageContaining("Invalid source folder").withCauseInstanceOf(IllegalArgumentException.class); } @Test - public void testUserSpecifiedMain() throws Exception { + void testUserSpecifiedMain() throws Exception { PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("demo.Application"); assertThat(System.getProperty("loader.main")).isNull(); } @Test - public void testUserSpecifiedConfigName() throws Exception { + void testUserSpecifiedConfigName() throws Exception { System.setProperty("loader.config.name", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("my.Application"); @@ -116,21 +118,21 @@ public class PropertiesLauncherTests { } @Test - public void testRootOfClasspathFirst() throws Exception { + void testRootOfClasspathFirst() throws Exception { System.setProperty("loader.config.name", "bar"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("my.BarApplication"); } @Test - public void testUserSpecifiedDotPath() { + void testUserSpecifiedDotPath() { System.setProperty("loader.path", "."); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[.]"); } @Test - public void testUserSpecifiedSlashPath() throws Exception { + void testUserSpecifiedSlashPath() throws Exception { System.setProperty("loader.path", "jars/"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]"); @@ -139,7 +141,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedWildcardPath() throws Exception { + void testUserSpecifiedWildcardPath() throws Exception { System.setProperty("loader.path", "jars/*"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -149,7 +151,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedJarPath() throws Exception { + void testUserSpecifiedJarPath() throws Exception { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -159,7 +161,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedRootOfJarPath() throws Exception { + void testUserSpecifiedRootOfJarPath() throws Exception { System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) @@ -170,7 +172,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedRootOfJarPathWithDot() throws Exception { + void testUserSpecifiedRootOfJarPathWithDot() throws Exception { System.setProperty("loader.path", "nested-jars/app.jar!/./"); PropertiesLauncher launcher = new PropertiesLauncher(); List archives = launcher.getClassPathArchives(); @@ -179,7 +181,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception { + void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception { System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/./"); PropertiesLauncher launcher = new PropertiesLauncher(); List archives = launcher.getClassPathArchives(); @@ -187,7 +189,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedJarFileWithNestedArchives() throws Exception { + void testUserSpecifiedJarFileWithNestedArchives() throws Exception { System.setProperty("loader.path", "nested-jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -197,7 +199,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedNestedJarPath() throws Exception { + void testUserSpecifiedNestedJarPath() throws Exception { System.setProperty("loader.path", "nested-jars/app.jar!/foo.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -206,7 +208,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception { + void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception { System.setProperty("loader.path", "nested-jars"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -215,7 +217,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedJarPathWithDot() throws Exception { + void testUserSpecifiedJarPathWithDot() throws Exception { System.setProperty("loader.path", "./jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -225,7 +227,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedClassLoader() throws Exception { + void testUserSpecifiedClassLoader() throws Exception { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -235,7 +237,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedClassPathOrder() throws Exception { + void testUserSpecifiedClassPathOrder() throws Exception { System.setProperty("loader.path", "more-jars/app.jar,jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -246,7 +248,7 @@ public class PropertiesLauncherTests { } @Test - public void testCustomClassLoaderCreation() throws Exception { + void testCustomClassLoaderCreation() throws Exception { System.setProperty("loader.classLoader", TestLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); ClassLoader loader = launcher.createClassLoader(archives()); @@ -272,7 +274,7 @@ public class PropertiesLauncherTests { } @Test - public void testUserSpecifiedConfigPathWins() throws Exception { + void testUserSpecifiedConfigPathWins() throws Exception { System.setProperty("loader.config.name", "foo"); System.setProperty("loader.config.location", "classpath:bar.properties"); @@ -281,21 +283,21 @@ public class PropertiesLauncherTests { } @Test - public void testSystemPropertySpecifiedMain() throws Exception { + void testSystemPropertySpecifiedMain() throws Exception { System.setProperty("loader.main", "foo.Bar"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("foo.Bar"); } @Test - public void testSystemPropertiesSet() { + void testSystemPropertiesSet() { System.setProperty("loader.system", "true"); new PropertiesLauncher(); assertThat(System.getProperty("loader.main")).isEqualTo("demo.Application"); } @Test - public void testArgsEnhanced() throws Exception { + void testArgsEnhanced() throws Exception { System.setProperty("loader.args", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(Arrays.asList(launcher.getArgs("bar")).toString()).isEqualTo("[foo, bar]"); @@ -303,12 +305,12 @@ public class PropertiesLauncherTests { @SuppressWarnings("unchecked") @Test - public void testLoadPathCustomizedUsingManifest() throws Exception { - System.setProperty("loader.home", this.temporaryFolder.getRoot().getAbsolutePath()); + void testLoadPathCustomizedUsingManifest() throws Exception { + System.setProperty("loader.home", this.tempDir.getAbsolutePath()); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar"); - File manifestFile = new File(this.temporaryFolder.getRoot(), "META-INF/MANIFEST.MF"); + File manifestFile = new File(this.tempDir, "META-INF/MANIFEST.MF"); manifestFile.getParentFile().mkdirs(); manifest.write(new FileOutputStream(manifestFile)); PropertiesLauncher launcher = new PropertiesLauncher(); @@ -316,15 +318,16 @@ public class PropertiesLauncherTests { } @Test - public void testManifestWithPlaceholders() throws Exception { + void testManifestWithPlaceholders() throws Exception { System.setProperty("loader.home", "src/test/resources/placeholders"); PropertiesLauncher launcher = new PropertiesLauncher(); assertThat(launcher.getMainClass()).isEqualTo("demo.FooApplication"); } @Test - public void encodedFileUrlLoaderPathIsHandledCorrectly() throws Exception { - File loaderPath = this.temporaryFolder.newFolder("loader path"); + void encodedFileUrlLoaderPathIsHandledCorrectly() throws Exception { + File loaderPath = new File(this.tempDir, "loader path"); + loaderPath.mkdir(); System.setProperty("loader.path", loaderPath.toURI().toURL().toString()); PropertiesLauncher launcher = new PropertiesLauncher(); List archives = launcher.getClassPathArchives(); @@ -339,7 +342,7 @@ public class PropertiesLauncherTests { while (!timeout && count < 100) { count++; Thread.sleep(50L); - timeout = this.output.toString().contains(value); + timeout = this.capturedOutput.toString().contains(value); } assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java index c6c02f1d678..c1b5259815c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java @@ -20,7 +20,7 @@ import java.io.File; import java.net.URL; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.loader.archive.Archive; import org.springframework.boot.loader.archive.ExplodedArchive; @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests { +class WarLauncherTests extends AbstractExecutableArchiveLauncherTests { @Test - public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception { + void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception { File explodedRoot = explode(createJarArchive("archive.war", "WEB-INF")); WarLauncher launcher = new WarLauncher(new ExplodedArchive(explodedRoot, true)); List archives = launcher.getClassPathArchives(); @@ -46,7 +46,7 @@ public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests { } @Test - public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception { + void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception { File jarRoot = createJarArchive("archive.war", "WEB-INF"); WarLauncher launcher = new WarLauncher(new JarFileArchive(jarRoot)); List archives = launcher.getClassPathArchives(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java index ab5a6a5469c..fd7cda2d1f6 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java @@ -26,13 +26,13 @@ import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; +import java.util.UUID; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.archive.Archive.Entry; @@ -47,16 +47,16 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class ExplodedArchiveTests { +class ExplodedArchiveTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private File rootFolder; private ExplodedArchive archive; - @Before + @BeforeEach public void setup() throws Exception { createArchive(); } @@ -66,11 +66,11 @@ public class ExplodedArchiveTests { } private void createArchive(String folderName) throws Exception { - File file = this.temporaryFolder.newFile(); + File file = new File(this.tempDir, "test.jar"); TestJarCreator.createTestJar(file); - this.rootFolder = (StringUtils.hasText(folderName) ? this.temporaryFolder.newFolder(folderName) - : this.temporaryFolder.newFolder()); + this.rootFolder = (StringUtils.hasText(folderName) ? new File(this.tempDir, folderName) + : new File(this.tempDir, UUID.randomUUID().toString())); JarFile jarFile = new JarFile(file); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { @@ -98,36 +98,36 @@ public class ExplodedArchiveTests { } @Test - public void getManifest() throws Exception { + void getManifest() throws Exception { assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test - public void getEntries() { + void getEntries() { Map entries = getEntriesMap(this.archive); assertThat(entries.size()).isEqualTo(12); } @Test - public void getUrl() throws Exception { + void getUrl() throws Exception { assertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL()); } @Test - public void getUrlWithSpaceInPath() throws Exception { + void getUrlWithSpaceInPath() throws Exception { createArchive("spaces in the name"); assertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL()); } @Test - public void getNestedArchive() throws Exception { + void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); assertThat(nested.getUrl().toString()).isEqualTo(this.rootFolder.toURI() + "nested.jar"); } @Test - public void nestedDirArchive() throws Exception { + void nestedDirArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("d/"); Archive nested = this.archive.getNestedArchive(entry); Map nestedEntries = getEntriesMap(nested); @@ -136,14 +136,14 @@ public class ExplodedArchiveTests { } @Test - public void getNonRecursiveEntriesForRoot() { + void getNonRecursiveEntriesForRoot() { ExplodedArchive archive = new ExplodedArchive(new File("/"), false); Map entries = getEntriesMap(archive); assertThat(entries.size()).isGreaterThan(1); } @Test - public void getNonRecursiveManifest() throws Exception { + void getNonRecursiveManifest() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); @@ -151,7 +151,7 @@ public class ExplodedArchiveTests { } @Test - public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { + void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); @@ -159,7 +159,7 @@ public class ExplodedArchiveTests { } @Test - public void getResourceAsStream() throws Exception { + void getResourceAsStream() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root")); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); @@ -168,7 +168,7 @@ public class ExplodedArchiveTests { } @Test - public void getResourceAsStreamNonRecursive() throws Exception { + void getResourceAsStreamNonRecursive() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index b7a3f83991c..366bcac886a 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -28,10 +28,9 @@ import java.util.jar.JarOutputStream; import java.util.zip.CRC32; import java.util.zip.ZipEntry; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.archive.Archive.Entry; @@ -46,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Phillip Webb * @author Andy Wilkinson */ -public class JarFileArchiveTests { +class JarFileArchiveTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private File rootJarFile; @@ -57,44 +56,44 @@ public class JarFileArchiveTests { private String rootJarFileUrl; - @Before + @BeforeEach public void setup() throws Exception { setup(false); } private void setup(boolean unpackNested) throws Exception { - this.rootJarFile = this.temporaryFolder.newFile(); + this.rootJarFile = new File(this.tempDir, "root.jar"); this.rootJarFileUrl = this.rootJarFile.toURI().toString(); TestJarCreator.createTestJar(this.rootJarFile, unpackNested); this.archive = new JarFileArchive(this.rootJarFile); } @Test - public void getManifest() throws Exception { + void getManifest() throws Exception { assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test - public void getEntries() { + void getEntries() { Map entries = getEntriesMap(this.archive); assertThat(entries.size()).isEqualTo(12); } @Test - public void getUrl() throws Exception { + void getUrl() throws Exception { URL url = this.archive.getUrl(); assertThat(url.toString()).isEqualTo(this.rootJarFileUrl); } @Test - public void getNestedArchive() throws Exception { + void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); assertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); } @Test - public void getNestedUnpackedArchive() throws Exception { + void getNestedUnpackedArchive() throws Exception { setup(true); Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); @@ -103,7 +102,7 @@ public class JarFileArchiveTests { } @Test - public void unpackedLocationsAreUniquePerArchive() throws Exception { + void unpackedLocationsAreUniquePerArchive() throws Exception { setup(true); Entry entry = getEntriesMap(this.archive).get("nested.jar"); URL firstNested = this.archive.getNestedArchive(entry).getUrl(); @@ -114,7 +113,7 @@ public class JarFileArchiveTests { } @Test - public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception { + void unpackedLocationsFromSameArchiveShareSameParent() throws Exception { setup(true); File nested = new File( this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl().toURI()); @@ -124,16 +123,16 @@ public class JarFileArchiveTests { } @Test - public void zip64ArchivesAreHandledGracefully() throws IOException { - File file = this.temporaryFolder.newFile("test.jar"); + void zip64ArchivesAreHandledGracefully() throws IOException { + File file = new File(this.tempDir, "test.jar"); FileCopyUtils.copy(writeZip64Jar(), file); assertThatIllegalStateException().isThrownBy(() -> new JarFileArchive(file)) .withMessageContaining("Zip64 archives are not supported"); } @Test - public void nestedZip64ArchivesAreHandledGracefully() throws IOException { - File file = this.temporaryFolder.newFile("test.jar"); + void nestedZip64ArchivesAreHandledGracefully() throws IOException { + File file = new File(this.tempDir, "test.jar"); JarOutputStream output = new JarOutputStream(new FileOutputStream(file)); JarEntry zip64JarEntry = new JarEntry("nested/zip64.jar"); output.putNextEntry(zip64JarEntry); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 2e964069276..2e29b7d32bc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -27,11 +27,10 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -44,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThatNullPointerException; * @author Phillip Webb * @author Andy Wilkinson */ -public class RandomAccessDataFileTests { +class RandomAccessDataFileTests { private static final byte[] BYTES; @@ -55,18 +54,15 @@ public class RandomAccessDataFileTests { } } - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private File tempFile; private RandomAccessDataFile file; private InputStream inputStream; - @Before - public void setup() throws Exception { - this.tempFile = this.temporaryFolder.newFile(); + @BeforeEach + public void setup(@TempDir File tempDir) throws Exception { + this.tempFile = new File(tempDir, "tempFile"); FileOutputStream outputStream = new FileOutputStream(this.tempFile); outputStream.write(BYTES); outputStream.close(); @@ -74,74 +70,74 @@ public class RandomAccessDataFileTests { this.inputStream = this.file.getInputStream(); } - @After + @AfterEach public void cleanup() throws Exception { this.inputStream.close(); this.file.close(); } @Test - public void fileNotNull() { + void fileNotNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null)) .withMessageContaining("File must not be null"); } @Test - public void fileExists() { + void fileExists() { File file = new File("/does/not/exist"); assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file)) .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); } @Test - public void readWithOffsetAndLengthShouldRead() throws Exception { + void readWithOffsetAndLengthShouldRead() throws Exception { byte[] read = this.file.read(2, 3); assertThat(read).isEqualTo(new byte[] { 2, 3, 4 }); } @Test - public void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception { + void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception { assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.read(257, 0)); } @Test - public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception { + void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 10); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> subsection.read(11, 0)); } @Test - public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception { + void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception { assertThatExceptionOfType(EOFException.class).isThrownBy(() -> this.file.read(256, 1)); } @Test - public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception { + void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 10); assertThatExceptionOfType(EOFException.class).isThrownBy(() -> subsection.read(10, 1)); } @Test - public void inputStreamRead() throws Exception { + void inputStreamRead() throws Exception { for (int i = 0; i <= 255; i++) { assertThat(this.inputStream.read()).isEqualTo(i); } } @Test - public void inputStreamReadNullBytes() throws Exception { + void inputStreamReadNullBytes() throws Exception { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null)) .withMessage("Bytes must not be null"); } @Test - public void inputStreamReadNullBytesWithOffset() throws Exception { + void inputStreamReadNullBytesWithOffset() throws Exception { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1)) .withMessage("Bytes must not be null"); } @Test - public void inputStreamReadBytes() throws Exception { + void inputStreamReadBytes() throws Exception { byte[] b = new byte[256]; int amountRead = this.inputStream.read(b); assertThat(b).isEqualTo(BYTES); @@ -149,7 +145,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamReadOffsetBytes() throws Exception { + void inputStreamReadOffsetBytes() throws Exception { byte[] b = new byte[7]; this.inputStream.skip(1); int amountRead = this.inputStream.read(b, 2, 3); @@ -158,7 +154,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamReadMoreBytesThanAvailable() throws Exception { + void inputStreamReadMoreBytesThanAvailable() throws Exception { byte[] b = new byte[257]; int amountRead = this.inputStream.read(b); assertThat(b).startsWith(BYTES); @@ -166,7 +162,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamReadPastEnd() throws Exception { + void inputStreamReadPastEnd() throws Exception { this.inputStream.skip(255); assertThat(this.inputStream.read()).isEqualTo(0xFF); assertThat(this.inputStream.read()).isEqualTo(-1); @@ -174,7 +170,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamReadZeroLength() throws Exception { + void inputStreamReadZeroLength() throws Exception { byte[] b = new byte[] { 0x0F }; int amountRead = this.inputStream.read(b, 0, 0); assertThat(b).isEqualTo(new byte[] { 0x0F }); @@ -183,62 +179,62 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamSkip() throws Exception { + void inputStreamSkip() throws Exception { long amountSkipped = this.inputStream.skip(4); assertThat(this.inputStream.read()).isEqualTo(4); assertThat(amountSkipped).isEqualTo(4L); } @Test - public void inputStreamSkipMoreThanAvailable() throws Exception { + void inputStreamSkipMoreThanAvailable() throws Exception { long amountSkipped = this.inputStream.skip(257); assertThat(this.inputStream.read()).isEqualTo(-1); assertThat(amountSkipped).isEqualTo(256L); } @Test - public void inputStreamSkipPastEnd() throws Exception { + void inputStreamSkipPastEnd() throws Exception { this.inputStream.skip(256); long amountSkipped = this.inputStream.skip(1); assertThat(amountSkipped).isEqualTo(0L); } @Test - public void subsectionNegativeOffset() { + void subsectionNegativeOffset() { assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(-1, 1)); } @Test - public void subsectionNegativeLength() { + void subsectionNegativeLength() { assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, -1)); } @Test - public void subsectionZeroLength() throws Exception { + void subsectionZeroLength() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 0); assertThat(subsection.getInputStream().read()).isEqualTo(-1); } @Test - public void subsectionTooBig() { + void subsectionTooBig() { this.file.getSubsection(0, 256); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, 257)); } @Test - public void subsectionTooBigWithOffset() { + void subsectionTooBigWithOffset() { this.file.getSubsection(1, 255); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(1, 256)); } @Test - public void subsection() throws Exception { + void subsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 1); assertThat(subsection.getInputStream().read()).isEqualTo(1); } @Test - public void inputStreamReadPastSubsection() throws Exception { + void inputStreamReadPastSubsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 2); InputStream inputStream = subsection.getInputStream(); assertThat(inputStream.read()).isEqualTo(1); @@ -247,7 +243,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamReadBytesPastSubsection() throws Exception { + void inputStreamReadBytesPastSubsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 2); InputStream inputStream = subsection.getInputStream(); byte[] b = new byte[3]; @@ -257,7 +253,7 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamSkipPastSubsection() throws Exception { + void inputStreamSkipPastSubsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 2); InputStream inputStream = subsection.getInputStream(); assertThat(inputStream.skip(3)).isEqualTo(2L); @@ -265,17 +261,17 @@ public class RandomAccessDataFileTests { } @Test - public void inputStreamSkipNegative() throws Exception { + void inputStreamSkipNegative() throws Exception { assertThat(this.inputStream.skip(-1)).isEqualTo(0L); } @Test - public void getFile() { + void getFile() { assertThat(this.file.getFile()).isEqualTo(this.tempFile); } @Test - public void concurrentReads() throws Exception { + void concurrentReads() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(20); List> results = new ArrayList<>(); for (int i = 0; i < 100; i++) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java index 94be92bed87..991581700e1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.loader.jar; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -27,30 +27,30 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Andy Wilkinson */ -public class AsciiBytesTests { +class AsciiBytesTests { private static final char NO_SUFFIX = 0; @Test - public void createFromBytes() { + void createFromBytes() { AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 }); assertThat(bytes.toString()).isEqualTo("AB"); } @Test - public void createFromBytesWithOffset() { + void createFromBytesWithOffset() { AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); assertThat(bytes.toString()).isEqualTo("BC"); } @Test - public void createFromString() { + void createFromString() { AsciiBytes bytes = new AsciiBytes("AB"); assertThat(bytes.toString()).isEqualTo("AB"); } @Test - public void length() { + void length() { AsciiBytes b1 = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes b2 = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); assertThat(b1.length()).isEqualTo(2); @@ -58,7 +58,7 @@ public class AsciiBytesTests { } @Test - public void startWith() { + void startWith() { AsciiBytes abc = new AsciiBytes(new byte[] { 65, 66, 67 }); AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); @@ -70,7 +70,7 @@ public class AsciiBytesTests { } @Test - public void endsWith() { + void endsWith() { AsciiBytes abc = new AsciiBytes(new byte[] { 65, 66, 67 }); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); @@ -82,7 +82,7 @@ public class AsciiBytesTests { } @Test - public void substringFromBeingIndex() { + void substringFromBeingIndex() { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); assertThat(abcd.substring(0).toString()).isEqualTo("ABCD"); assertThat(abcd.substring(1).toString()).isEqualTo("BCD"); @@ -93,7 +93,7 @@ public class AsciiBytesTests { } @Test - public void substring() { + void substring() { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); assertThat(abcd.substring(0, 4).toString()).isEqualTo("ABCD"); assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC"); @@ -103,7 +103,7 @@ public class AsciiBytesTests { } @Test - public void hashCodeAndEquals() { + void hashCodeAndEquals() { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes bc = new AsciiBytes(new byte[] { 66, 67 }); AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }).substring(1, 3); @@ -119,22 +119,22 @@ public class AsciiBytesTests { } @Test - public void hashCodeSameAsString() { + void hashCodeSameAsString() { hashCodeSameAsString("abcABC123xyz!"); } @Test - public void hashCodeSameAsStringWithSpecial() { + void hashCodeSameAsStringWithSpecial() { hashCodeSameAsString("special/\u00EB.dat"); } @Test - public void hashCodeSameAsStringWithCyrillicCharacters() { + void hashCodeSameAsStringWithCyrillicCharacters() { hashCodeSameAsString("\u0432\u0435\u0441\u043D\u0430"); } @Test - public void hashCodeSameAsStringWithEmoji() { + void hashCodeSameAsStringWithEmoji() { hashCodeSameAsString("\ud83d\udca9"); } @@ -143,22 +143,22 @@ public class AsciiBytesTests { } @Test - public void matchesSameAsString() { + void matchesSameAsString() { matchesSameAsString("abcABC123xyz!"); } @Test - public void matchesSameAsStringWithSpecial() { + void matchesSameAsStringWithSpecial() { matchesSameAsString("special/\u00EB.dat"); } @Test - public void matchesSameAsStringWithCyrillicCharacters() { + void matchesSameAsStringWithCyrillicCharacters() { matchesSameAsString("\u0432\u0435\u0441\u043D\u0430"); } @Test - public void matchesDifferentLengths() { + void matchesDifferentLengths() { assertThat(new AsciiBytes("abc").matches("ab", NO_SUFFIX)).isFalse(); assertThat(new AsciiBytes("abc").matches("abcd", NO_SUFFIX)).isFalse(); assertThat(new AsciiBytes("abc").matches("abc", NO_SUFFIX)).isTrue(); @@ -168,23 +168,23 @@ public class AsciiBytesTests { } @Test - public void matchesSuffix() { + void matchesSuffix() { assertThat(new AsciiBytes("ab").matches("a", 'b')).isTrue(); } @Test - public void matchesSameAsStringWithEmoji() { + void matchesSameAsStringWithEmoji() { matchesSameAsString("\ud83d\udca9"); } @Test - public void hashCodeFromInstanceMatchesHashCodeFromString() { + void hashCodeFromInstanceMatchesHashCodeFromString() { String name = "fonts/宋体/simsun.ttf"; assertThat(new AsciiBytes(name).hashCode()).isEqualTo(AsciiBytes.hashCode(name)); } @Test - public void instanceCreatedFromCharSequenceMatchesSameCharSequence() { + void instanceCreatedFromCharSequenceMatchesSameCharSequence() { String name = "fonts/宋体/simsun.ttf"; assertThat(new AsciiBytes(name).matches(name, NO_SUFFIX)).isTrue(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java index 0e9d1a5308d..f9b7f4cd9bc 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java @@ -21,10 +21,9 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.data.RandomAccessData; @@ -37,24 +36,21 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class CentralDirectoryParserTests { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); +class CentralDirectoryParserTests { private File jarFile; private RandomAccessData jarData; - @Before - public void setup() throws Exception { - this.jarFile = this.temporaryFolder.newFile(); + @BeforeEach + public void setup(@TempDir File tempDir) throws Exception { + this.jarFile = new File(tempDir, "test.jar"); TestJarCreator.createTestJar(this.jarFile); this.jarData = new RandomAccessDataFile(this.jarFile); } @Test - public void visitsInOrder() throws Exception { + void visitsInOrder() throws Exception { MockCentralDirectoryVisitor visitor = new MockCentralDirectoryVisitor(); CentralDirectoryParser parser = new CentralDirectoryParser(); parser.addVisitor(visitor); @@ -64,7 +60,7 @@ public class CentralDirectoryParserTests { } @Test - public void visitRecords() throws Exception { + void visitRecords() throws Exception { Collector collector = new Collector(); CentralDirectoryParser parser = new CentralDirectoryParser(); parser.addVisitor(collector); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java index c2239778d8d..9b1e3fc0d7b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java @@ -21,9 +21,8 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; @@ -34,15 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class HandlerTests { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); +class HandlerTests { private final Handler handler = new Handler(); @Test - public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { + void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -50,7 +46,7 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { + void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException { String spec = "/entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -58,7 +54,7 @@ public class HandlerTests { } @Test - public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException { + void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -66,7 +62,7 @@ public class HandlerTests { } @Test - public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { + void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -74,7 +70,7 @@ public class HandlerTests { } @Test - public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { + void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException { String spec = "entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); this.handler.parseURL(context, spec, 0, spec.length()); @@ -82,7 +78,7 @@ public class HandlerTests { } @Test - public void parseUrlWithSpecThatIgnoresContext() throws MalformedURLException { + void parseUrlWithSpecThatIgnoresContext() throws MalformedURLException { JarFile.registerUrlProtocolHandler(); String spec = "jar:file:/other.jar!/nested!/entry.txt"; URL context = createUrl("file:example.jar!/dir/file"); @@ -91,73 +87,72 @@ public class HandlerTests { } @Test - public void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException { + void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), new URL("file:/foo.jar"))).isFalse(); } @Test - public void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { + void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), new URL("jar:file:/foo.jar!/content.txt"))).isFalse(); } @Test - public void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { + void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/second.jar!/content.txt"))).isFalse(); } @Test - public void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { + void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue(); } @Test - public void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() + void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue(); } @Test - public void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() - throws MalformedURLException { + void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); } @Test - public void urlWithSpecReferencingParentDirectory() throws MalformedURLException { + void urlWithSpecReferencingParentDirectory() throws MalformedURLException { assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../folderB/b.xsd"); } @Test - public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException { + void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException { assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "../../../../../../folderB/b.xsd"); } @Test - public void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException { + void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException { assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd", "./folderB/./b.xsd"); } @Test - public void urlWithRef() throws MalformedURLException { + void urlWithRef() throws MalformedURLException { assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt#alpha"); } @Test - public void urlWithQuery() throws MalformedURLException { + void urlWithQuery() throws MalformedURLException { assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt?alpha"); } @Test - public void fallbackToJdksJarUrlStreamHandler() throws Exception { - File testJar = this.temporaryFolder.newFile("test.jar"); + void fallbackToJdksJarUrlStreamHandler(@TempDir File tempDir) throws Exception { + File testJar = new File(tempDir, "test.jar"); TestJarCreator.createTestJar(testJar); URLConnection connection = new URL(null, "jar:file:" + testJar.getAbsolutePath() + "!/nested.jar!/", this.handler).openConnection(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index 1b0c4194f9d..d0dec5c1f34 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -32,10 +32,9 @@ import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.data.RandomAccessDataFile; @@ -55,28 +54,28 @@ import static org.mockito.Mockito.verify; * @author Martin Lau * @author Andy Wilkinson */ -public class JarFileTests { +class JarFileTests { private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private File rootJarFile; private JarFile jarFile; - @Before + @BeforeEach public void setup() throws Exception { - this.rootJarFile = this.temporaryFolder.newFile(); + this.rootJarFile = new File(this.tempDir, "root.jar"); TestJarCreator.createTestJar(this.rootJarFile); this.jarFile = new JarFile(this.rootJarFile); } @Test - public void jdkJarFile() throws Exception { + void jdkJarFile() throws Exception { // Sanity checks to see how the default jar file operates java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile); Enumeration entries = jarFile.entries(); @@ -102,26 +101,26 @@ public class JarFileTests { } @Test - public void createFromFile() throws Exception { + void createFromFile() throws Exception { JarFile jarFile = new JarFile(this.rootJarFile); assertThat(jarFile.getName()).isNotNull(); jarFile.close(); } @Test - public void getManifest() throws Exception { + void getManifest() throws Exception { assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test - public void getManifestEntry() throws Exception { + void getManifestEntry() throws Exception { ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(this.jarFile.getInputStream(entry)); assertThat(manifest.getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test - public void getEntries() { + void getEntries() { Enumeration entries = this.jarFile.entries(); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF"); @@ -139,21 +138,21 @@ public class JarFileTests { } @Test - public void getSpecialResourceViaClassLoader() throws Exception { + void getSpecialResourceViaClassLoader() throws Exception { URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { this.jarFile.getUrl() }); assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull(); urlClassLoader.close(); } @Test - public void getJarEntry() { + void getJarEntry() { java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat"); assertThat(entry).isNotNull(); assertThat(entry.getName()).isEqualTo("1.dat"); } @Test - public void getInputStream() throws Exception { + void getInputStream() throws Exception { InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat")); assertThat(inputStream.available()).isEqualTo(1); assertThat(inputStream.read()).isEqualTo(1); @@ -162,19 +161,19 @@ public class JarFileTests { } @Test - public void getName() { + void getName() { assertThat(this.jarFile.getName()).isEqualTo(this.rootJarFile.getPath()); } @Test - public void getSize() throws Exception { + void getSize() throws Exception { try (ZipFile zip = new ZipFile(this.rootJarFile)) { assertThat(this.jarFile.size()).isEqualTo(zip.size()); } } @Test - public void getEntryTime() throws Exception { + void getEntryTime() throws Exception { java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile); assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime()) .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); @@ -182,7 +181,7 @@ public class JarFileTests { } @Test - public void close() throws Exception { + void close() throws Exception { RandomAccessDataFile randomAccessDataFile = spy(new RandomAccessDataFile(this.rootJarFile)); JarFile jarFile = new JarFile(randomAccessDataFile); jarFile.close(); @@ -190,7 +189,7 @@ public class JarFileTests { } @Test - public void getUrl() throws Exception { + void getUrl() throws Exception { URL url = this.jarFile.getUrl(); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); @@ -203,7 +202,7 @@ public class JarFileTests { } @Test - public void createEntryUrl() throws Exception { + void createEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "1.dat"); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); @@ -219,7 +218,7 @@ public class JarFileTests { } @Test - public void getMissingEntryUrl() throws Exception { + void getMissingEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); assertThatExceptionOfType(FileNotFoundException.class) @@ -227,14 +226,14 @@ public class JarFileTests { } @Test - public void getUrlStream() throws Exception { + void getUrlStream() throws Exception { URL url = this.jarFile.getUrl(); url.openConnection(); assertThatIOException().isThrownBy(url::openStream); } @Test - public void getEntryUrlStream() throws Exception { + void getEntryUrlStream() throws Exception { URL url = new URL(this.jarFile.getUrl(), "1.dat"); url.openConnection(); InputStream stream = url.openStream(); @@ -243,7 +242,7 @@ public class JarFileTests { } @Test - public void getNestedJarFile() throws Exception { + void getNestedJarFile() throws Exception { JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); Enumeration entries = nestedJarFile.entries(); @@ -276,7 +275,7 @@ public class JarFileTests { } @Test - public void getNestedJarDirectory() throws Exception { + void getNestedJarDirectory() throws Exception { JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("d/")); Enumeration entries = nestedJarFile.entries(); @@ -293,7 +292,7 @@ public class JarFileTests { } @Test - public void getNestedJarEntryUrl() throws Exception { + void getNestedJarEntryUrl() throws Exception { JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL url = nestedJarFile.getJarEntry("3.dat").getUrl(); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); @@ -303,7 +302,7 @@ public class JarFileTests { } @Test - public void createUrlFromString() throws Exception { + void createUrlFromString() throws Exception { JarFile.registerUrlProtocolHandler(); String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"; URL url = new URL(spec); @@ -318,12 +317,12 @@ public class JarFileTests { } @Test - public void createNonNestedUrlFromString() throws Exception { + void createNonNestedUrlFromString() throws Exception { nonNestedJarFileFromString("jar:" + this.rootJarFile.toURI() + "!/2.dat"); } @Test - public void createNonNestedUrlFromPathString() throws Exception { + void createNonNestedUrlFromPathString() throws Exception { nonNestedJarFileFromString("jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat"); } @@ -341,28 +340,28 @@ public class JarFileTests { } @Test - public void getDirectoryInputStream() throws Exception { + void getDirectoryInputStream() throws Exception { InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d/")); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(-1); } @Test - public void getDirectoryInputStreamWithoutSlash() throws Exception { + void getDirectoryInputStreamWithoutSlash() throws Exception { InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d")); assertThat(inputStream).isNotNull(); assertThat(inputStream.read()).isEqualTo(-1); } @Test - public void sensibleToString() throws Exception { + void sensibleToString() throws Exception { assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath()); assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")).toString()) .isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); } @Test - public void verifySignedJar() throws Exception { + void verifySignedJar() throws Exception { String classpath = System.getProperty("java.class.path"); String[] entries = classpath.split(System.getProperty("path.separator")); String signedJarFile = null; @@ -389,8 +388,8 @@ public class JarFileTests { } @Test - public void jarFileWithScriptAtTheStart() throws Exception { - File file = this.temporaryFolder.newFile(); + void jarFileWithScriptAtTheStart() throws Exception { + File file = new File(this.tempDir, "test.jar"); InputStream sourceJarContent = new FileInputStream(this.rootJarFile); FileOutputStream outputStream = new FileOutputStream(file); StreamUtils.copy("#/bin/bash", Charset.defaultCharset(), outputStream); @@ -403,7 +402,7 @@ public class JarFileTests { } @Test - public void cannotLoadMissingJar() throws Exception { + void cannotLoadMissingJar() throws Exception { // relates to gh-1070 JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL nestedUrl = nestedJarFile.getUrl(); @@ -412,7 +411,7 @@ public class JarFileTests { } @Test - public void registerUrlProtocolHandlerWithNoExistingRegistration() { + void registerUrlProtocolHandlerWithNoExistingRegistration() { String original = System.getProperty(PROTOCOL_HANDLER); try { System.clearProperty(PROTOCOL_HANDLER); @@ -431,7 +430,7 @@ public class JarFileTests { } @Test - public void registerUrlProtocolHandlerAddsToExistingRegistration() { + void registerUrlProtocolHandlerAddsToExistingRegistration() { String original = System.getProperty(PROTOCOL_HANDLER); try { System.setProperty(PROTOCOL_HANDLER, "com.example"); @@ -450,16 +449,16 @@ public class JarFileTests { } @Test - public void jarFileCanBeDeletedOnceItHasBeenClosed() throws Exception { - File temp = this.temporaryFolder.newFile(); - TestJarCreator.createTestJar(temp); - JarFile jf = new JarFile(temp); + void jarFileCanBeDeletedOnceItHasBeenClosed() throws Exception { + File jar = new File(this.tempDir, "test.jar"); + TestJarCreator.createTestJar(jar); + JarFile jf = new JarFile(jar); jf.close(); - assertThat(temp.delete()).isTrue(); + assertThat(jar.delete()).isTrue(); } @Test - public void createUrlFromStringWithContextWhenNotFound() throws Exception { + void createUrlFromStringWithContextWhenNotFound() throws Exception { // gh-12483 JarURLConnection.setUseFastExceptions(true); try { @@ -477,7 +476,7 @@ public class JarFileTests { } @Test - public void multiReleaseEntry() throws Exception { + void multiReleaseEntry() throws Exception { JarFile multiRelease = this.jarFile.getNestedJarFile(this.jarFile.getEntry("multi-release.jar")); ZipEntry entry = multiRelease.getEntry("multi-release.dat"); assertThat(entry.getName()).isEqualTo("multi-release.dat"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index f254aaf82ef..ca578cda87b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -21,10 +21,9 @@ import java.io.File; import java.io.FileNotFoundException; import java.net.URL; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.jar.JarURLConnection.JarEntryName; @@ -39,71 +38,68 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Rostyslav Dudka */ -public class JarURLConnectionTests { - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target")); +class JarURLConnectionTests { private File rootJarFile; private JarFile jarFile; - @Before - public void setup() throws Exception { - this.rootJarFile = this.temporaryFolder.newFile(); + @BeforeEach + public void setup(@TempDir File tempDir) throws Exception { + this.rootJarFile = new File(tempDir, "root.jar"); TestJarCreator.createTestJar(this.rootJarFile); this.jarFile = new JarFile(this.rootJarFile); } @Test - public void connectionToRootUsingAbsoluteUrl() throws Exception { + void connectionToRootUsingAbsoluteUrl() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/"); assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test - public void connectionToRootUsingRelativeUrl() throws Exception { + void connectionToRootUsingRelativeUrl() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/"); assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile); } @Test - public void connectionToEntryUsingAbsoluteUrl() throws Exception { + void connectionToEntryUsingAbsoluteUrl() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 })); } @Test - public void connectionToEntryUsingRelativeUrl() throws Exception { + void connectionToEntryUsingRelativeUrl() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/1.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 })); } @Test - public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception { + void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception { URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 })); } @Test - public void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception { + void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception { + void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception { + void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat"); JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) @@ -111,7 +107,7 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception { + void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat"); JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThat(JarURLConnection.get(url, nested).getInputStream()) @@ -119,7 +115,7 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception { + void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception { URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); @@ -128,21 +124,21 @@ public class JarURLConnectionTests { } @Test - public void connectionToEntryWithSpaceNestedEntry() throws Exception { + void connectionToEntryWithSpaceNestedEntry() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/space nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception { + void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception { URL url = new URL("jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat"); assertThat(JarURLConnection.get(url, this.jarFile).getInputStream()) .hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 })); } @Test - public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception { + void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat"); JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")); assertThatExceptionOfType(FileNotFoundException.class) @@ -150,43 +146,43 @@ public class JarURLConnectionTests { } @Test - public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception { + void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception { URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); assertThat(url.openConnection().getContentLength()).isEqualTo(1); } @Test - public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception { + void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception { URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat"); assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1); } @Test - public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception { + void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception { URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat"); JarURLConnection connection = JarURLConnection.get(url, this.jarFile); assertThat(connection.getLastModified()).isEqualTo(connection.getJarEntry().getTime()); } @Test - public void jarEntryBasicName() { + void jarEntryBasicName() { assertThat(new JarEntryName(new StringSequence("a/b/C.class")).toString()).isEqualTo("a/b/C.class"); } @Test - public void jarEntryNameWithSingleByteEncodedCharacters() { + void jarEntryNameWithSingleByteEncodedCharacters() { assertThat(new JarEntryName(new StringSequence("%61/%62/%43.class")).toString()).isEqualTo("a/b/C.class"); } @Test - public void jarEntryNameWithDoubleByteEncodedCharacters() { + void jarEntryNameWithDoubleByteEncodedCharacters() { assertThat(new JarEntryName(new StringSequence("%c3%a1/b/C.class")).toString()).isEqualTo("\u00e1/b/C.class"); } @Test - public void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() { + void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() { assertThat(new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.class")).toString()) .isEqualTo("\u00e1/b/\u00c7.class"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java index 821899d590b..d61f59f1d89 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.loader.jar; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -27,55 +27,55 @@ import static org.assertj.core.api.Assertions.assertThatNullPointerException; * * @author Phillip Webb */ -public class StringSequenceTests { +class StringSequenceTests { @Test - public void createWhenSourceIsNullShouldThrowException() { + void createWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null)) .withMessage("Source must not be null"); } @Test - public void createWithIndexWhenSourceIsNullShouldThrowException() { + void createWithIndexWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null, 0, 0)) .withMessage("Source must not be null"); } @Test - public void createWhenStartIsLessThanZeroShouldThrowException() { + void createWhenStartIsLessThanZeroShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) .isThrownBy(() -> new StringSequence("x", -1, 0)); } @Test - public void createWhenEndIsGreaterThanLengthShouldThrowException() { + void createWhenEndIsGreaterThanLengthShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) .isThrownBy(() -> new StringSequence("x", 0, 2)); } @Test - public void createFromString() { + void createFromString() { assertThat(new StringSequence("test").toString()).isEqualTo("test"); } @Test - public void subSequenceWithJustStartShouldReturnSubSequence() { + void subSequenceWithJustStartShouldReturnSubSequence() { assertThat(new StringSequence("smiles").subSequence(1).toString()).isEqualTo("miles"); } @Test - public void subSequenceShouldReturnSubSequence() { + void subSequenceShouldReturnSubSequence() { assertThat(new StringSequence("hamburger").subSequence(4, 8).toString()).isEqualTo("urge"); assertThat(new StringSequence("smiles").subSequence(1, 5).toString()).isEqualTo("mile"); } @Test - public void subSequenceWhenCalledMultipleTimesShouldReturnSubSequence() { + void subSequenceWhenCalledMultipleTimesShouldReturnSubSequence() { assertThat(new StringSequence("hamburger").subSequence(4, 8).subSequence(1, 3).toString()).isEqualTo("rg"); } @Test - public void subSequenceWhenEndPastExistingEndShouldThrowException() { + void subSequenceWhenEndPastExistingEndShouldThrowException() { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); @@ -83,7 +83,7 @@ public class StringSequenceTests { } @Test - public void subSequenceWhenStartPastExistingEndShouldThrowException() { + void subSequenceWhenStartPastExistingEndShouldThrowException() { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); @@ -91,24 +91,24 @@ public class StringSequenceTests { } @Test - public void isEmptyWhenEmptyShouldReturnTrue() { + void isEmptyWhenEmptyShouldReturnTrue() { assertThat(new StringSequence("").isEmpty()).isTrue(); } @Test - public void isEmptyWhenNotEmptyShouldReturnFalse() { + void isEmptyWhenNotEmptyShouldReturnFalse() { assertThat(new StringSequence("x").isEmpty()).isFalse(); } @Test - public void lengthShouldReturnLength() { + void lengthShouldReturnLength() { StringSequence sequence = new StringSequence("hamburger"); assertThat(sequence.length()).isEqualTo(9); assertThat(sequence.subSequence(4, 8).length()).isEqualTo(4); } @Test - public void charAtShouldReturnChar() { + void charAtShouldReturnChar() { StringSequence sequence = new StringSequence("hamburger"); assertThat(sequence.charAt(0)).isEqualTo('h'); assertThat(sequence.charAt(1)).isEqualTo('a'); @@ -117,7 +117,7 @@ public class StringSequenceTests { } @Test - public void indexOfCharShouldReturnIndexOf() { + void indexOfCharShouldReturnIndexOf() { StringSequence sequence = new StringSequence("aabbaacc"); assertThat(sequence.indexOf('a')).isEqualTo(0); assertThat(sequence.indexOf('b')).isEqualTo(2); @@ -125,7 +125,7 @@ public class StringSequenceTests { } @Test - public void indexOfStringShouldReturnIndexOf() { + void indexOfStringShouldReturnIndexOf() { StringSequence sequence = new StringSequence("aabbaacc"); assertThat(sequence.indexOf("a")).isEqualTo(0); assertThat(sequence.indexOf("b")).isEqualTo(2); @@ -133,7 +133,7 @@ public class StringSequenceTests { } @Test - public void indexOfStringFromIndexShouldReturnIndexOf() { + void indexOfStringFromIndexShouldReturnIndexOf() { StringSequence sequence = new StringSequence("aabbaacc"); assertThat(sequence.indexOf("a", 2)).isEqualTo(4); assertThat(sequence.indexOf("b", 3)).isEqualTo(3); @@ -141,13 +141,13 @@ public class StringSequenceTests { } @Test - public void hashCodeShouldBeSameAsString() { + void hashCodeShouldBeSameAsString() { assertThat(new StringSequence("hamburger").hashCode()).isEqualTo("hamburger".hashCode()); assertThat(new StringSequence("hamburger").subSequence(4, 8).hashCode()).isEqualTo("urge".hashCode()); } @Test - public void equalsWhenSameContentShouldMatch() { + void equalsWhenSameContentShouldMatch() { StringSequence a = new StringSequence("hamburger").subSequence(4, 8); StringSequence b = new StringSequence("urge"); StringSequence c = new StringSequence("urgh"); @@ -155,50 +155,50 @@ public class StringSequenceTests { } @Test - public void notEqualsWhenSequencesOfDifferentLength() { + void notEqualsWhenSequencesOfDifferentLength() { StringSequence a = new StringSequence("abcd"); StringSequence b = new StringSequence("ef"); assertThat(a).isNotEqualTo(b); } @Test - public void startsWithWhenExactMatch() { + void startsWithWhenExactMatch() { assertThat(new StringSequence("abc").startsWith("abc")).isTrue(); } @Test - public void startsWithWhenLongerAndStartsWith() { + void startsWithWhenLongerAndStartsWith() { assertThat(new StringSequence("abcd").startsWith("abc")).isTrue(); } @Test - public void startsWithWhenLongerAndDoesNotStartWith() { + void startsWithWhenLongerAndDoesNotStartWith() { assertThat(new StringSequence("abcd").startsWith("abx")).isFalse(); } @Test - public void startsWithWhenShorterAndDoesNotStartWith() { + void startsWithWhenShorterAndDoesNotStartWith() { assertThat(new StringSequence("ab").startsWith("abc")).isFalse(); assertThat(new StringSequence("ab").startsWith("c")).isFalse(); } @Test - public void startsWithOffsetWhenExactMatch() { + void startsWithOffsetWhenExactMatch() { assertThat(new StringSequence("xabc").startsWith("abc", 1)).isTrue(); } @Test - public void startsWithOffsetWhenLongerAndStartsWith() { + void startsWithOffsetWhenLongerAndStartsWith() { assertThat(new StringSequence("xabcd").startsWith("abc", 1)).isTrue(); } @Test - public void startsWithOffsetWhenLongerAndDoesNotStartWith() { + void startsWithOffsetWhenLongerAndDoesNotStartWith() { assertThat(new StringSequence("xabcd").startsWith("abx", 1)).isFalse(); } @Test - public void startsWithOffsetWhenShorterAndDoesNotStartWith() { + void startsWithOffsetWhenShorterAndDoesNotStartWith() { assertThat(new StringSequence("xab").startsWith("abc", 1)).isFalse(); assertThat(new StringSequence("xab").startsWith("c", 1)).isFalse(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java index 6733a24d149..dd59cf980ae 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.loader.util; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,35 +27,35 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class SystemPropertyUtilsTests { +class SystemPropertyUtilsTests { - @BeforeClass - public static void init() { + @BeforeEach + public void init() { System.setProperty("foo", "bar"); } - @AfterClass - public static void close() { + @AfterEach + public void close() { System.clearProperty("foo"); } @Test - public void testVanillaPlaceholder() { + void testVanillaPlaceholder() { assertThat(SystemPropertyUtils.resolvePlaceholders("${foo}")).isEqualTo("bar"); } @Test - public void testDefaultValue() { + void testDefaultValue() { assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")).isEqualTo("foo"); } @Test - public void testNestedPlaceholder() { + void testNestedPlaceholder() { assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")).isEqualTo("foo"); } @Test - public void testEnvVar() { + void testEnvVar() { assertThat(SystemPropertyUtils.getProperty("lang")).isEqualTo(System.getenv("LANG")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index 1cfec166e81..a0fe0e56e0e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -26,8 +26,8 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ArtifactsLibrariesTests { +class ArtifactsLibrariesTests { @Mock private Artifact artifact; @@ -68,7 +68,7 @@ public class ArtifactsLibrariesTests { @Captor private ArgumentCaptor libraryCaptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.artifacts = Collections.singleton(this.artifact); @@ -79,7 +79,7 @@ public class ArtifactsLibrariesTests { } @Test - public void callbackForJars() throws Exception { + void callbackForJars() throws Exception { given(this.artifact.getType()).willReturn("jar"); given(this.artifact.getScope()).willReturn("compile"); this.libs.doWithLibraries(this.callback); @@ -91,7 +91,7 @@ public class ArtifactsLibrariesTests { } @Test - public void callbackWithUnpack() throws Exception { + void callbackWithUnpack() throws Exception { given(this.artifact.getGroupId()).willReturn("gid"); given(this.artifact.getArtifactId()).willReturn("aid"); given(this.artifact.getType()).willReturn("jar"); @@ -106,7 +106,7 @@ public class ArtifactsLibrariesTests { } @Test - public void renamesDuplicates() throws Exception { + void renamesDuplicates() throws Exception { Artifact artifact1 = mock(Artifact.class); Artifact artifact2 = mock(Artifact.class); given(artifact1.getType()).willReturn("jar"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java index 5d8091e3a0c..e3b73ce9357 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java @@ -26,7 +26,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.ScopeFilter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -37,10 +37,10 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class DependencyFilterMojoTests { +class DependencyFilterMojoTests { @Test - public void filterDependencies() throws MojoExecutionException { + void filterDependencies() throws MojoExecutionException { TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact artifact = createArtifact("com.bar", "one"); @@ -51,7 +51,7 @@ public class DependencyFilterMojoTests { } @Test - public void filterGroupIdExactMatch() throws MojoExecutionException { + void filterGroupIdExactMatch() throws MojoExecutionException { TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact artifact = createArtifact("com.foo.bar", "one"); @@ -62,7 +62,7 @@ public class DependencyFilterMojoTests { } @Test - public void filterScopeKeepOrder() throws MojoExecutionException { + void filterScopeKeepOrder() throws MojoExecutionException { TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "", new ScopeFilter(null, Artifact.SCOPE_SYSTEM)); Artifact one = createArtifact("com.foo", "one"); @@ -73,7 +73,7 @@ public class DependencyFilterMojoTests { } @Test - public void filterGroupIdKeepOrder() throws MojoExecutionException { + void filterGroupIdKeepOrder() throws MojoExecutionException { TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo"); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.bar", "two"); @@ -84,7 +84,7 @@ public class DependencyFilterMojoTests { } @Test - public void filterExcludeKeepOrder() throws MojoExecutionException { + void filterExcludeKeepOrder() throws MojoExecutionException { Exclude exclude = new Exclude(); exclude.setGroupId("com.bar"); exclude.setArtifactId("two"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java index a8770c1f4f9..88363adc93d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/EnvVariablesTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.maven; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; @@ -29,22 +29,22 @@ import static org.assertj.core.api.Assertions.entry; * * @author Dmytro Nosan */ -public class EnvVariablesTests { +class EnvVariablesTests { @Test - public void asNull() { + void asNull() { Map args = new EnvVariables(null).asMap(); assertThat(args).isEmpty(); } @Test - public void asArray() { + void asArray() { assertThat(new EnvVariables(getTestArgs()).asArray()).contains("key=My Value", "key1= tt ", "key2= ", "key3="); } @Test - public void asMap() { + void asMap() { assertThat(new EnvVariables(getTestArgs()).asMap()).containsExactly(entry("key", "My Value"), entry("key1", " tt "), entry("key2", " "), entry("key3", "")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java index 995df1d0325..cceca0c8b3d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java @@ -23,7 +23,7 @@ import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -36,17 +36,17 @@ import static org.mockito.Mockito.mock; * @author David Turanski */ @SuppressWarnings({ "rawtypes", "unchecked" }) -public class ExcludeFilterTests { +class ExcludeFilterTests { @Test - public void excludeSimple() throws ArtifactFilterException { + void excludeSimple() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar"))); assertThat(result).isEmpty(); } @Test - public void excludeGroupIdNoMatch() throws ArtifactFilterException { + void excludeGroupIdNoMatch() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); @@ -55,7 +55,7 @@ public class ExcludeFilterTests { } @Test - public void excludeArtifactIdNoMatch() throws ArtifactFilterException { + void excludeArtifactIdNoMatch() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); @@ -64,14 +64,14 @@ public class ExcludeFilterTests { } @Test - public void excludeClassifier() throws ArtifactFilterException { + void excludeClassifier() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); assertThat(result).isEmpty(); } @Test - public void excludeClassifierNoTargetClassifier() throws ArtifactFilterException { + void excludeClassifierNoTargetClassifier() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); @@ -80,7 +80,7 @@ public class ExcludeFilterTests { } @Test - public void excludeClassifierNoMatch() throws ArtifactFilterException { + void excludeClassifierNoMatch() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); @@ -89,7 +89,7 @@ public class ExcludeFilterTests { } @Test - public void excludeMulti() throws ArtifactFilterException { + void excludeMulti() throws ArtifactFilterException { ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"), createExclude("com.foo", "bar2"), createExclude("org.acme", "app"))); Set artifacts = new HashSet<>(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java index c07ecfce002..1d63e6088a6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java @@ -23,7 +23,7 @@ import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock; * @author David Turanski */ @SuppressWarnings({ "rawtypes", "unchecked" }) -public class IncludeFilterTests { +class IncludeFilterTests { @Test - public void includeSimple() throws ArtifactFilterException { + void includeSimple() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); @@ -47,7 +47,7 @@ public class IncludeFilterTests { } @Test - public void includeGroupIdNoMatch() throws ArtifactFilterException { + void includeGroupIdNoMatch() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); @@ -55,7 +55,7 @@ public class IncludeFilterTests { } @Test - public void includeArtifactIdNoMatch() throws ArtifactFilterException { + void includeArtifactIdNoMatch() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); @@ -63,7 +63,7 @@ public class IncludeFilterTests { } @Test - public void includeClassifier() throws ArtifactFilterException { + void includeClassifier() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk5"); Set result = filter.filter(Collections.singleton(artifact)); @@ -72,7 +72,7 @@ public class IncludeFilterTests { } @Test - public void includeClassifierNoTargetClassifier() throws ArtifactFilterException { + void includeClassifierNoTargetClassifier() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); @@ -80,7 +80,7 @@ public class IncludeFilterTests { } @Test - public void includeClassifierNoMatch() throws ArtifactFilterException { + void includeClassifierNoMatch() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); @@ -88,7 +88,7 @@ public class IncludeFilterTests { } @Test - public void includeMulti() throws ArtifactFilterException { + void includeMulti() throws ArtifactFilterException { IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"), createInclude("com.foo", "bar2"), createInclude("org.acme", "app"))); Set artifacts = new HashSet<>(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java index bb3ea1cb9ea..f221c5fad52 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java @@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.jar.JarOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class PropertiesMergingResourceTransformerTests { +class PropertiesMergingResourceTransformerTests { private final PropertiesMergingResourceTransformer transformer = new PropertiesMergingResourceTransformer(); @Test - public void testProcess() throws Exception { + void testProcess() throws Exception { assertThat(this.transformer.hasTransformedResource()).isFalse(); this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); assertThat(this.transformer.hasTransformedResource()).isTrue(); } @Test - public void testMerge() throws Exception { + void testMerge() throws Exception { this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); this.transformer.processResource("bar", new ByteArrayInputStream("foo=spam".getBytes()), null); assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam"); } @Test - public void testOutput() throws Exception { + void testOutput() throws Exception { this.transformer.setResource("foo"); this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); ByteArrayOutputStream out = new ByteArrayOutputStream(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java index 6a7843ddd04..87a92131511 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.maven; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,45 +25,45 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class RunArgumentsTests { +class RunArgumentsTests { @Test - public void parseNull() { + void parseNull() { String[] args = parseArgs(null); assertThat(args).isNotNull(); assertThat(args.length).isEqualTo(0); } @Test - public void parseNullArray() { + void parseNullArray() { String[] args = new RunArguments((String[]) null).asArray(); assertThat(args).isNotNull(); assertThat(args.length).isEqualTo(0); } @Test - public void parseArrayContainingNullValue() { + void parseArrayContainingNullValue() { String[] args = new RunArguments(new String[] { "foo", null, "bar" }).asArray(); assertThat(args).isNotNull(); assertThat(args).containsOnly("foo", "bar"); } @Test - public void parseArrayContainingEmptyValue() { + void parseArrayContainingEmptyValue() { String[] args = new RunArguments(new String[] { "foo", "", "bar" }).asArray(); assertThat(args).isNotNull(); assertThat(args).containsOnly("foo", "", "bar"); } @Test - public void parseEmpty() { + void parseEmpty() { String[] args = parseArgs(" "); assertThat(args).isNotNull(); assertThat(args.length).isEqualTo(0); } @Test - public void parseDebugFlags() { + void parseDebugFlags() { String[] args = parseArgs("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); assertThat(args.length).isEqualTo(2); assertThat(args[0]).isEqualTo("-Xdebug"); @@ -71,7 +71,7 @@ public class RunArgumentsTests { } @Test - public void parseWithExtraSpaces() { + void parseWithExtraSpaces() { String[] args = parseArgs(" -Dfoo=bar -Dfoo2=bar2 "); assertThat(args.length).isEqualTo(2); assertThat(args[0]).isEqualTo("-Dfoo=bar"); @@ -79,7 +79,7 @@ public class RunArgumentsTests { } @Test - public void parseWithNewLinesAndTabs() { + void parseWithNewLinesAndTabs() { String[] args = parseArgs(" -Dfoo=bar \n" + "\t\t -Dfoo2=bar2 "); assertThat(args.length).isEqualTo(2); assertThat(args[0]).isEqualTo("-Dfoo=bar"); @@ -87,7 +87,7 @@ public class RunArgumentsTests { } @Test - public void quoteHandledProperly() { + void quoteHandledProperly() { String[] args = parseArgs("-Dvalue=\"My Value\" "); assertThat(args.length).isEqualTo(1); assertThat(args[0]).isEqualTo("-Dvalue=My Value"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java index 075bd381178..0099859bd3b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/SystemPropertyFormatterTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.maven; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.maven.AbstractRunMojo.SystemPropertyFormatter; @@ -25,30 +25,30 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AbstractRunMojo.SystemPropertyFormatter}. */ -public class SystemPropertyFormatterTests { +class SystemPropertyFormatterTests { @Test - public void parseEmpty() { + void parseEmpty() { assertThat(SystemPropertyFormatter.format(null, null)).isEqualTo(""); } @Test - public void parseOnlyKey() { + void parseOnlyKey() { assertThat(SystemPropertyFormatter.format("key1", null)).isEqualTo("-Dkey1"); } @Test - public void parseKeyWithValue() { + void parseKeyWithValue() { assertThat(SystemPropertyFormatter.format("key1", "value1")).isEqualTo("-Dkey1=\"value1\""); } @Test - public void parseKeyWithEmptyValue() { + void parseKeyWithEmptyValue() { assertThat(SystemPropertyFormatter.format("key1", "")).isEqualTo("-Dkey1"); } @Test - public void parseKeyWithOnlySpaces() { + void parseKeyWithOnlySpaces() { assertThat(SystemPropertyFormatter.format("key1", " ")).isEqualTo("-Dkey1=\" \""); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml b/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml index 2445f43df46..4d7e027f915 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml @@ -109,6 +109,11 @@ + + org.testcontainers + junit-jupiter + true + junit diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/Assume.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/Assume.java deleted file mode 100644 index ab9d1419969..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/Assume.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testsupport; - -import org.junit.AssumptionViolatedException; - -import org.springframework.util.ClassUtils; - -/** - * Provides utility methods that allow JUnit tests to {@link org.junit.Assume} certain - * conditions hold {@code true}. If the assumption fails, it means the test should be - * skipped. - * - * @author Stephane Nicoll - */ -public abstract class Assume { - - public static void javaEight() { - if (ClassUtils.isPresent("java.security.cert.URICertStoreParameters", null)) { - throw new AssumptionViolatedException("Assumed Java 8 but got Java 9"); - } - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java index 6602dda9a62..ffd7a08105c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/compiler/TestCompiler.java @@ -29,8 +29,6 @@ import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; -import org.junit.rules.TemporaryFolder; - /** * Wrapper to make the {@link JavaCompiler} easier to use in tests. * @@ -51,14 +49,15 @@ public class TestCompiler { private final File outputLocation; - public TestCompiler(TemporaryFolder temporaryFolder) throws IOException { - this(ToolProvider.getSystemJavaCompiler(), temporaryFolder); + public TestCompiler(File outputLocation) throws IOException { + this(ToolProvider.getSystemJavaCompiler(), outputLocation); } - public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) throws IOException { + public TestCompiler(JavaCompiler compiler, File outputLocation) throws IOException { this.compiler = compiler; this.fileManager = compiler.getStandardFileManager(null, null, null); - this.outputLocation = temporaryFolder.newFolder(); + this.outputLocation = outputLocation; + this.outputLocation.mkdirs(); Iterable temp = Arrays.asList(this.outputLocation); this.fileManager.setLocation(StandardLocation.CLASS_OUTPUT, temp); this.fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, temp); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java index 8fa95a18ad1..15ad1eaf264 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/context/AbstractConfigurationClassTests.java @@ -20,7 +20,7 @@ import java.io.IOException; import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.asm.Opcodes; import org.springframework.beans.DirectFieldAccessor; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/OutputCapture.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/OutputCapture.java deleted file mode 100644 index 66e6251cd34..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/OutputCapture.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testsupport.rule; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; - -import org.hamcrest.Matcher; -import org.junit.Assert; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import static org.hamcrest.Matchers.allOf; - -/** - * Internal JUnit {@code @Rule} to capture output from System.out and System.err. - * - * @author Phillip Webb - * @author Andy Wilkinson - */ -public class OutputCapture implements TestRule { - - private CaptureOutputStream captureOut; - - private CaptureOutputStream captureErr; - - private ByteArrayOutputStream copy; - - private List> matchers = new ArrayList<>(); - - @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - captureOutput(); - try { - base.evaluate(); - } - finally { - try { - if (!OutputCapture.this.matchers.isEmpty()) { - String output = OutputCapture.this.toString(); - Assert.assertThat(output, allOf(OutputCapture.this.matchers)); - } - } - finally { - releaseOutput(); - } - } - } - }; - } - - protected void captureOutput() { - // FIXME AnsiOutput.setEnabled(Enabled.NEVER); - this.copy = new ByteArrayOutputStream(); - this.captureOut = new CaptureOutputStream(System.out, this.copy); - this.captureErr = new CaptureOutputStream(System.err, this.copy); - System.setOut(new PrintStream(this.captureOut)); - System.setErr(new PrintStream(this.captureErr)); - } - - protected void releaseOutput() { - // FIXME AnsiOutput.setEnabled(Enabled.DETECT); - System.setOut(this.captureOut.getOriginal()); - System.setErr(this.captureErr.getOriginal()); - this.copy = null; - } - - public void flush() { - try { - this.captureOut.flush(); - this.captureErr.flush(); - } - catch (IOException ex) { - // ignore - } - } - - @Override - public String toString() { - flush(); - return this.copy.toString(); - } - - /** - * Verify that the output is matched by the supplied {@code matcher}. Verification is - * performed after the test method has executed. - * @param matcher the matcher - */ - public void expect(Matcher matcher) { - this.matchers.add(matcher); - } - - private static class CaptureOutputStream extends OutputStream { - - private final PrintStream original; - - private final OutputStream copy; - - CaptureOutputStream(PrintStream original, OutputStream copy) { - this.original = original; - this.copy = copy; - } - - @Override - public void write(int b) throws IOException { - this.copy.write(b); - this.original.write(b); - this.original.flush(); - } - - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - this.copy.write(b, off, len); - this.original.write(b, off, len); - } - - public PrintStream getOriginal() { - return this.original; - } - - @Override - public void flush() throws IOException { - this.copy.flush(); - this.original.flush(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/CapturedOutput.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/CapturedOutput.java new file mode 100644 index 00000000000..b3e4800c243 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/CapturedOutput.java @@ -0,0 +1,71 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.system; + +/** + * Provides access to {@link System#out System.out} and {@link System#err System.err} + * output that has been capture by the {@link OutputCaptureExtension}. Can be used to + * apply assertions either using AssertJ or standard JUnit assertions. For example: + *
+ * assertThat(output).contains("started"); // Checks all output
+ * assertThat(output.getErr()).contains("failed"); // Only checks System.err
+ * assertThat(output.getOut()).contains("ok"); // Only checks System.put
+ * 
+ * + * @author Madhura Bhave + * @author Phillip Webb + * @author Andy Wilkinson + * @since 2.2.0 + * @see OutputCaptureExtension + */ +public interface CapturedOutput extends CharSequence { + + @Override + default int length() { + return toString().length(); + } + + @Override + default char charAt(int index) { + return toString().charAt(index); + } + + @Override + default CharSequence subSequence(int start, int end) { + return toString().subSequence(start, end); + } + + /** + * Return all content (both {@link System#out System.out} and {@link System#err + * System.err}) in the order that it was was captured. + * @return all captured output + */ + String getAll(); + + /** + * Return {@link System#out System.out} content in the order that it was was captured. + * @return {@link System#out System.out} captured output + */ + String getOut(); + + /** + * Return {@link System#err System.err} content in the order that it was was captured. + * @return {@link System#err System.err} captured output + */ + String getErr(); + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java new file mode 100644 index 00000000000..b97402d50f6 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java @@ -0,0 +1,273 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.system; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; + +import org.springframework.util.Assert; + +/** + * Provides support for capturing {@link System#out System.out} and {@link System#err + * System.err}. + * + * @author Madhura Bhave + * @author Phillip Webb + * @author Andy Wilkinson + * @see OutputCaptureExtension + * @see OutputCaptureRule + */ +class OutputCapture implements CapturedOutput { + + private final Deque systemCaptures = new ArrayDeque<>(); + + /** + * Push a new system capture session onto the stack. + */ + final void push() { + this.systemCaptures.addLast(new SystemCapture()); + } + + /** + * Pop the last system capture session from the stack. + */ + final void pop() { + this.systemCaptures.removeLast().release(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof CapturedOutput || obj instanceof CharSequence) { + return getAll().equals(obj.toString()); + } + return false; + } + + @Override + public int hashCode() { + return toString().hashCode(); + } + + @Override + public String toString() { + return getAll(); + } + + /** + * Return all content (both {@link System#out System.out} and {@link System#err + * System.err}) in the order that it was was captured. + * @return all captured output + */ + @Override + public String getAll() { + return get((type) -> true); + } + + /** + * Return {@link System#out System.out} content in the order that it was was captured. + * @return {@link System#out System.out} captured output + */ + @Override + public String getOut() { + return get(Type.OUT::equals); + } + + /** + * Return {@link System#err System.err} content in the order that it was was captured. + * @return {@link System#err System.err} captured output + */ + @Override + public String getErr() { + return get(Type.ERR::equals); + } + + /** + * Resets the current capture session, clearing its captured output. + */ + void reset() { + this.systemCaptures.peek().reset(); + } + + private String get(Predicate filter) { + Assert.state(!this.systemCaptures.isEmpty(), + "No system captures found. Check that you have used @RegisterExtension " + + "or @ExtendWith and the fields are not private"); + StringBuilder builder = new StringBuilder(); + for (SystemCapture systemCapture : this.systemCaptures) { + systemCapture.append(builder, filter); + } + return builder.toString(); + } + + /** + * A capture session that captures {@link System#out System.out} and {@link System#out + * System.err}. + */ + private static class SystemCapture { + + private final PrintStreamCapture out; + + private final PrintStreamCapture err; + + private final Object monitor = new Object(); + + private final List capturedStrings = new ArrayList<>(); + + SystemCapture() { + this.out = new PrintStreamCapture(System.out, this::captureOut); + this.err = new PrintStreamCapture(System.err, this::captureErr); + System.setOut(this.out); + System.setErr(this.err); + } + + public void release() { + System.setOut(this.out.getParent()); + System.setErr(this.err.getParent()); + } + + private void captureOut(String string) { + synchronized (this.monitor) { + this.capturedStrings.add(new CapturedString(Type.OUT, string)); + } + } + + private void captureErr(String string) { + synchronized (this.monitor) { + this.capturedStrings.add(new CapturedString(Type.ERR, string)); + } + } + + public void append(StringBuilder builder, Predicate filter) { + synchronized (this.monitor) { + for (CapturedString stringCapture : this.capturedStrings) { + if (filter.test(stringCapture.getType())) { + builder.append(stringCapture); + } + } + } + } + + public void reset() { + synchronized (this.monitor) { + this.capturedStrings.clear(); + } + } + + } + + /** + * A {@link PrintStream} implementation that captures written strings. + */ + private static class PrintStreamCapture extends PrintStream { + + private final PrintStream parent; + + PrintStreamCapture(PrintStream parent, Consumer copy) { + super(new OutputStreamCapture(getSystemStream(parent), copy)); + this.parent = parent; + } + + public PrintStream getParent() { + return this.parent; + } + + private static PrintStream getSystemStream(PrintStream printStream) { + while (printStream instanceof PrintStreamCapture) { + return ((PrintStreamCapture) printStream).getParent(); + } + return printStream; + } + + } + + /** + * An {@link OutputStream} implementation that captures written strings. + */ + private static class OutputStreamCapture extends OutputStream { + + private final PrintStream systemStream; + + private final Consumer copy; + + OutputStreamCapture(PrintStream systemStream, Consumer copy) { + this.systemStream = systemStream; + this.copy = copy; + } + + @Override + public void write(int b) throws IOException { + write(new byte[] { (byte) (b & 0xFF) }); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + this.copy.accept(new String(b, off, len)); + this.systemStream.write(b, off, len); + } + + @Override + public void flush() throws IOException { + this.systemStream.flush(); + } + + } + + /** + * A captured string that forms part of the full output. + */ + private static class CapturedString { + + private final Type type; + + private final String string; + + CapturedString(Type type, String string) { + this.type = type; + this.string = string; + } + + public Type getType() { + return this.type; + } + + @Override + public String toString() { + return this.string; + } + + } + + /** + * Types of content that can be captured. + */ + private enum Type { + + OUT, ERR + + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureExtension.java new file mode 100644 index 00000000000..d990d4b9538 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureExtension.java @@ -0,0 +1,98 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.system; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +/** + * Internal JUnit 5 {@code @Extension} to capture {@link System#out System.out} and + * {@link System#err System.err}. Can be used on a test class via + * {@link ExtendWith @ExtendWith}. This extension provides {@link ParameterResolver + * parameter resolution} for a {@link CapturedOutput} instance which can be used to assert + * that the correct output was written. + *

+ * To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as an + * argument to your test class constructor or test method: + * + *

+ * @ExtendWith(OutputExtension.class)
+ * class MyTest {
+ *
+ *     @Test
+ *     void test(CapturedOutput output) {
+ *         assertThat(output).contains("ok");
+ *     }
+ *
+ * }
+ * 
+ * + * @author Madhura Bhave + * @author Phillip Webb + * @author Andy Wilkinson + * @since 2.2.0 + * @see CapturedOutput + */ +public class OutputCaptureExtension + implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver { + + private final OutputCapture outputCapture = new OutputCapture(); + + OutputCaptureExtension() { + // Package private to prevent users from directly creating an instance. + } + + @Override + public void beforeAll(ExtensionContext context) throws Exception { + this.outputCapture.push(); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + this.outputCapture.pop(); + } + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + this.outputCapture.push(); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + this.outputCapture.pop(); + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return CapturedOutput.class.equals(parameterContext.getParameter().getType()); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return this.outputCapture; + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureRule.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureRule.java new file mode 100644 index 00000000000..78138052282 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureRule.java @@ -0,0 +1,80 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.system; + +import java.util.ArrayList; +import java.util.List; + +import org.hamcrest.Matcher; +import org.junit.Assert; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +import static org.hamcrest.Matchers.allOf; + +/** + * Internal JUnit {@code @Rule} to capture output from System.out and System.err. + * + * @author Phillip Webb + * @author Andy Wilkinson + */ +public class OutputCaptureRule implements TestRule { + + private final OutputCapture delegate = new OutputCapture(); + + private List> matchers = new ArrayList<>(); + + @Override + public Statement apply(Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + OutputCaptureRule.this.delegate.push(); + try { + base.evaluate(); + } + finally { + try { + if (!OutputCaptureRule.this.matchers.isEmpty()) { + String output = OutputCaptureRule.this.delegate.toString(); + Assert.assertThat(output, allOf(OutputCaptureRule.this.matchers)); + } + } + finally { + OutputCaptureRule.this.delegate.pop(); + } + } + } + }; + } + + @Override + public String toString() { + return this.delegate.toString(); + } + + /** + * Verify that the output is matched by the supplied {@code matcher}. Verification is + * performed after the test method has executed. + * @param matcher the matcher + */ + public void expect(Matcher matcher) { + this.matchers.add(matcher); + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/package-info.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/package-info.java similarity index 77% rename from spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/package-info.java rename to spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/package-info.java index e6545bce906..9849d59af64 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/package-info.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,6 @@ */ /** - * Internal JUnit rules used in Spring Boot tests. + * Classes for {@link java.lang.System System}-related testing. */ -package org.springframework.boot.testsupport.rule; +package org.springframework.boot.testsupport.system; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java deleted file mode 100644 index 0c3924147e5..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Container.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testsupport.testcontainers; - -import java.util.function.Consumer; -import java.util.function.Supplier; - -import org.junit.jupiter.api.Assumptions; -import org.junit.rules.TestRule; -import org.testcontainers.DockerClientFactory; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.lifecycle.Startable; - -/** - * {@link TestRule} for working with an optional Docker environment. Spins up a - * {@link GenericContainer} if a valid docker environment is found. - * - * @author Madhura Bhave - * @author Phillip Webb - */ -class Container implements Startable { - - private final int port; - - private final Supplier> containerFactory; - - private GenericContainer container; - - > Container(String dockerImageName, int port) { - this(dockerImageName, port, null); - } - - @SuppressWarnings({ "unchecked", "resource" }) - > Container(String dockerImageName, int port, Consumer customizer) { - this.port = port; - this.containerFactory = () -> { - T container = (T) new GenericContainer<>(dockerImageName).withExposedPorts(port); - if (customizer != null) { - customizer.accept(container); - } - return container; - }; - } - - public int getMappedPort() { - return this.container.getMappedPort(this.port); - } - - protected GenericContainer getContainer() { - return this.container; - } - - @Override - public void start() { - Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment."); - this.container = this.containerFactory.get(); - this.container.start(); - } - - private boolean isDockerRunning() { - try { - DockerClientFactory.instance().client(); - return true; - } - catch (Throwable ex) { - return false; - } - } - - @Override - public void stop() { - if (this.container != null) { - this.container.stop(); - } - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DisabledWithoutDockerTestcontainers.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DisabledWithoutDockerTestcontainers.java new file mode 100644 index 00000000000..a5ae35a15ab --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DisabledWithoutDockerTestcontainers.java @@ -0,0 +1,39 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.testcontainers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Customization of {@link Testcontainers @Testcontainers} that disables the tests when + * Docker is not available. + * + * @author Andy Wilkinson + */ +@ExtendWith(DockerIsAvailableCondition.class) +@Testcontainers +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface DisabledWithoutDockerTestcontainers { + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DockerIsAvailableCondition.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DockerIsAvailableCondition.java new file mode 100644 index 00000000000..c8e3fbdac34 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/DockerIsAvailableCondition.java @@ -0,0 +1,43 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.testsupport.testcontainers; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.testcontainers.DockerClientFactory; + +/** + * {@link ExecutionCondition} for + * {@link DisabledWithoutDockerTestcontainers @DisabledWithoutDockerTestcontainers}. + * + * @author Andy Wilkinson + */ +final class DockerIsAvailableCondition implements ExecutionCondition { + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + try { + DockerClientFactory.instance().client(); + return ConditionEvaluationResult.enabled("Docker is available"); + } + catch (Throwable ex) { + return ConditionEvaluationResult.disabled("Docker is not available: " + ex.getMessage()); + } + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java deleted file mode 100644 index b040fe0bb2c..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/ElasticsearchContainer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testsupport.testcontainers; - -import java.time.Duration; - -/** - * A {@link Container} for Elasticsearch. - * - * @author Andy Wilkinson - */ -public class ElasticsearchContainer extends Container { - - public ElasticsearchContainer() { - super("elasticsearch:6.7.2", 9200, (container) -> container.withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(5).withEnv("discovery.type", "single-node").addExposedPorts(9200, 9300)); - } - - public int getMappedTransportPort() { - return getContainer().getMappedPort(9300); - } - - public int getMappedHttpPort() { - return getContainer().getMappedPort(9200); - } - - @Override - public void start() { - System.setProperty("es.set.netty.runtime.available.processors", "false"); - super.start(); - } - - @Override - public void stop() { - System.clearProperty("es.set.netty.runtime.available.processors"); - super.stop(); - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/RedisContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/RedisContainer.java index 3a149b50732..e8794fed158 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/RedisContainer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/RedisContainer.java @@ -24,10 +24,11 @@ import org.testcontainers.containers.GenericContainer; * @author Andy Wilkinson * @author Madhura Bhave */ -public class RedisContainer extends Container { +public class RedisContainer extends GenericContainer { public RedisContainer() { - super("redis:4.0.6", 6379); + super("redis:4.0.6"); + addExposedPorts(6379); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java deleted file mode 100644 index 0d91d18e7ed..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/SkippableContainer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testsupport.testcontainers; - -import java.util.function.Supplier; - -import org.junit.jupiter.api.Assumptions; -import org.testcontainers.DockerClientFactory; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.lifecycle.Startable; - -/** - * A {@link GenericContainer} decorator that skips test execution when Docker is not - * available. - * - * @param type of the underlying container - * @author Andy Wilkinson - * @author Madhura Bhave - */ -public class SkippableContainer> implements Startable { - - private final Supplier containerFactory; - - private T container; - - public SkippableContainer(Supplier containerFactory) { - this.containerFactory = containerFactory; - } - - public T getContainer() { - if (this.container == null) { - throw new IllegalStateException("Container cannot be accessed prior to test invocation"); - } - return this.container; - } - - @Override - public void start() { - Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment."); - this.container = this.containerFactory.get(); - this.container.start(); - } - - private boolean isDockerRunning() { - try { - DockerClientFactory.instance().client(); - return true; - } - catch (Throwable ex) { - return false; - } - } - - @Override - public void stop() { - if (this.container != null) { - this.container.stop(); - } - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/package-info.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/package-info.java deleted file mode 100644 index c6b1f244ed9..00000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Support for integration testing with Testcontainers. - */ -package org.springframework.boot.testsupport.testcontainers; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java index 1f1b58295ce..30d6b5d689b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.testsupport.assertj; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -27,27 +27,27 @@ import static org.hamcrest.Matchers.startsWith; * * @author Phillip Webb */ -public class MatchedTests { +class MatchedTests { @Test - public void byMatcherMatches() { + void byMatcherMatches() { assertThat("1234").is(Matched.by(startsWith("12"))); } @Test - public void byMatcherDoesNotMatch() { + void byMatcherDoesNotMatch() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat("1234").is(Matched.by(startsWith("23")))) .withMessageContaining("a string starting with \"23\""); } @Test - public void whenMatcherMatches() { + void whenMatcherMatches() { assertThat("1234").is(Matched.when(startsWith("12"))); } @Test - public void whenMatcherDoesNotMatch() { + void whenMatcherDoesNotMatch() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertThat("1234").is(Matched.when(startsWith("23")))) .withMessageContaining("a string starting with \"23\""); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AdhocTestSuite.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AdhocTestSuite.java deleted file mode 100644 index 63b647ad4fd..00000000000 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AdhocTestSuite.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot; - -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * A test suite for probing weird ordering problems in the tests. - * - * @author Dave Syer - */ -@RunWith(Suite.class) -@SuiteClasses({}) -@Ignore -public class AdhocTestSuite { - -} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index 580292fe436..8a329b8614c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -18,16 +18,17 @@ package org.springframework.boot; import java.io.PrintStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.springframework.boot.Banner.Mode; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @@ -46,59 +47,57 @@ import static org.mockito.Mockito.verify; * @author Michael Stummvoll * @author Michael Simons */ -public class BannerTests { +@ExtendWith(OutputCaptureExtension.class) +class BannerTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); } } - @Rule - public OutputCapture out = new OutputCapture(); - @Captor private ArgumentCaptor> sourceClassCaptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void testDefaultBanner() { + void testDefaultBanner(CapturedOutput capturedOutput) { SpringApplication application = createSpringApplication(); this.context = application.run(); - assertThat(this.out.toString()).contains(":: Spring Boot ::"); + assertThat(capturedOutput).contains(":: Spring Boot ::"); } @Test - public void testDefaultBannerInLog() { + void testDefaultBannerInLog(CapturedOutput capturedOutput) { SpringApplication application = createSpringApplication(); this.context = application.run(); - assertThat(this.out.toString()).contains(":: Spring Boot ::"); + assertThat(capturedOutput).contains(":: Spring Boot ::"); } @Test - public void testCustomBanner() { + void testCustomBanner(CapturedOutput capturedOutput) { SpringApplication application = createSpringApplication(); application.setBanner(new DummyBanner()); this.context = application.run(); - assertThat(this.out.toString()).contains("My Banner"); + assertThat(capturedOutput).contains("My Banner"); } @Test - public void testBannerInContext() { + void testBannerInContext() { SpringApplication application = createSpringApplication(); this.context = application.run(); assertThat(this.context.containsBean("springBootBanner")).isTrue(); } @Test - public void testCustomBannerInContext() { + void testCustomBannerInContext() { SpringApplication application = createSpringApplication(); Banner banner = mock(Banner.class); application.setBanner(banner); @@ -113,7 +112,7 @@ public class BannerTests { } @Test - public void testDisableBannerInContext() { + void testDisableBannerInContext() { SpringApplication application = createSpringApplication(); application.setBannerMode(Mode.OFF); this.context = application.run(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java index 02203e8af3c..9654c8ec4fc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java @@ -16,9 +16,9 @@ package org.springframework.boot; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import sampleconfig.MyComponentInPackageWithoutDot; import org.springframework.boot.sampleconfig.MyComponent; @@ -32,29 +32,29 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class BeanDefinitionLoaderTests { +class BeanDefinitionLoaderTests { private StaticApplicationContext registry; - @Before + @BeforeEach public void setup() { this.registry = new StaticApplicationContext(); } - @After + @AfterEach public void cleanUp() { this.registry.close(); } @Test - public void loadClass() { + void loadClass() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test - public void loadXmlResource() { + void loadXmlResource() { ClassPathResource resource = new ClassPathResource("sample-beans.xml", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); @@ -63,7 +63,7 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadGroovyResource() { + void loadGroovyResource() { ClassPathResource resource = new ClassPathResource("sample-beans.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); @@ -72,7 +72,7 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadGroovyResourceWithNamespace() { + void loadGroovyResourceWithNamespace() { ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); assertThat(loader.load()).isEqualTo(1); @@ -81,21 +81,21 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadPackage() { + void loadPackage() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test - public void loadClassName() { + void loadClassName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test - public void loadResourceName() { + void loadResourceName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.xml"); assertThat(loader.load()).isEqualTo(1); @@ -103,7 +103,7 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadGroovyName() { + void loadGroovyName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.groovy"); assertThat(loader.load()).isEqualTo(1); @@ -111,14 +111,14 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadPackageName() { + void loadPackageName() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage().getName()); assertThat(loader.load()).isEqualTo(1); assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test - public void loadPackageNameWithoutDot() { + void loadPackageNameWithoutDot() { // See gh-6126 BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponentInPackageWithoutDot.class.getPackage().getName()); @@ -128,7 +128,7 @@ public class BeanDefinitionLoaderTests { } @Test - public void loadPackageAndClassDoesNotDoubleAdd() { + void loadPackageAndClassDoesNotDoubleAdd() { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage(), MyComponent.class); assertThat(loader.load()).isEqualTo(1); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 2eb536ec217..31b5b892ec5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -20,7 +20,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -30,31 +30,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class DefaultApplicationArgumentsTests { +class DefaultApplicationArgumentsTests { private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", "--debug", "spring", "boot" }; @Test - public void argumentsMustNotBeNull() { + void argumentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultApplicationArguments((String[]) null)) .withMessageContaining("Args must not be null"); } @Test - public void getArgs() { + void getArgs() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); assertThat(arguments.getSourceArgs()).isEqualTo(ARGS); } @Test - public void optionNames() { + void optionNames() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); Set expected = new HashSet<>(Arrays.asList("foo", "debug")); assertThat(arguments.getOptionNames()).isEqualTo(expected); } @Test - public void containsOption() { + void containsOption() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); assertThat(arguments.containsOption("foo")).isTrue(); assertThat(arguments.containsOption("debug")).isTrue(); @@ -62,7 +62,7 @@ public class DefaultApplicationArgumentsTests { } @Test - public void getOptionValues() { + void getOptionValues() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); assertThat(arguments.getOptionValues("foo")).isEqualTo(Arrays.asList("bar", "baz")); assertThat(arguments.getOptionValues("debug")).isEmpty(); @@ -70,13 +70,13 @@ public class DefaultApplicationArgumentsTests { } @Test - public void getNonOptionArgs() { + void getNonOptionArgs() { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); assertThat(arguments.getNonOptionArgs()).containsExactly("spring", "boot"); } @Test - public void getNoNonOptionArgs() { + void getNoNonOptionArgs() { ApplicationArguments arguments = new DefaultApplicationArguments("--debug"); assertThat(arguments.getNonOptionArgs()).isEmpty(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java index 9d08c2e2c99..a7f814080d2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java @@ -19,7 +19,7 @@ package org.springframework.boot; import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.convert.support.ConfigurableConversionService; import org.springframework.core.env.AbstractEnvironment; @@ -38,12 +38,12 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Madhura Bhave */ -public class EnvironmentConverterTests { +class EnvironmentConverterTests { private final EnvironmentConverter environmentConverter = new EnvironmentConverter(getClass().getClassLoader()); @Test - public void convertedEnvironmentHasSameActiveProfiles() { + void convertedEnvironmentHasSameActiveProfiles() { AbstractEnvironment originalEnvironment = new MockEnvironment(); originalEnvironment.setActiveProfiles("activeProfile1", "activeProfile2"); StandardEnvironment convertedEnvironment = this.environmentConverter @@ -52,7 +52,7 @@ public class EnvironmentConverterTests { } @Test - public void convertedEnvironmentHasSameConversionService() { + void convertedEnvironmentHasSameConversionService() { AbstractEnvironment originalEnvironment = new MockEnvironment(); ConfigurableConversionService conversionService = mock(ConfigurableConversionService.class); originalEnvironment.setConversionService(conversionService); @@ -62,7 +62,7 @@ public class EnvironmentConverterTests { } @Test - public void envClassSameShouldReturnEnvironmentUnconverted() { + void envClassSameShouldReturnEnvironmentUnconverted() { StandardEnvironment standardEnvironment = new StandardEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); @@ -70,7 +70,7 @@ public class EnvironmentConverterTests { } @Test - public void standardServletEnvironmentIsConverted() { + void standardServletEnvironmentIsConverted() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); @@ -78,7 +78,7 @@ public class EnvironmentConverterTests { } @Test - public void servletPropertySourcesAreNotCopiedOverIfNotWebEnvironment() { + void servletPropertySourcesAreNotCopiedOverIfNotWebEnvironment() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); @@ -93,7 +93,7 @@ public class EnvironmentConverterTests { } @Test - public void envClassSameShouldReturnEnvironmentUnconvertedEvenForWeb() { + void envClassSameShouldReturnEnvironmentUnconvertedEvenForWeb() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); @@ -101,7 +101,7 @@ public class EnvironmentConverterTests { } @Test - public void servletPropertySourcesArePresentWhenTypeToConvertIsWeb() { + void servletPropertySourcesArePresentWhenTypeToConvertIsWeb() { StandardEnvironment standardEnvironment = new StandardEnvironment(); StandardEnvironment convertedEnvironment = this.environmentConverter .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index 8dc1d96b85a..9a81e716265 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -19,7 +19,7 @@ package org.springframework.boot; import java.io.IOException; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -31,10 +31,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class ExitCodeGeneratorsTests { +class ExitCodeGeneratorsTests { @Test - public void addAllWhenGeneratorsIsNullShouldThrowException() { + void addAllWhenGeneratorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> { List generators = null; new ExitCodeGenerators().addAll(generators); @@ -42,18 +42,18 @@ public class ExitCodeGeneratorsTests { } @Test - public void addWhenGeneratorIsNullShouldThrowException() { + void addWhenGeneratorIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ExitCodeGenerators().add(null)) .withMessageContaining("Generator must not be null"); } @Test - public void getExitCodeWhenNoGeneratorsShouldReturnZero() { + void getExitCodeWhenNoGeneratorsShouldReturnZero() { assertThat(new ExitCodeGenerators().getExitCode()).isEqualTo(0); } @Test - public void getExitCodeWhenGeneratorThrowsShouldReturnOne() { + void getExitCodeWhenGeneratorThrowsShouldReturnOne() { ExitCodeGenerator generator = mock(ExitCodeGenerator.class); given(generator.getExitCode()).willThrow(new IllegalStateException()); ExitCodeGenerators generators = new ExitCodeGenerators(); @@ -62,7 +62,7 @@ public class ExitCodeGeneratorsTests { } @Test - public void getExitCodeWhenAllNegativeShouldReturnLowestValue() { + void getExitCodeWhenAllNegativeShouldReturnLowestValue() { ExitCodeGenerators generators = new ExitCodeGenerators(); generators.add(mockGenerator(-1)); generators.add(mockGenerator(-3)); @@ -71,7 +71,7 @@ public class ExitCodeGeneratorsTests { } @Test - public void getExitCodeWhenAllPositiveShouldReturnHighestValue() { + void getExitCodeWhenAllPositiveShouldReturnHighestValue() { ExitCodeGenerators generators = new ExitCodeGenerators(); generators.add(mockGenerator(1)); generators.add(mockGenerator(3)); @@ -80,7 +80,7 @@ public class ExitCodeGeneratorsTests { } @Test - public void getExitCodeWhenUsingExitCodeExceptionMapperShouldCallMapper() { + void getExitCodeWhenUsingExitCodeExceptionMapperShouldCallMapper() { ExitCodeGenerators generators = new ExitCodeGenerators(); Exception e = new IOException(); generators.add(e, mockMapper(IllegalStateException.class, 1)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java index 7665e556da1..7537175b793 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ImageBannerTests.java @@ -19,9 +19,9 @@ package org.springframework.boot; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiBackground; import org.springframework.boot.ansi.AnsiColor; @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Craig Burke * @author Phillip Webb */ -public class ImageBannerTests { +class ImageBannerTests { private static final char HIGH_LUMINANCE_CHARACTER = ' '; @@ -48,60 +48,60 @@ public class ImageBannerTests { private static final String INVERT_TRUE = "spring.banner.image.invert=true"; - @Before + @BeforeEach public void setup() { AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); } - @After + @AfterEach public void cleanup() { AnsiOutput.setEnabled(Enabled.DETECT); } @Test - public void printBannerShouldResetForegroundAndBackground() { + void printBannerShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif"); String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.DEFAULT); assertThat(banner).startsWith(expected); } @Test - public void printBannerWhenInvertedShouldResetForegroundAndBackground() { + void printBannerWhenInvertedShouldResetForegroundAndBackground() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); String expected = AnsiOutput.encode(AnsiColor.DEFAULT) + AnsiOutput.encode(AnsiBackground.BLACK); assertThat(banner).startsWith(expected); } @Test - public void printBannerShouldPrintWhiteAsBrightWhiteHighLuminance() { + void printBannerShouldPrintWhiteAsBrightWhiteHighLuminance() { String banner = printBanner("black-and-white.gif"); String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + HIGH_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test - public void printBannerWhenInvertedShouldPrintWhiteAsBrightWhiteLowLuminance() { + void printBannerWhenInvertedShouldPrintWhiteAsBrightWhiteLowLuminance() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); String expected = AnsiOutput.encode(AnsiColor.BRIGHT_WHITE) + LOW_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test - public void printBannerShouldPrintBlackAsBlackLowLuminance() { + void printBannerShouldPrintBlackAsBlackLowLuminance() { String banner = printBanner("black-and-white.gif"); String expected = AnsiOutput.encode(AnsiColor.BLACK) + LOW_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test - public void printBannerWhenInvertedShouldPrintBlackAsBlackHighLuminance() { + void printBannerWhenInvertedShouldPrintBlackAsBlackHighLuminance() { String banner = printBanner("black-and-white.gif", INVERT_TRUE); String expected = AnsiOutput.encode(AnsiColor.BLACK) + HIGH_LUMINANCE_CHARACTER; assertThat(banner).contains(expected); } @Test - public void printBannerWhenShouldPrintAllColors() { + void printBannerWhenShouldPrintAllColors() { String banner = printBanner("colors.gif"); for (AnsiColor color : AnsiColor.values()) { if (color != AnsiColor.DEFAULT) { @@ -111,26 +111,26 @@ public class ImageBannerTests { } @Test - public void printBannerShouldRenderGradient() { + void printBannerShouldRenderGradient() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("gradient.gif", "spring.banner.image.width=10", "spring.banner.image.margin=0"); assertThat(banner).contains("@#8&o:*. "); } @Test - public void printBannerShouldCalculateHeight() { + void printBannerShouldCalculateHeight() { String banner = printBanner("large.gif", "spring.banner.image.width=20"); assertThat(getBannerHeight(banner)).isEqualTo(10); } @Test - public void printBannerWhenHasHeightPropertyShouldSetHeight() { + void printBannerWhenHasHeightPropertyShouldSetHeight() { String banner = printBanner("large.gif", "spring.banner.image.width=20", "spring.banner.image.height=30"); assertThat(getBannerHeight(banner)).isEqualTo(30); } @Test - public void printBannerShouldCapWidthAndCalculateHeight() { + void printBannerShouldCapWidthAndCalculateHeight() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("large.gif", "spring.banner.image.margin=0"); assertThat(getBannerWidth(banner)).isEqualTo(76); @@ -138,7 +138,7 @@ public class ImageBannerTests { } @Test - public void printBannerShouldPrintMargin() { + void printBannerShouldPrintMargin() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("large.gif"); String[] lines = banner.split(System.lineSeparator()); @@ -148,7 +148,7 @@ public class ImageBannerTests { } @Test - public void printBannerWhenHasMarginPropertyShouldPrintSizedMargin() { + void printBannerWhenHasMarginPropertyShouldPrintSizedMargin() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("large.gif", "spring.banner.image.margin=4"); String[] lines = banner.split(System.lineSeparator()); @@ -158,7 +158,7 @@ public class ImageBannerTests { } @Test - public void printBannerWhenAnimatesShouldPrintAllFrames() { + void printBannerWhenAnimatesShouldPrintAllFrames() { AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner("animated.gif"); String[] lines = banner.split(System.lineSeparator()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java index 1161b3b4d48..0f689a39649 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java @@ -16,8 +16,8 @@ package org.springframework.boot; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; @@ -33,11 +33,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class OverrideSourcesTests { +class OverrideSourcesTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -45,14 +45,14 @@ public class OverrideSourcesTests { } @Test - public void beanInjectedToMainConfiguration() { + void beanInjectedToMainConfiguration() { this.context = SpringApplication.run(new Class[] { MainConfiguration.class }, new String[] { "--spring.main.web-application-type=none" }); assertThat(this.context.getBean(Service.class).bean.name).isEqualTo("foo"); } @Test - public void primaryBeanInjectedProvingSourcesNotOverridden() { + void primaryBeanInjectedProvingSourcesNotOverridden() { this.context = SpringApplication.run(new Class[] { MainConfiguration.class, TestConfiguration.class }, new String[] { "--spring.main.web-application-type=none", "--spring.main.allow-bean-definition-overriding=true", diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java index 2bd7ff65313..be28bfee932 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ReproTests.java @@ -16,8 +16,8 @@ package org.springframework.boot; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; @@ -31,11 +31,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Dave Syer */ -public class ReproTests { +class ReproTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -43,7 +43,7 @@ public class ReproTests { } @Test - public void enableProfileViaApplicationProperties() { + void enableProfileViaApplicationProperties() { // gh-308 SpringApplication application = new SpringApplication(Config.class); @@ -55,7 +55,7 @@ public class ReproTests { } @Test - public void activeProfilesWithYamlAndCommandLine() { + void activeProfilesWithYamlAndCommandLine() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -65,7 +65,7 @@ public class ReproTests { } @Test - public void activeProfilesWithYamlOnly() { + void activeProfilesWithYamlOnly() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -75,7 +75,7 @@ public class ReproTests { } @Test - public void orderActiveProfilesWithYamlOnly() { + void orderActiveProfilesWithYamlOnly() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -85,7 +85,7 @@ public class ReproTests { } @Test - public void commandLineBeatsProfilesWithYaml() { + void commandLineBeatsProfilesWithYaml() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -95,7 +95,7 @@ public class ReproTests { } @Test - public void orderProfilesWithYaml() { + void orderProfilesWithYaml() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -105,7 +105,7 @@ public class ReproTests { } @Test - public void reverseOrderOfProfilesWithYaml() { + void reverseOrderOfProfilesWithYaml() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -115,7 +115,7 @@ public class ReproTests { } @Test - public void activeProfilesWithYamlAndCommandLineAndNoOverride() { + void activeProfilesWithYamlAndCommandLineAndNoOverride() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -125,7 +125,7 @@ public class ReproTests { } @Test - public void activeProfilesWithYamlOnlyAndNoOverride() { + void activeProfilesWithYamlOnlyAndNoOverride() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -135,7 +135,7 @@ public class ReproTests { } @Test - public void commandLineBeatsProfilesWithYamlAndNoOverride() { + void commandLineBeatsProfilesWithYamlAndNoOverride() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -145,7 +145,7 @@ public class ReproTests { } @Test - public void orderProfilesWithYamlAndNoOverride() { + void orderProfilesWithYamlAndNoOverride() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -155,7 +155,7 @@ public class ReproTests { } @Test - public void reverseOrderOfProfilesWithYamlAndNoOverride() { + void reverseOrderOfProfilesWithYamlAndNoOverride() { // gh-322, gh-342 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java index b90c2f930d6..c0cbd39a88f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java @@ -21,8 +21,8 @@ import java.io.PrintStream; import java.util.Collections; import java.util.Map; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiOutput.Enabled; @@ -40,15 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Vedran Pavic */ -public class ResourceBannerTests { +class ResourceBannerTests { - @After + @AfterEach public void reset() { AnsiOutput.setEnabled(Enabled.DETECT); } @Test - public void renderVersions() { + void renderVersions() { Resource resource = new ByteArrayResource( "banner ${a} ${spring-boot.version} ${application.version}".getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); @@ -56,7 +56,7 @@ public class ResourceBannerTests { } @Test - public void renderWithoutVersions() { + void renderWithoutVersions() { Resource resource = new ByteArrayResource( "banner ${a} ${spring-boot.version} ${application.version}".getBytes()); String banner = printBanner(resource, null, null, null); @@ -64,7 +64,7 @@ public class ResourceBannerTests { } @Test - public void renderFormattedVersions() { + void renderFormattedVersions() { Resource resource = new ByteArrayResource( "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); @@ -72,7 +72,7 @@ public class ResourceBannerTests { } @Test - public void renderWithoutFormattedVersions() { + void renderWithoutFormattedVersions() { Resource resource = new ByteArrayResource( "banner ${a}${spring-boot.formatted-version}${application.formatted-version}".getBytes()); String banner = printBanner(resource, null, null, null); @@ -80,7 +80,7 @@ public class ResourceBannerTests { } @Test - public void renderWithColors() { + void renderWithColors() { Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); String banner = printBanner(resource, null, null, null); @@ -88,7 +88,7 @@ public class ResourceBannerTests { } @Test - public void renderWithColorsButDisabled() { + void renderWithColorsButDisabled() { Resource resource = new ByteArrayResource("${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner(resource, null, null, null); @@ -96,14 +96,14 @@ public class ResourceBannerTests { } @Test - public void renderWithTitle() { + void renderWithTitle() { Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, "title"); assertThat(banner).startsWith("banner title 1"); } @Test - public void renderWithoutTitle() { + void renderWithoutTitle() { Resource resource = new ByteArrayResource("banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, null); assertThat(banner).startsWith("banner 1"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java index 07f58c2bcf4..9b7dde111ef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java @@ -20,10 +20,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; @@ -37,40 +38,38 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Dave Syer */ @Configuration(proxyBeanMethods = false) -public class SimpleMainTests { - - @Rule - public OutputCapture outputCapture = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class SimpleMainTests { private static final String SPRING_STARTUP = "Started SpringApplication in"; @Test - public void emptyApplicationContext() throws Exception { + void emptyApplicationContext() throws Exception { assertThatIllegalArgumentException().isThrownBy(() -> SpringApplication.main(getArgs())); } @Test - public void basePackageScan() throws Exception { + void basePackageScan(CapturedOutput capturedOutput) throws Exception { SpringApplication.main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); - assertThat(getOutput()).contains(SPRING_STARTUP); + assertThat(capturedOutput).contains(SPRING_STARTUP); } @Test - public void configClassContext() throws Exception { + void configClassContext(CapturedOutput capturedOutput) throws Exception { SpringApplication.main(getArgs(getClass().getName())); - assertThat(getOutput()).contains(SPRING_STARTUP); + assertThat(capturedOutput).contains(SPRING_STARTUP); } @Test - public void xmlContext() throws Exception { + void xmlContext(CapturedOutput capturedOutput) throws Exception { SpringApplication.main(getArgs("org/springframework/boot/sample-beans.xml")); - assertThat(getOutput()).contains(SPRING_STARTUP); + assertThat(capturedOutput).contains(SPRING_STARTUP); } @Test - public void mixedContext() throws Exception { + void mixedContext(CapturedOutput capturedOutput) throws Exception { SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml")); - assertThat(getOutput()).contains(SPRING_STARTUP); + assertThat(capturedOutput).contains(SPRING_STARTUP); } private String[] getArgs(String... args) { @@ -82,8 +81,4 @@ public class SimpleMainTests { return StringUtils.toStringArray(list); } - private String getOutput() { - return this.outputCapture.toString(); - } - } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 70461eeec23..98b7ed11c64 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -28,10 +28,10 @@ import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; import org.assertj.core.api.Condition; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.InOrder; @@ -55,7 +55,8 @@ import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.boot.context.event.ApplicationStartingEvent; import org.springframework.boot.context.event.SpringApplicationEvent; import org.springframework.boot.convert.ApplicationConversionService; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebApplicationContext; @@ -128,13 +129,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * @author Brian Clozel * @author Artsiom Yudovin */ -public class SpringApplicationTests { +@ExtendWith(OutputCaptureExtension.class) +class SpringApplicationTests { private String headlessProperty; - @Rule - public OutputCapture output = new OutputCapture(); - private ConfigurableApplicationContext context; private Environment getEnvironment() { @@ -144,13 +143,13 @@ public class SpringApplicationTests { throw new IllegalStateException("Could not obtain Environment"); } - @Before + @BeforeEach public void storeAndClearHeadlessProperty() { this.headlessProperty = System.getProperty("java.awt.headless"); System.clearProperty("java.awt.headless"); } - @After + @AfterEach public void reinstateHeadlessProperty() { if (this.headlessProperty == null) { System.clearProperty("java.awt.headless"); @@ -160,7 +159,7 @@ public class SpringApplicationTests { } } - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -170,43 +169,43 @@ public class SpringApplicationTests { } @Test - public void sourcesMustNotBeNull() { + void sourcesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication((Class[]) null).run()) .withMessageContaining("PrimarySources must not be null"); } @Test - public void sourcesMustNotBeEmpty() { + void sourcesMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication().run()) .withMessageContaining("Sources must not be empty"); } @Test - public void sourcesMustBeAccessible() { + void sourcesMustBeAccessible() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) .withMessageContaining("No visible constructors"); } @Test - public void customBanner() { + void customBanner(CapturedOutput capturedOutput) { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.banner.location=classpath:test-banner.txt"); - assertThat(this.output.toString()).startsWith("Running a Test!"); + assertThat(capturedOutput).startsWith("Running a Test!"); } @Test - public void customBannerWithProperties() { + void customBannerWithProperties(CapturedOutput capturedOutput) { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.banner.location=classpath:test-banner-with-placeholder.txt", "--test.property=123456"); - assertThat(this.output.toString()).containsPattern("Running a Test!\\s+123456"); + assertThat(capturedOutput).containsPattern("Running a Test!\\s+123456"); } @Test - public void imageBannerAndTextBanner() { + void imageBannerAndTextBanner(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); MockResourceLoader resourceLoader = new MockResourceLoader(); resourceLoader.addResource("banner.gif", "black-and-white.gif"); @@ -214,47 +213,47 @@ public class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); application.setResourceLoader(resourceLoader); application.run(); - assertThat(this.output.toString()).contains("@@@@").contains("Foo Bar"); + assertThat(capturedOutput).contains("@@@@").contains("Foo Bar"); } @Test - public void imageBannerLoads() { + void imageBannerLoads(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); MockResourceLoader resourceLoader = new MockResourceLoader(); resourceLoader.addResource("banner.gif", "black-and-white.gif"); application.setWebApplicationType(WebApplicationType.NONE); application.setResourceLoader(resourceLoader); application.run(); - assertThat(this.output.toString()).contains("@@@@@@"); + assertThat(capturedOutput).contains("@@@@@@"); } @Test - public void logsNoActiveProfiles() { + void logsNoActiveProfiles(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - assertThat(this.output.toString()).contains("No active profile set, falling back to default profiles: default"); + assertThat(capturedOutput).contains("No active profile set, falling back to default profiles: default"); } @Test - public void logsActiveProfiles() { + void logsActiveProfiles(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.active=myprofiles"); - assertThat(this.output.toString()).contains("The following profiles are active: myprofile"); + assertThat(capturedOutput).contains("The following profiles are active: myprofile"); } @Test - public void enableBannerInLogViaProperty() { + void enableBannerInLogViaProperty(CapturedOutput capturedOutput) { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.main.banner-mode=log"); verify(application, atLeastOnce()).setBannerMode(Banner.Mode.LOG); - assertThat(this.output.toString()).contains("o.s.b.SpringApplication"); + assertThat(capturedOutput).contains("o.s.b.SpringApplication"); } @Test - public void setIgnoreBeanInfoPropertyByDefault() { + void setIgnoreBeanInfoPropertyByDefault(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -263,7 +262,7 @@ public class SpringApplicationTests { } @Test - public void disableIgnoreBeanInfoProperty() { + void disableIgnoreBeanInfoProperty() { System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, "false"); SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -273,7 +272,7 @@ public class SpringApplicationTests { } @Test - public void triggersConfigFileApplicationListenerBeforeBinding() { + void triggersConfigFileApplicationListenerBeforeBinding() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.config.name=bindtoapplication"); @@ -281,7 +280,7 @@ public class SpringApplicationTests { } @Test - public void bindsSystemPropertyToSpringApplication() { + void bindsSystemPropertyToSpringApplication() { System.setProperty("spring.main.banner-mode", "off"); SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -290,7 +289,7 @@ public class SpringApplicationTests { } @Test - public void customId() { + void customId() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.application.name=foo"); @@ -298,7 +297,7 @@ public class SpringApplicationTests { } @Test - public void specificApplicationContextClass() { + void specificApplicationContextClass() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(StaticApplicationContext.class); this.context = application.run(); @@ -306,28 +305,28 @@ public class SpringApplicationTests { } @Test - public void specificWebApplicationContextClassDetectWebApplicationType() { + void specificWebApplicationContextClassDetectWebApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(AnnotationConfigServletWebApplicationContext.class); assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.SERVLET); } @Test - public void specificReactiveApplicationContextClassDetectReactiveApplicationType() { + void specificReactiveApplicationContextClassDetectReactiveApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(AnnotationConfigReactiveWebApplicationContext.class); assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.REACTIVE); } @Test - public void nonWebNorReactiveApplicationContextClassDetectNoneApplicationType() { + void nonWebNorReactiveApplicationContextClassDetectNoneApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(StaticApplicationContext.class); assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.NONE); } @Test - public void specificApplicationContextInitializer() { + void specificApplicationContextInitializer() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); @@ -340,7 +339,7 @@ public class SpringApplicationTests { } @Test - public void applicationRunningEventListener() { + void applicationRunningEventListener() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); @@ -358,7 +357,7 @@ public class SpringApplicationTests { } @Test - public void contextRefreshedEventListener() { + void contextRefreshedEventListener() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); @@ -379,7 +378,7 @@ public class SpringApplicationTests { @Test @SuppressWarnings("unchecked") - public void eventsArePublishedInExpectedOrder() { + void eventsArePublishedInExpectedOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ApplicationListener listener = mock(ApplicationListener.class); @@ -397,7 +396,7 @@ public class SpringApplicationTests { } @Test - public void defaultApplicationContext() { + void defaultApplicationContext() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -405,7 +404,7 @@ public class SpringApplicationTests { } @Test - public void defaultApplicationContextForWeb() { + void defaultApplicationContextForWeb() { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.SERVLET); this.context = application.run(); @@ -413,7 +412,7 @@ public class SpringApplicationTests { } @Test - public void defaultApplicationContextForReactiveWeb() { + void defaultApplicationContextForReactiveWeb() { SpringApplication application = new SpringApplication(ExampleReactiveWebConfig.class); application.setWebApplicationType(WebApplicationType.REACTIVE); this.context = application.run(); @@ -421,7 +420,7 @@ public class SpringApplicationTests { } @Test - public void environmentForWeb() { + void environmentForWeb() { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.SERVLET); this.context = application.run(); @@ -429,7 +428,7 @@ public class SpringApplicationTests { } @Test - public void environmentForReactiveWeb() { + void environmentForReactiveWeb() { SpringApplication application = new SpringApplication(ExampleReactiveWebConfig.class); application.setWebApplicationType(WebApplicationType.REACTIVE); this.context = application.run(); @@ -437,7 +436,7 @@ public class SpringApplicationTests { } @Test - public void customEnvironment() { + void customEnvironment() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); @@ -447,7 +446,7 @@ public class SpringApplicationTests { } @Test - public void customResourceLoader() { + void customResourceLoader() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ResourceLoader resourceLoader = new DefaultResourceLoader(); @@ -457,7 +456,7 @@ public class SpringApplicationTests { } @Test - public void customResourceLoaderFromConstructor() { + void customResourceLoaderFromConstructor() { ResourceLoader resourceLoader = new DefaultResourceLoader(); TestSpringApplication application = new TestSpringApplication(resourceLoader, ExampleWebConfig.class); this.context = application.run(); @@ -465,7 +464,7 @@ public class SpringApplicationTests { } @Test - public void customBeanNameGenerator() { + void customBeanNameGenerator() { TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); application.setBeanNameGenerator(beanNameGenerator); @@ -476,7 +475,7 @@ public class SpringApplicationTests { } @Test - public void customBeanNameGeneratorWithNonWebApplication() { + void customBeanNameGeneratorWithNonWebApplication() { TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class); application.setWebApplicationType(WebApplicationType.NONE); BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); @@ -488,7 +487,7 @@ public class SpringApplicationTests { } @Test - public void commandLinePropertySource() { + void commandLinePropertySource() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); @@ -498,7 +497,7 @@ public class SpringApplicationTests { } @Test - public void commandLinePropertySourceEnhancesEnvironment() { + void commandLinePropertySourceEnhancesEnvironment() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); @@ -521,7 +520,7 @@ public class SpringApplicationTests { } @Test - public void propertiesFileEnhancesEnvironment() { + void propertiesFileEnhancesEnvironment() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); @@ -531,7 +530,7 @@ public class SpringApplicationTests { } @Test - public void addProfiles() { + void addProfiles() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setAdditionalProfiles("foo"); @@ -542,7 +541,7 @@ public class SpringApplicationTests { } @Test - public void addProfilesOrder() { + void addProfilesOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setAdditionalProfiles("foo"); @@ -554,7 +553,7 @@ public class SpringApplicationTests { } @Test - public void addProfilesOrderWithProperties() { + void addProfilesOrderWithProperties() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setAdditionalProfiles("other"); @@ -566,7 +565,7 @@ public class SpringApplicationTests { } @Test - public void emptyCommandLinePropertySourceNotAdded() { + void emptyCommandLinePropertySourceNotAdded() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); @@ -576,7 +575,7 @@ public class SpringApplicationTests { } @Test - public void disableCommandLinePropertySource() { + void disableCommandLinePropertySource() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setAddCommandLineProperties(false); @@ -587,7 +586,7 @@ public class SpringApplicationTests { } @Test - public void contextUsesApplicationConversionService() { + void contextUsesApplicationConversionService() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -598,7 +597,7 @@ public class SpringApplicationTests { } @Test - public void contextWhenHasAddConversionServiceFalseUsesRegularConversionService() { + void contextWhenHasAddConversionServiceFalseUsesRegularConversionService() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setAddConversionService(false); @@ -609,7 +608,7 @@ public class SpringApplicationTests { } @Test - public void runCommandLineRunnersAndApplicationRunners() { + void runCommandLineRunnersAndApplicationRunners() { SpringApplication application = new SpringApplication(CommandLineRunConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("arg"); @@ -620,18 +619,19 @@ public class SpringApplicationTests { @Test @SuppressWarnings("unchecked") - public void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished() throws Exception { + void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished(CapturedOutput capturedOutput) + throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); ApplicationRunner applicationRunner = mock(ApplicationRunner.class); CommandLineRunner commandLineRunner = mock(CommandLineRunner.class); application.addInitializers((context) -> { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); beanFactory.registerSingleton("commandLineRunner", (CommandLineRunner) (args) -> { - assertThat(SpringApplicationTests.this.output.toString()).contains("Started"); + assertThat(capturedOutput).contains("Started"); commandLineRunner.run(args); }); beanFactory.registerSingleton("applicationRunner", (ApplicationRunner) (args) -> { - assertThat(SpringApplicationTests.this.output.toString()).contains("Started"); + assertThat(capturedOutput).contains("Started"); applicationRunner.run(args); }); }); @@ -650,7 +650,7 @@ public class SpringApplicationTests { } @Test - public void applicationRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { + void applicationRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") @@ -667,7 +667,7 @@ public class SpringApplicationTests { } @Test - public void commandLineRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { + void commandLineRunnerFailureCausesApplicationFailedEventToBePublished() throws Exception { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") @@ -684,7 +684,7 @@ public class SpringApplicationTests { } @Test - public void failureInReadyEventListenerDoesNotCausePublicationOfFailedEvent() { + void failureInReadyEventListenerDoesNotCausePublicationOfFailedEvent() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @SuppressWarnings("unchecked") @@ -698,7 +698,7 @@ public class SpringApplicationTests { } @Test - public void failureInReadyEventListenerCloseApplicationContext() { + void failureInReadyEventListenerCloseApplicationContext(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); ExitCodeListener exitCodeListener = new ExitCodeListener(); @@ -712,11 +712,11 @@ public class SpringApplicationTests { verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); assertThat(exitCodeListener.getExitCode()).isEqualTo(11); - assertThat(this.output.toString()).contains("Application run failed"); + assertThat(capturedOutput).contains("Application run failed"); } @Test - public void loadSources() { + void loadSources() { Class[] sources = { ExampleConfig.class, TestCommandLineRunner.class }; TestSpringApplication application = new TestSpringApplication(sources); application.getSources().add("a"); @@ -728,7 +728,7 @@ public class SpringApplicationTests { } @Test - public void wildcardSources() { + void wildcardSources() { TestSpringApplication application = new TestSpringApplication(); application.getSources().add("classpath:org/springframework/boot/sample-${sample.app.test.prop}.xml"); application.setWebApplicationType(WebApplicationType.NONE); @@ -736,19 +736,19 @@ public class SpringApplicationTests { } @Test - public void run() { + void run() { this.context = SpringApplication.run(ExampleWebConfig.class); assertThat(this.context).isNotNull(); } @Test - public void runComponents() { + void runComponents() { this.context = SpringApplication.run(new Class[] { ExampleWebConfig.class, Object.class }, new String[0]); assertThat(this.context).isNotNull(); } @Test - public void exit() { + void exit() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -757,7 +757,7 @@ public class SpringApplicationTests { } @Test - public void exitWithExplicitCode() { + void exitWithExplicitCode() { SpringApplication application = new SpringApplication(ExampleConfig.class); ExitCodeListener listener = new ExitCodeListener(); application.addListeners(listener); @@ -769,7 +769,7 @@ public class SpringApplicationTests { } @Test - public void exitWithExplicitCodeFromException() { + void exitWithExplicitCodeFromException() { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); SpringApplication application = new SpringApplication(ExitCodeCommandLineRunConfig.class) { @@ -788,7 +788,7 @@ public class SpringApplicationTests { } @Test - public void exitWithExplicitCodeFromMappedException() { + void exitWithExplicitCodeFromMappedException() { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); SpringApplication application = new SpringApplication(MappedExitCodeCommandLineRunConfig.class) { @@ -807,7 +807,7 @@ public class SpringApplicationTests { } @Test - public void exceptionFromRefreshIsHandledGracefully() { + void exceptionFromRefreshIsHandledGracefully(CapturedOutput capturedOutput) { final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); SpringApplication application = new SpringApplication(RefreshFailureConfig.class) { @@ -824,11 +824,11 @@ public class SpringApplicationTests { ArgumentCaptor exceptionCaptor = ArgumentCaptor.forClass(RuntimeException.class); verify(handler).registerLoggedException(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).hasCauseInstanceOf(RefreshFailureException.class); - assertThat(this.output.toString()).doesNotContain("NullPointerException"); + assertThat(capturedOutput).doesNotContain("NullPointerException"); } @Test - public void defaultCommandLineArgs() { + void defaultCommandLineArgs() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setDefaultProperties( StringUtils.splitArrayElementsIntoProperties(new String[] { "baz=", "bar=spam" }, "=")); @@ -840,7 +840,7 @@ public class SpringApplicationTests { } @Test - public void commandLineArgsApplyToSpringApplication() { + void commandLineArgsApplyToSpringApplication() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.main.banner-mode=OFF"); @@ -848,7 +848,7 @@ public class SpringApplicationTests { } @Test - public void registerShutdownHook() { + void registerShutdownHook() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); this.context = application.run(); @@ -857,7 +857,7 @@ public class SpringApplicationTests { } @Test - public void registerListener() { + void registerListener() { SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); Set events = new LinkedHashSet<>(); @@ -869,7 +869,7 @@ public class SpringApplicationTests { } @Test - public void registerListenerWithCustomMulticaster() { + void registerListenerWithCustomMulticaster() { SpringApplication application = new SpringApplication(ExampleConfig.class, ListenerConfig.class, Multicaster.class); application.setApplicationContextClass(SpyApplicationContext.class); @@ -900,7 +900,7 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test - public void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { + void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); application.addListeners(listener); @@ -911,7 +911,7 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test - public void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshAfterListenerRegistration() { + void applicationListenerFromApplicationIsCalledWhenContextFailsRefreshAfterListenerRegistration() { ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -923,7 +923,7 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test - public void applicationListenerFromContextIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { + void applicationListenerFromContextIsCalledWhenContextFailsRefreshBeforeListenerRegistration() { final ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); application.addInitializers((applicationContext) -> applicationContext.addApplicationListener(listener)); @@ -933,7 +933,7 @@ public class SpringApplicationTests { @SuppressWarnings("unchecked") @Test - public void applicationListenerFromContextIsCalledWhenContextFailsRefreshAfterListenerRegistration() { + void applicationListenerFromContextIsCalledWhenContextFailsRefreshAfterListenerRegistration() { ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -943,7 +943,7 @@ public class SpringApplicationTests { } @Test - public void registerShutdownHookOff() { + void registerShutdownHookOff() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); application.setRegisterShutdownHook(false); @@ -953,7 +953,7 @@ public class SpringApplicationTests { } @Test - public void headless() { + void headless() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -961,7 +961,7 @@ public class SpringApplicationTests { } @Test - public void headlessFalse() { + void headlessFalse() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.setHeadless(false); @@ -970,7 +970,7 @@ public class SpringApplicationTests { } @Test - public void headlessSystemPropertyTakesPrecedence() { + void headlessSystemPropertyTakesPrecedence() { System.setProperty("java.awt.headless", "false"); TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -979,7 +979,7 @@ public class SpringApplicationTests { } @Test - public void getApplicationArgumentsBean() { + void getApplicationArgumentsBean() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--debug", "spring", "boot"); @@ -989,7 +989,7 @@ public class SpringApplicationTests { } @Test - public void webApplicationSwitchedOffInListener() { + void webApplicationSwitchedOffInListener() { TestSpringApplication application = new TestSpringApplication(ExampleConfig.class); application.addListeners((ApplicationListener) (event) -> { assertThat(event.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); @@ -1006,7 +1006,7 @@ public class SpringApplicationTests { } @Test - public void nonWebApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { + void nonWebApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleConfig.class) .run("--spring.main.web-application-type=none"); assertThat(context).isNotInstanceOfAny(WebApplicationContext.class, ReactiveWebApplicationContext.class); @@ -1014,7 +1014,7 @@ public class SpringApplicationTests { } @Test - public void webApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { + void webApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleWebConfig.class) .run("--spring.main.web-application-type=servlet"); assertThat(context).isInstanceOf(WebApplicationContext.class); @@ -1022,7 +1022,7 @@ public class SpringApplicationTests { } @Test - public void reactiveApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { + void reactiveApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) .run("--spring.main.web-application-type=reactive"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); @@ -1030,7 +1030,7 @@ public class SpringApplicationTests { } @Test - public void environmentIsConvertedIfTypeDoesNotMatch() { + void environmentIsConvertedIfTypeDoesNotMatch() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) .run("--spring.profiles.active=withwebapplicationtype"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); @@ -1038,7 +1038,7 @@ public class SpringApplicationTests { } @Test - public void failureResultsInSingleStackTrace() throws Exception { + void failureResultsInSingleStackTrace(CapturedOutput capturedOutput) throws Exception { ThreadGroup group = new ThreadGroup("main"); Thread thread = new Thread(group, "main") { @Override @@ -1050,39 +1050,37 @@ public class SpringApplicationTests { }; thread.start(); thread.join(6000); - int occurrences = StringUtils.countOccurrencesOf(this.output.toString(), - "Caused by: java.lang.RuntimeException: ExpectedError"); - assertThat(occurrences).as("Expected single stacktrace").isEqualTo(1); + assertThat(capturedOutput).containsOnlyOnce("Caused by: java.lang.RuntimeException: ExpectedError"); } @Test - public void beanDefinitionOverridingIsDisabledByDefault() { + void beanDefinitionOverridingIsDisabledByDefault() { assertThatExceptionOfType(BeanDefinitionOverrideException.class) .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); } @Test - public void beanDefinitionOverridingCanBeEnabled() { + void beanDefinitionOverridingCanBeEnabled() { assertThat(new SpringApplication(ExampleConfig.class, OverrideConfig.class) .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") .getBean("someBean")).isEqualTo("override"); } @Test - public void lazyInitializationIsDisabledByDefault() { + void lazyInitializationIsDisabledByDefault() { assertThat(new SpringApplication(LazyInitializationConfig.class).run("--spring.main.web-application-type=none") .getBean(AtomicInteger.class)).hasValue(1); } @Test - public void lazyInitializationCanBeEnabled() { + void lazyInitializationCanBeEnabled() { assertThat(new SpringApplication(LazyInitializationConfig.class) .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") .getBean(AtomicInteger.class)).hasValue(0); } @Test - public void lazyInitializationShouldNotApplyToBeansThatAreExplicitlyNotLazy() { + void lazyInitializationShouldNotApplyToBeansThatAreExplicitlyNotLazy() { assertThat(new SpringApplication(NotLazyInitializationConfig.class) .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") .getBean(AtomicInteger.class)).hasValue(1); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java index e6c42a92978..087ba479ff9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java @@ -16,7 +16,7 @@ package org.springframework.boot; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotatedElementUtils; @@ -29,17 +29,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SpringBootConfigurationTests { +class SpringBootConfigurationTests { @Test - public void proxyBeanMethodsIsEnabledByDefault() { + void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(true); } @Test - public void proxyBeanMethodsCanBeDisabled() { + void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); assertThat(attributes.get("proxyBeanMethods")).isEqualTo(false); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java index d7b9aefa122..07823ca7b80 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootExceptionHandlerTests.java @@ -19,7 +19,7 @@ package org.springframework.boot; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.InvocationTargetException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -31,14 +31,14 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Henri Tremblay * @author Andy Wilkinson */ -public class SpringBootExceptionHandlerTests { +class SpringBootExceptionHandlerTests { private final UncaughtExceptionHandler parent = mock(UncaughtExceptionHandler.class); private final SpringBootExceptionHandler handler = new SpringBootExceptionHandler(this.parent); @Test - public void uncaughtExceptionDoesNotForwardLoggedErrorToParent() { + void uncaughtExceptionDoesNotForwardLoggedErrorToParent() { Thread thread = Thread.currentThread(); Exception ex = new Exception(); this.handler.registerLoggedException(ex); @@ -47,7 +47,7 @@ public class SpringBootExceptionHandlerTests { } @Test - public void uncaughtExceptionForwardsLogConfigurationErrorToParent() { + void uncaughtExceptionForwardsLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); Exception ex = new Exception("[stuff] Logback configuration error detected [stuff]"); this.handler.registerLoggedException(ex); @@ -56,7 +56,7 @@ public class SpringBootExceptionHandlerTests { } @Test - public void uncaughtExceptionForwardsWrappedLogConfigurationErrorToParent() { + void uncaughtExceptionForwardsWrappedLogConfigurationErrorToParent() { Thread thread = Thread.currentThread(); Exception ex = new InvocationTargetException( new Exception("[stuff] Logback configuration error detected [stuff]", new Exception())); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java index 228130f8cfc..bd84ec87b23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java @@ -17,7 +17,7 @@ package org.springframework.boot; import org.apache.commons.logging.Log; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import static org.assertj.core.api.Assertions.assertThat; @@ -31,12 +31,12 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Andy Wilkinson */ -public class StartUpLoggerTests { +class StartUpLoggerTests { private final Log log = mock(Log.class); @Test - public void sourceClassIncluded() { + void sourceClassIncluded() { given(this.log.isInfoEnabled()).willReturn(true); new StartupInfoLogger(getClass()).logStarting(this.log); ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index bf508e3c330..7ed890a2413 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -23,9 +23,9 @@ import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -46,7 +46,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Andy Wilkinson */ -public class SpringApplicationAdminMXBeanRegistrarTests { +class SpringApplicationAdminMXBeanRegistrarTests { private static final String OBJECT_NAME = "org.springframework.boot:type=Test,name=SpringApplication"; @@ -54,12 +54,12 @@ public class SpringApplicationAdminMXBeanRegistrarTests { private ConfigurableApplicationContext context; - @Before + @BeforeEach public void setup() { this.mBeanServer = ManagementFactory.getPlatformMBeanServer(); } - @After + @AfterEach public void closeContext() { if (this.context != null) { this.context.close(); @@ -67,7 +67,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { } @Test - public void validateReadyFlag() { + void validateReadyFlag() { final ObjectName objectName = createObjectName(OBJECT_NAME); SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -84,7 +84,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { } @Test - public void eventsFromOtherContextsAreIgnored() throws MalformedObjectNameException { + void eventsFromOtherContextsAreIgnored() throws MalformedObjectNameException { SpringApplicationAdminMXBeanRegistrar registrar = new SpringApplicationAdminMXBeanRegistrar(OBJECT_NAME); ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); registrar.setApplicationContext(context); @@ -100,7 +100,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { } @Test - public void environmentIsExposed() { + void environmentIsExposed() { final ObjectName objectName = createObjectName(OBJECT_NAME); SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -112,7 +112,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { } @Test - public void shutdownApp() throws InstanceNotFoundException { + void shutdownApp() throws InstanceNotFoundException { final ObjectName objectName = createObjectName(OBJECT_NAME); SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiColorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiColorsTests.java index 44a2c8dce8e..37febd393ca 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiColorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiColorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.ansi; import java.awt.Color; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AnsiColorsTests { +class AnsiColorsTests { @Test - public void getClosestWhenExactMatchShouldReturnAnsiColor() { + void getClosestWhenExactMatchShouldReturnAnsiColor() { assertThat(getClosest(0x000000)).isEqualTo(AnsiColor.BLACK); assertThat(getClosest(0xAA0000)).isEqualTo(AnsiColor.RED); assertThat(getClosest(0x00AA00)).isEqualTo(AnsiColor.GREEN); @@ -50,7 +50,7 @@ public class AnsiColorsTests { } @Test - public void getClosestWhenCloseShouldReturnAnsiColor() { + void getClosestWhenCloseShouldReturnAnsiColor() { assertThat(getClosest(0x292424)).isEqualTo(AnsiColor.BLACK); assertThat(getClosest(0x8C1919)).isEqualTo(AnsiColor.RED); assertThat(getClosest(0x0BA10B)).isEqualTo(AnsiColor.GREEN); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java index dde77b6244e..9dda751cab3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.ansi; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiOutput.Enabled; @@ -29,20 +29,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AnsiOutputTests { +class AnsiOutputTests { - @BeforeClass + @BeforeAll public static void enable() { AnsiOutput.setEnabled(Enabled.ALWAYS); } - @AfterClass + @AfterAll public static void reset() { AnsiOutput.setEnabled(Enabled.DETECT); } @Test - public void encoding() { + void encoding() { String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", AnsiStyle.NORMAL, "D", AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); assertThat(encoded).isEqualTo("ABDEF"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java index ad07de91c05..af25c3687f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.ansi; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiOutput.Enabled; @@ -28,51 +28,51 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AnsiPropertySourceTests { +class AnsiPropertySourceTests { private AnsiPropertySource source = new AnsiPropertySource("ansi", false); - @After + @AfterEach public void reset() { AnsiOutput.setEnabled(Enabled.DETECT); } @Test - public void getAnsiStyle() { + void getAnsiStyle() { assertThat(this.source.getProperty("AnsiStyle.BOLD")).isEqualTo(AnsiStyle.BOLD); } @Test - public void getAnsiColor() { + void getAnsiColor() { assertThat(this.source.getProperty("AnsiColor.RED")).isEqualTo(AnsiColor.RED); } @Test - public void getAnsiBackground() { + void getAnsiBackground() { assertThat(this.source.getProperty("AnsiBackground.GREEN")).isEqualTo(AnsiBackground.GREEN); } @Test - public void getAnsi() { + void getAnsi() { assertThat(this.source.getProperty("Ansi.BOLD")).isEqualTo(AnsiStyle.BOLD); assertThat(this.source.getProperty("Ansi.RED")).isEqualTo(AnsiColor.RED); assertThat(this.source.getProperty("Ansi.BG_RED")).isEqualTo(AnsiBackground.RED); } @Test - public void getMissing() { + void getMissing() { assertThat(this.source.getProperty("AnsiStyle.NOPE")).isNull(); } @Test - public void encodeEnabled() { + void encodeEnabled() { AnsiOutput.setEnabled(Enabled.ALWAYS); AnsiPropertySource source = new AnsiPropertySource("ansi", true); assertThat(source.getProperty("Ansi.RED")).isEqualTo("\033[31m"); } @Test - public void encodeDisabled() { + void encodeDisabled() { AnsiOutput.setEnabled(Enabled.NEVER); AnsiPropertySource source = new AnsiPropertySource("ansi", true); assertThat(source.getProperty("Ansi.RED")).isEqualTo(""); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index b39982d4b54..d98e84ed595 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -20,8 +20,8 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.WebApplicationType; @@ -47,11 +47,11 @@ import static org.mockito.Mockito.verify; * * @author Dave Syer */ -public class SpringApplicationBuilderTests { +class SpringApplicationBuilderTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void close() { close(this.context); } @@ -66,7 +66,7 @@ public class SpringApplicationBuilderTests { } @Test - public void profileAndProperties() { + void profileAndProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class).profiles("foo").properties("foo=bar"); this.context = application.run(); @@ -76,7 +76,7 @@ public class SpringApplicationBuilderTests { } @Test - public void propertiesAsMap() { + void propertiesAsMap() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class).properties(Collections.singletonMap("bar", "foo")); this.context = application.run(); @@ -84,7 +84,7 @@ public class SpringApplicationBuilderTests { } @Test - public void propertiesAsProperties() { + void propertiesAsProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class) .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); @@ -93,7 +93,7 @@ public class SpringApplicationBuilderTests { } @Test - public void propertiesWithRepeatSeparator() { + void propertiesWithRepeatSeparator() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class) .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); @@ -106,7 +106,7 @@ public class SpringApplicationBuilderTests { } @Test - public void specificApplicationContextClass() { + void specificApplicationContextClass() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class); this.context = application.run(); @@ -114,7 +114,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentContextCreationThatIsRunDirectly() { + void parentContextCreationThatIsRunDirectly() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); @@ -127,7 +127,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentContextCreationThatIsBuiltThenRun() { + void parentContextCreationThatIsBuiltThenRun() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) .contextClass(SpyApplicationContext.class); application.parent(ExampleConfig.class); @@ -139,7 +139,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentContextCreationWithChildShutdown() { + void parentContextCreationWithChildShutdown() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) .contextClass(SpyApplicationContext.class).registerShutdownHook(true); application.parent(ExampleConfig.class); @@ -149,7 +149,7 @@ public class SpringApplicationBuilderTests { } @Test - public void contextWithClassLoader() { + void contextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .contextClass(SpyApplicationContext.class); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); @@ -159,7 +159,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentContextWithClassLoader() { + void parentContextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) .contextClass(SpyApplicationContext.class); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); @@ -170,7 +170,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentFirstCreation() { + void parentFirstCreation() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .child(ChildConfig.class); application.contextClass(SpyApplicationContext.class); @@ -180,7 +180,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentFirstCreationWithProfileAndDefaultArgs() { + void parentFirstCreationWithProfileAndDefaultArgs() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") .properties("transport=redis").child(ChildConfig.class).web(WebApplicationType.NONE); this.context = application.run(); @@ -193,7 +193,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentFirstWithDifferentProfile() { + void parentFirstWithDifferentProfile() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") .properties("transport=redis").child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); this.context = application.run(); @@ -202,7 +202,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentWithDifferentProfile() { + void parentWithDifferentProfile() { SpringApplicationBuilder shared = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") .properties("transport=redis"); SpringApplicationBuilder application = shared.child(ChildConfig.class).profiles("admin") @@ -215,7 +215,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentFirstWithDifferentProfileAndExplicitEnvironment() { + void parentFirstWithDifferentProfileAndExplicitEnvironment() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .environment(new StandardEnvironment()).profiles("node").properties("transport=redis") .child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); @@ -227,7 +227,7 @@ public class SpringApplicationBuilderTests { } @Test - public void parentContextIdentical() { + void parentContextIdentical() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class); application.parent(ExampleConfig.class); application.contextClass(SpyApplicationContext.class); @@ -236,7 +236,7 @@ public class SpringApplicationBuilderTests { } @Test - public void initializersCreatedOnce() { + void initializersCreatedOnce() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .web(WebApplicationType.NONE); this.context = application.run(); @@ -244,7 +244,7 @@ public class SpringApplicationBuilderTests { } @Test - public void initializersCreatedOnceForChild() { + void initializersCreatedOnceForChild() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .child(ChildConfig.class).web(WebApplicationType.NONE); this.context = application.run(); @@ -252,7 +252,7 @@ public class SpringApplicationBuilderTests { } @Test - public void initializersIncludeDefaults() { + void initializersIncludeDefaults() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) .web(WebApplicationType.NONE).initializers((ConfigurableApplicationContext applicationContext) -> { }); @@ -261,7 +261,7 @@ public class SpringApplicationBuilderTests { } @Test - public void sourcesWithBoundSources() { + void sourcesWithBoundSources() { SpringApplicationBuilder application = new SpringApplicationBuilder().web(WebApplicationType.NONE) .sources(ExampleConfig.class).properties("spring.main.sources=" + ChildConfig.class.getName()); this.context = application.run(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 4cffb008609..1eb711b9816 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; @@ -35,16 +35,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class CloudPlatformTests { +class CloudPlatformTests { @Test - public void getActiveWhenEnvironmentIsNullShouldReturnNull() { + void getActiveWhenEnvironmentIsNullShouldReturnNull() { CloudPlatform platform = CloudPlatform.getActive(null); assertThat(platform).isNull(); } @Test - public void getActiveWhenNotInCloudShouldReturnNull() { + void getActiveWhenNotInCloudShouldReturnNull() { Environment environment = new MockEnvironment(); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isNull(); @@ -52,7 +52,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasVcapApplicationShouldReturnCloudFoundry() { + void getActiveWhenHasVcapApplicationShouldReturnCloudFoundry() { Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); @@ -60,7 +60,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasVcapServicesShouldReturnCloudFoundry() { + void getActiveWhenHasVcapServicesShouldReturnCloudFoundry() { Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); @@ -68,7 +68,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasDynoShouldReturnHeroku() { + void getActiveWhenHasDynoShouldReturnHeroku() { Environment environment = new MockEnvironment().withProperty("DYNO", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.HEROKU); @@ -76,7 +76,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasHcLandscapeShouldReturnSap() { + void getActiveWhenHasHcLandscapeShouldReturnSap() { Environment environment = new MockEnvironment().withProperty("HC_LANDSCAPE", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); assertThat(platform).isEqualTo(CloudPlatform.SAP); @@ -84,7 +84,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasServiceHostAndServicePortShouldReturnKubernetes() { + void getActiveWhenHasServiceHostAndServicePortShouldReturnKubernetes() { MockEnvironment environment = new MockEnvironment(); Map source = new HashMap<>(); source.put("EXAMPLE_SERVICE_HOST", "---"); @@ -98,7 +98,7 @@ public class CloudPlatformTests { } @Test - public void getActiveWhenHasServiceHostAndNoServicePortShouldNotReturnKubernetes() { + void getActiveWhenHasServiceHostAndNoServicePortShouldNotReturnKubernetes() { MockEnvironment environment = new MockEnvironment(); PropertySource propertySource = new SystemEnvironmentPropertySource( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java index 1dfc56386c2..f254fa450cb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.cloud.cloudfoundry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor; import org.springframework.context.ConfigurableApplicationContext; @@ -31,14 +31,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class CloudFoundryVcapEnvironmentPostProcessorTests { +class CloudFoundryVcapEnvironmentPostProcessorTests { private final CloudFoundryVcapEnvironmentPostProcessor initializer = new CloudFoundryVcapEnvironmentPostProcessor(); private final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); @Test - public void testApplicationProperties() { + void testApplicationProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION={\"application_users\":[]," + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," + "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\"," @@ -55,7 +55,7 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { } @Test - public void testApplicationUris() { + void testApplicationUris() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION={\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\",\"instance_index\":0,\"uris\":[\"foo.cfapps.io\"]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); @@ -63,14 +63,14 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { } @Test - public void testUnparseableApplicationProperties() { + void testUnparseableApplicationProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION:"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); assertThat(getProperty("vcap")).isNull(); } @Test - public void testNullApplicationProperties() { + void testNullApplicationProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_APPLICATION={\"application_users\":null," + "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\"," @@ -87,7 +87,7 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { } @Test - public void testServiceProperties() { + void testServiceProperties() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_SERVICES={\"rds-mysql-n/a\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql-n/a\"," + "\"plan\":\"10mb\",\"credentials\":{" + "\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," @@ -104,7 +104,7 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { } @Test - public void testServicePropertiesWithoutNA() { + void testServicePropertiesWithoutNA() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "VCAP_SERVICES={\"rds-mysql\":[{" + "\"name\":\"mysql\",\"label\":\"rds-mysql\",\"plan\":\"10mb\"," + "\"credentials\":{\"name\":\"d04fb13d27d964c62b267bbba1cffb9da\"," diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java index e91f799c93d..5764afbe319 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java @@ -18,11 +18,10 @@ package org.springframework.boot.context; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; @@ -49,16 +48,16 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Tomasz Przybyla */ -public class ApplicationPidFileWriterTests { +class ApplicationPidFileWriterTests { private static final ApplicationPreparedEvent EVENT = new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, mock(ConfigurableApplicationContext.class)); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; - @Before - @After + @BeforeEach + @AfterEach public void resetListener() { System.clearProperty("PIDFILE"); System.clearProperty("PID_FAIL_ON_WRITE_ERROR"); @@ -66,25 +65,25 @@ public class ApplicationPidFileWriterTests { } @Test - public void createPidFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void createPidFile() throws Exception { + File file = new File(this.tempDir, "pid"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); assertThat(contentOf(file)).isNotEmpty(); } @Test - public void overridePidFile() throws Exception { - File file = this.temporaryFolder.newFile(); - System.setProperty("PIDFILE", this.temporaryFolder.newFile().getAbsolutePath()); + void overridePidFile() throws Exception { + File file = new File(this.tempDir, "pid"); + System.setProperty("PIDFILE", new File(this.tempDir, "override").getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); assertThat(contentOf(new File(System.getProperty("PIDFILE")))).isNotEmpty(); } @Test - public void overridePidFileWithSpring() throws Exception { - File file = this.temporaryFolder.newFile(); + void overridePidFileWithSpring() throws Exception { + File file = new File(this.tempDir, "pid"); SpringApplicationEvent event = createPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); @@ -92,8 +91,9 @@ public class ApplicationPidFileWriterTests { } @Test - public void tryEnvironmentPreparedEvent() throws Exception { - File file = this.temporaryFolder.newFile(); + void tryEnvironmentPreparedEvent() throws Exception { + File file = new File(this.tempDir, "pid"); + file.createNewFile(); SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); @@ -104,8 +104,9 @@ public class ApplicationPidFileWriterTests { } @Test - public void tryReadyEvent() throws Exception { - File file = this.temporaryFolder.newFile(); + void tryReadyEvent() throws Exception { + File file = new File(this.tempDir, "pid"); + file.createNewFile(); SpringApplicationEvent event = createReadyEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); @@ -116,8 +117,8 @@ public class ApplicationPidFileWriterTests { } @Test - public void withNoEnvironment() throws Exception { - File file = this.temporaryFolder.newFile(); + void withNoEnvironment() throws Exception { + File file = new File(this.tempDir, "pid"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.setTriggerEventType(ApplicationStartingEvent.class); listener.onApplicationEvent(new ApplicationStartingEvent(new SpringApplication(), new String[] {})); @@ -125,8 +126,9 @@ public class ApplicationPidFileWriterTests { } @Test - public void continueWhenPidFileIsReadOnly() throws Exception { - File file = this.temporaryFolder.newFile(); + void continueWhenPidFileIsReadOnly() throws Exception { + File file = new File(this.tempDir, "pid"); + file.createNewFile(); file.setReadOnly(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); @@ -134,8 +136,9 @@ public class ApplicationPidFileWriterTests { } @Test - public void throwWhenPidFileIsReadOnly() throws Exception { - File file = this.temporaryFolder.newFile(); + void throwWhenPidFileIsReadOnly() throws Exception { + File file = new File(this.tempDir, "pid"); + file.createNewFile(); file.setReadOnly(); System.setProperty("PID_FAIL_ON_WRITE_ERROR", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); @@ -144,8 +147,9 @@ public class ApplicationPidFileWriterTests { } @Test - public void throwWhenPidFileIsReadOnlyWithSpring() throws Exception { - File file = this.temporaryFolder.newFile(); + void throwWhenPidFileIsReadOnlyWithSpring() throws Exception { + File file = new File(this.tempDir, "pid"); + file.createNewFile(); file.setReadOnly(); SpringApplicationEvent event = createPreparedEvent("spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java index ecdd92eea0d..f51829835c6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.context; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer.ComponentScanPackageCheck; @@ -33,7 +33,8 @@ import org.springframework.boot.context.configwarnings.dflt.InDefaultPackageWith import org.springframework.boot.context.configwarnings.orgspring.InOrgSpringPackageConfiguration; import org.springframework.boot.context.configwarnings.real.InRealButScanningProblemPackages; import org.springframework.boot.context.configwarnings.real.InRealPackageConfiguration; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static org.assertj.core.api.Assertions.assertThat; @@ -43,7 +44,8 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConfigurationWarningsApplicationContextInitializerTests { +@ExtendWith(OutputCaptureExtension.class) +class ConfigurationWarningsApplicationContextInitializerTests { private static final String DEFAULT_SCAN_WARNING = "Your ApplicationContext is unlikely to " + "start due to a @ComponentScan of the default package."; @@ -51,61 +53,58 @@ public class ConfigurationWarningsApplicationContextInitializerTests { private static final String ORGSPRING_SCAN_WARNING = "Your ApplicationContext is unlikely to " + "start due to a @ComponentScan of 'org.springframework'."; - @Rule - public OutputCapture output = new OutputCapture(); - @Test - public void logWarningInDefaultPackage() { + void logWarningInDefaultPackage(CapturedOutput capturedOutput) { load(InDefaultPackageConfiguration.class); - assertThat(this.output.toString()).contains(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).contains(DEFAULT_SCAN_WARNING); } @Test - public void logWarningInDefaultPackageAndMetaAnnotation() { + void logWarningInDefaultPackageAndMetaAnnotation(CapturedOutput capturedOutput) { load(InDefaultPackageWithMetaAnnotationConfiguration.class); - assertThat(this.output.toString()).contains(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).contains(DEFAULT_SCAN_WARNING); } @Test - public void noLogIfInRealPackage() { + void noLogIfInRealPackage(CapturedOutput capturedOutput) { load(InRealPackageConfiguration.class); - assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); } @Test - public void noLogWithoutComponentScanAnnotation() { + void noLogWithoutComponentScanAnnotation(CapturedOutput capturedOutput) { load(InDefaultPackageWithoutScanConfiguration.class); - assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); } @Test - public void noLogIfHasValue() { + void noLogIfHasValue(CapturedOutput capturedOutput) { load(InDefaultPackageWithValueConfiguration.class); - assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); } @Test - public void noLogIfHasBasePackages() { + void noLogIfHasBasePackages(CapturedOutput capturedOutput) { load(InDefaultPackageWithBasePackagesConfiguration.class); - assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); } @Test - public void noLogIfHasBasePackageClasses() { + void noLogIfHasBasePackageClasses(CapturedOutput capturedOutput) { load(InDefaultPackageWithBasePackageClassesConfiguration.class); - assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); + assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); } @Test - public void logWarningInOrgSpringPackage() { + void logWarningInOrgSpringPackage(CapturedOutput capturedOutput) { load(InOrgSpringPackageConfiguration.class); - assertThat(this.output.toString()).contains(ORGSPRING_SCAN_WARNING); + assertThat(capturedOutput).contains(ORGSPRING_SCAN_WARNING); } @Test - public void logWarningIfScanningProblemPackages() { + void logWarningIfScanningProblemPackages(CapturedOutput capturedOutput) { load(InRealButScanningProblemPackages.class); - assertThat(this.output.toString()).contains("Your ApplicationContext is unlikely to start due to a " + assertThat(capturedOutput).contains("Your ApplicationContext is unlikely to start due to a " + "@ComponentScan of the default package, 'org.springframework'."); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java index 0bee82cfd66..d786e07690b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java @@ -20,8 +20,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -34,32 +34,32 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class ContextIdApplicationContextInitializerTests { +class ContextIdApplicationContextInitializerTests { private final ContextIdApplicationContextInitializer initializer = new ContextIdApplicationContextInitializer(); private List contexts = new ArrayList<>(); - @After + @AfterEach public void closeContexts() { Collections.reverse(this.contexts); this.contexts.forEach(ConfigurableApplicationContext::close); } @Test - public void singleContextWithDefaultName() { + void singleContextWithDefaultName() { ConfigurableApplicationContext context = createContext(null); assertThat(context.getId()).isEqualTo("application"); } @Test - public void singleContextWithCustomName() { + void singleContextWithCustomName() { ConfigurableApplicationContext context = createContext(null, "spring.application.name=test"); assertThat(context.getId()).isEqualTo("test"); } @Test - public void linearHierarchy() { + void linearHierarchy() { ConfigurableApplicationContext grandparent = createContext(null); ConfigurableApplicationContext parent = createContext(grandparent); ConfigurableApplicationContext child = createContext(parent); @@ -67,7 +67,7 @@ public class ContextIdApplicationContextInitializerTests { } @Test - public void complexHierarchy() { + void complexHierarchy() { ConfigurableApplicationContext grandparent = createContext(null); ConfigurableApplicationContext parent1 = createContext(grandparent); ConfigurableApplicationContext parent2 = createContext(grandparent); @@ -80,7 +80,7 @@ public class ContextIdApplicationContextInitializerTests { } @Test - public void contextWithParentWithNoContextIdFallsBackToDefaultId() { + void contextWithParentWithNoContextIdFallsBackToDefaultId() { ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(); this.contexts.add(parent); parent.refresh(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java index 825b01e3189..0c70e535323 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/FileEncodingApplicationListenerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Dave Syer */ -public class FileEncodingApplicationListenerTests { +class FileEncodingApplicationListenerTests { private final FileEncodingApplicationListener initializer = new FileEncodingApplicationListener(); @@ -43,7 +43,7 @@ public class FileEncodingApplicationListenerTests { new SpringApplication(), new String[0], this.environment); @Test - public void testIllegalState() { + void testIllegalState() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.mandatory_file_encoding=FOO"); ConfigurationPropertySources.attach(this.environment); @@ -51,12 +51,12 @@ public class FileEncodingApplicationListenerTests { } @Test - public void testSunnyDayNothingMandated() { + void testSunnyDayNothingMandated() { this.initializer.onApplicationEvent(this.event); } @Test - public void testSunnyDayMandated() { + void testSunnyDayMandated() { assertThat(System.getProperty("file.encoding")).isNotNull(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.mandatory_file_encoding:" + System.getProperty("file.encoding")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index 574f72e2ea7..f8328e19013 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.context; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.context.filtersample.ExampleComponent; @@ -37,11 +37,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -public class TypeExcludeFilterTests { +class TypeExcludeFilterTests { private AnnotationConfigApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -49,7 +49,7 @@ public class TypeExcludeFilterTests { } @Test - public void loadsTypeExcludeFilters() { + void loadsTypeExcludeFilters() { this.context = new AnnotationConfigApplicationContext(); this.context.getBeanFactory().registerSingleton("filter1", new WithoutMatchOverrideFilter()); this.context.getBeanFactory().registerSingleton("filter2", new SampleTypeExcludeFilter()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index f87968d360f..d4515a8b112 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -25,7 +25,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -39,23 +39,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ConfigurationsTests { +class ConfigurationsTests { @Test - public void createWhenClassesIsNullShouldThrowException() { + void createWhenClassesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestConfigurations(null)) .withMessageContaining("Classes must not be null"); } @Test - public void createShouldSortClasses() { + void createShouldSortClasses() { TestSortedConfigurations configurations = new TestSortedConfigurations( Arrays.asList(OutputStream.class, InputStream.class)); assertThat(configurations.getClasses()).containsExactly(InputStream.class, OutputStream.class); } @Test - public void getClassesShouldMergeByClassAndSort() { + void getClassesShouldMergeByClassAndSort() { Configurations c1 = new TestSortedConfigurations(Arrays.asList(OutputStream.class, InputStream.class)); Configurations c2 = new TestConfigurations(Collections.singletonList(Short.class)); Configurations c3 = new TestSortedConfigurations(Arrays.asList(String.class, Integer.class)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java index ec9a44ee182..88993c130ea 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/UserConfigurationsTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.annotation; import java.io.InputStream; import java.io.OutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class UserConfigurationsTests { +class UserConfigurationsTests { @Test - public void ofShouldCreateUnorderedConfigurations() { + void ofShouldCreateUnorderedConfigurations() { UserConfigurations configurations = UserConfigurations.of(OutputStream.class, InputStream.class); assertThat(Configurations.getClasses(configurations)).containsExactly(OutputStream.class, InputStream.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java index 4ae5811b23b..ab72b80516c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/AnsiOutputApplicationListenerTests.java @@ -19,9 +19,9 @@ package org.springframework.boot.context.config; import java.util.HashMap; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -41,16 +41,16 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class AnsiOutputApplicationListenerTests { +class AnsiOutputApplicationListenerTests { private ConfigurableApplicationContext context; - @Before + @BeforeEach public void resetAnsi() { AnsiOutput.setEnabled(Enabled.DETECT); } - @After + @AfterEach public void cleanUp() { resetAnsi(); if (this.context != null) { @@ -59,7 +59,7 @@ public class AnsiOutputApplicationListenerTests { } @Test - public void enabled() { + void enabled() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); Map props = new HashMap<>(); @@ -70,7 +70,7 @@ public class AnsiOutputApplicationListenerTests { } @Test - public void disabled() { + void disabled() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); Map props = new HashMap<>(); @@ -81,7 +81,7 @@ public class AnsiOutputApplicationListenerTests { } @Test - public void disabledViaApplicationProperties() { + void disabledViaApplicationProperties() { ConfigurableEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "spring.config.name=ansi"); SpringApplication application = new SpringApplication(Config.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index ae0ada2498e..65d5909c365 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -33,9 +33,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.LoggerConfig; import org.assertj.core.api.Condition; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -43,7 +43,8 @@ import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEven import org.springframework.boot.context.event.ApplicationPreparedEvent; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.boot.testsupport.BuildOutput; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; @@ -71,7 +72,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Eddú Meléndez */ -public class ConfigFileApplicationListenerTests { +@ExtendWith(OutputCaptureExtension.class) +class ConfigFileApplicationListenerTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); @@ -81,12 +83,9 @@ public class ConfigFileApplicationListenerTests { private final ConfigFileApplicationListener initializer = new ConfigFileApplicationListener(); - @Rule - public OutputCapture out = new OutputCapture(); - private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -96,7 +95,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadCustomResource() { + void loadCustomResource() { this.application.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { @@ -123,7 +122,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadPropertiesFile() { + void loadPropertiesFile() { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -131,7 +130,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadDefaultPropertiesFile() { + void loadDefaultPropertiesFile() { this.environment.setDefaultProfiles("thedefault"); this.initializer.setSearchNames("testprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -140,7 +139,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFile() { + void loadTwoPropertiesFile() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + "classpath:application.properties,classpath:testproperties.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -149,7 +148,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFilesWithProfiles() { + void loadTwoPropertiesFilesWithProfiles() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=classpath:enableprofile.properties," + "classpath:enableother.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -159,7 +158,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFilesWithProfilesUsingAdditionalLocation() { + void loadTwoPropertiesFilesWithProfilesUsingAdditionalLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.additional-location=classpath:enableprofile.properties," + "classpath:enableother.properties"); @@ -170,7 +169,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOff() { + void loadTwoPropertiesFilesWithProfilesAndSwitchOneOff() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=classpath:enabletwoprofiles.properties," + "classpath:enableprofile.properties"); @@ -183,7 +182,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation() { + void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.name=enabletwoprofiles", "spring.config.location=classpath:enableprofile.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -195,7 +194,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void localFileTakesPrecedenceOverClasspath() throws Exception { + void localFileTakesPrecedenceOverClasspath() throws Exception { File localFile = new File(new File("."), "application.properties"); assertThat(localFile.exists()).isFalse(); try { @@ -214,7 +213,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void moreSpecificLocationTakesPrecedenceOverRoot() { + void moreSpecificLocationTakesPrecedenceOverRoot() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.name=specific"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); @@ -222,7 +221,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadTwoOfThreePropertiesFile() { + void loadTwoOfThreePropertiesFile() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=classpath:application.properties," + "classpath:testproperties.properties," + "classpath:nonexistent.properties"); @@ -232,14 +231,14 @@ public class ConfigFileApplicationListenerTests { } @Test - public void randomValue() { + void randomValue() { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("random.value"); assertThat(property).isNotNull(); } @Test - public void loadTwoPropertiesFiles() { + void loadTwoPropertiesFiles() { this.initializer.setSearchNames("moreproperties,testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -248,7 +247,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadYamlFile() { + void loadYamlFile() { this.initializer.setSearchNames("testyaml"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); @@ -258,7 +257,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadProfileEmptySameAsNotSpecified() { + void loadProfileEmptySameAsNotSpecified() { this.initializer.setSearchNames("testprofilesempty"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); @@ -266,7 +265,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadDefaultYamlDocument() { + void loadDefaultYamlDocument() { this.environment.setDefaultProfiles("thedefault"); this.initializer.setSearchNames("testprofilesdocument"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -275,7 +274,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadDefaultYamlDocumentNotActivated() { + void loadDefaultYamlDocumentNotActivated() { this.environment.setDefaultProfiles("thedefault"); this.environment.setActiveProfiles("other"); this.initializer.setSearchNames("testprofilesdocument"); @@ -285,7 +284,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void commandLineWins() { + void commandLineWins() { this.environment.getPropertySources() .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.initializer.setSearchNames("testproperties"); @@ -295,7 +294,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void systemPropertyWins() { + void systemPropertyWins() { System.setProperty("the.property", "fromsystem"); this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -304,7 +303,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void defaultPropertyAsFallback() { + void defaultPropertyAsFallback() { this.environment.getPropertySources().addLast( new MapPropertySource("defaultProperties", Collections.singletonMap("my.fallback", (Object) "foo"))); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -313,7 +312,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void defaultPropertyAsFallbackDuringFileParsing() { + void defaultPropertyAsFallbackDuringFileParsing() { this.environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", Collections.singletonMap("spring.config.name", (Object) "testproperties"))); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -322,7 +321,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activeProfilesFromDefaultPropertiesShouldNotTakePrecedence() { + void activeProfilesFromDefaultPropertiesShouldNotTakePrecedence() { this.initializer.setSearchNames("enableprofile"); this.environment.getPropertySources().addLast( new MapPropertySource("defaultProperties", Collections.singletonMap("spring.profiles.active", "dev"))); @@ -331,7 +330,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void includedProfilesFromDefaultPropertiesShouldNotTakePrecedence() { + void includedProfilesFromDefaultPropertiesShouldNotTakePrecedence() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=morespecific"); this.environment.getPropertySources().addLast( @@ -341,7 +340,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activeAndIncludedProfilesFromDefaultProperties() { + void activeAndIncludedProfilesFromDefaultProperties() { Map source = new HashMap<>(); source.put("spring.profiles.include", "other"); source.put("spring.profiles.active", "dev"); @@ -351,7 +350,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activeFromDefaultPropertiesShouldNotApplyIfProfilesHaveBeenActivatedBefore() { + void activeFromDefaultPropertiesShouldNotApplyIfProfilesHaveBeenActivatedBefore() { Map source = new HashMap<>(); source.put("spring.profiles.active", "dev"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); @@ -361,7 +360,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadPropertiesThenProfilePropertiesActivatedInSpringApplication() { + void loadPropertiesThenProfilePropertiesActivatedInSpringApplication() { // This should be the effect of calling // SpringApplication.setAdditionalProfiles("other") this.environment.setActiveProfiles("other"); @@ -373,7 +372,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void twoProfilesFromProperties() { + void twoProfilesFromProperties() { // This should be the effect of calling // SpringApplication.setAdditionalProfiles("other", "dev") this.environment.setActiveProfiles("other", "dev"); @@ -385,7 +384,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadPropertiesThenProfilePropertiesActivatedInFirst() { + void loadPropertiesThenProfilePropertiesActivatedInFirst() { this.initializer.setSearchNames("enableprofile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); @@ -395,7 +394,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void loadPropertiesThenProfilePropertiesWithOverride() { + void loadPropertiesThenProfilePropertiesWithOverride() { this.environment.setActiveProfiles("other"); this.initializer.setSearchNames("enableprofile"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -410,7 +409,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void profilePropertiesUsedInPlaceholders() { + void profilePropertiesUsedInPlaceholders() { this.initializer.setSearchNames("enableprofile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("one.more"); @@ -418,68 +417,68 @@ public class ConfigFileApplicationListenerTests { } @Test - public void profilesAddedToEnvironmentAndViaProperty() { + void profilesAddedToEnvironmentAndViaProperty(CapturedOutput capturedOutput) { // External profile takes precedence over profile added via the environment TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); - validateProfilePrecedence(null, "dev", "other"); + validateProfilePreference(capturedOutput, null, "dev", "other"); } @Test - public void profilesAddedToEnvironmentViaActiveAndIncludeProperty() { + void profilesAddedToEnvironmentViaActiveAndIncludeProperty(CapturedOutput capturedOutput) { // Active profile property takes precedence TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev", "spring.profiles.include=other"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); - validateProfilePrecedence(null, "other", "dev"); + validateProfilePreference(capturedOutput, null, "other", "dev"); } @Test - public void profilesAddedViaIncludePropertyAndActivatedViaAnotherPropertySource() { + void profilesAddedViaIncludePropertyAndActivatedViaAnotherPropertySource(CapturedOutput capturedOutput) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.include=dev,simple"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "simple", "other"); - validateProfilePrecedence("dev", "simple", "other"); + validateProfilePreference(capturedOutput, "dev", "simple", "other"); } @Test - public void profilesAddedToEnvironmentAndViaPropertyDuplicate() { + void profilesAddedToEnvironmentAndViaPropertyDuplicate(CapturedOutput capturedOutput) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev,other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); - validateProfilePrecedence(null, "dev", "other"); + validateProfilePreference(capturedOutput, null, "dev", "other"); } @Test - public void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins() { + void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins(CapturedOutput capturedOutput) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other,dev"); this.environment.addActiveProfile("other"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); - validateProfilePrecedence(null, "other", "dev"); + validateProfilePreference(capturedOutput, null, "other", "dev"); } @Test - public void postProcessorsAreOrderedCorrectly() { + void postProcessorsAreOrderedCorrectly() { TestConfigFileApplicationListener testListener = new TestConfigFileApplicationListener(); testListener.onApplicationEvent( new ApplicationEnvironmentPreparedEvent(this.application, new String[0], this.environment)); } - private void validateProfilePrecedence(String... profiles) { + private void validateProfilePreference(CapturedOutput capturedOutput, String... profiles) { ApplicationPreparedEvent event = new ApplicationPreparedEvent(new SpringApplication(), new String[0], new AnnotationConfigApplicationContext()); withDebugLogging(() -> this.initializer.onApplicationEvent(event)); - String log = this.out.toString(); + String log = capturedOutput.toString(); // First make sure that each profile got processed only once for (String profile : profiles) { @@ -520,7 +519,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlProfiles() { + void yamlProfiles() { this.initializer.setSearchNames("testprofiles"); this.environment.setActiveProfiles("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -531,7 +530,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlTwoProfiles() { + void yamlTwoProfiles() { this.initializer.setSearchNames("testprofiles"); this.environment.setActiveProfiles("other", "dev"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -542,17 +541,17 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlProfileExpressionsAnd() { + void yamlProfileExpressionsAnd() { assertProfileExpression("devandother", "dev", "other"); } @Test - public void yamlProfileExpressionsComplex() { + void yamlProfileExpressionsComplex() { assertProfileExpression("devorotherandanother", "dev", "another"); } @Test - public void yamlProfileExpressionsNoMatch() { + void yamlProfileExpressionsNoMatch() { assertProfileExpression("fromyamlfile", "dev"); } @@ -565,7 +564,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlNegatedProfiles() { + void yamlNegatedProfiles() { // gh-8011 this.initializer.setSearchNames("testnegatedprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -576,7 +575,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlNegatedProfilesWithProfile() { + void yamlNegatedProfilesWithProfile() { // gh-8011 this.initializer.setSearchNames("testnegatedprofiles"); this.environment.setActiveProfiles("other"); @@ -588,7 +587,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlSetsProfiles() { + void yamlSetsProfiles() { this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev"); @@ -602,28 +601,28 @@ public class ConfigFileApplicationListenerTests { } @Test - public void yamlSetsMultiProfiles() { + void yamlSetsMultiProfiles() { this.initializer.setSearchNames("testsetmultiprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test - public void yamlSetsMultiProfilesWhenListProvided() { + void yamlSetsMultiProfilesWhenListProvided() { this.initializer.setSearchNames("testsetmultiprofileslist"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test - public void yamlSetsMultiProfilesWithWhitespace() { + void yamlSetsMultiProfilesWithWhitespace() { this.initializer.setSearchNames("testsetmultiprofileswhitespace"); this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "healthcheck"); } @Test - public void yamlProfileCanBeChanged() { + void yamlProfileCanBeChanged() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=prod"); this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -631,7 +630,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void specificNameAndProfileFromExistingSource() { + void specificNameAndProfileFromExistingSource() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=specificprofile", "spring.config.name=specificfile"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -640,7 +639,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void specificResource() { + void specificResource() { String location = "classpath:specificlocation.properties"; TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); @@ -656,7 +655,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void specificResourceFromAdditionalLocation() { + void specificResourceFromAdditionalLocation() { String additionalLocation = "classpath:specificlocation.properties"; TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.additional-location=" + additionalLocation); @@ -672,7 +671,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void specificResourceAsFile() { + void specificResourceAsFile() { String location = "file:src/test/resources/specificlocation.properties"; TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); @@ -681,7 +680,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void specificResourceDefaultsToFile() { + void specificResourceDefaultsToFile() { String location = "src/test/resources/specificlocation.properties"; TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); @@ -690,7 +689,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void absoluteResourceDefaultsToFile() { + void absoluteResourceDefaultsToFile() { String location = new File("src/test/resources/specificlocation.properties").getAbsolutePath().replace("\\", "/"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, @@ -701,7 +700,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotation() { + void propertySourceAnnotation() { SpringApplication application = new SpringApplication(WithPropertySource.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); @@ -715,7 +714,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationWithPlaceholder() { + void propertySourceAnnotationWithPlaceholder() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "source.location=specificlocation"); SpringApplication application = new SpringApplication(WithPropertySourcePlaceholders.class); application.setEnvironment(this.environment); @@ -729,7 +728,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationWithName() { + void propertySourceAnnotationWithName() { SpringApplication application = new SpringApplication(WithPropertySourceAndName.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); @@ -740,7 +739,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationInProfile() { + void propertySourceAnnotationInProfile() { SpringApplication application = new SpringApplication(WithPropertySourceInProfile.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run("--spring.profiles.active=myprofile"); @@ -754,7 +753,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationAndNonActiveProfile() { + void propertySourceAnnotationAndNonActiveProfile() { SpringApplication application = new SpringApplication(WithPropertySourceAndProfile.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); @@ -766,7 +765,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationMultipleLocations() { + void propertySourceAnnotationMultipleLocations() { SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocations.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); @@ -778,7 +777,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertySourceAnnotationMultipleLocationsAndName() { + void propertySourceAnnotationMultipleLocationsAndName() { SpringApplication application = new SpringApplication(WithPropertySourceMultipleLocationsAndName.class); application.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = application.run(); @@ -789,7 +788,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activateProfileFromProfileSpecificProperties() { + void activateProfileFromProfileSpecificProperties(CapturedOutput capturedOutput) { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.active=includeprofile"); @@ -799,12 +798,12 @@ public class ConfigFileApplicationListenerTests { assertThat(environment).has(matchingProfile("morespecific")); assertThat(environment).has(matchingProfile("yetmorespecific")); assertThat(environment).doesNotHave(matchingProfile("missing")); - assertThat(this.out.toString()) + assertThat(capturedOutput) .contains("The following profiles are active: includeprofile,specific,morespecific,yetmorespecific"); } @Test - public void profileSubDocumentInSameProfileSpecificFile() { + void profileSubDocumentInSameProfileSpecificFile() { // gh-340 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -814,7 +813,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void profileSubDocumentInDifferentProfileSpecificFile() { + void profileSubDocumentInDifferentProfileSpecificFile() { // gh-4132 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -825,7 +824,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void addBeforeDefaultProperties() { + void addBeforeDefaultProperties() { MapPropertySource defaultSource = new MapPropertySource("defaultProperties", Collections.singletonMap("the.property", "fromdefaultproperties")); this.environment.getPropertySources().addFirst(defaultSource); @@ -836,7 +835,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void customDefaultProfile() { + void customDefaultProfile() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.default=customdefault"); @@ -845,7 +844,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void customDefaultProfileAndActive() { + void customDefaultProfileAndActive() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.default=customdefault", "--spring.profiles.active=dev"); @@ -855,7 +854,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void customDefaultProfileAndActiveFromFile() { + void customDefaultProfileAndActiveFromFile() { // gh-5998 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -868,7 +867,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void additionalProfilesCanBeIncludedFromAnyPropertySource() { + void additionalProfilesCanBeIncludedFromAnyPropertySource() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.active=myprofile", "--spring.profiles.include=dev"); @@ -878,7 +877,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void profileCanBeIncludedWithoutAnyBeingActive() { + void profileCanBeIncludedWithoutAnyBeingActive() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run("--spring.profiles.include=dev"); @@ -887,7 +886,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void activeProfilesCanBeConfiguredUsingPlaceholdersResolvedAgainstTheEnvironment() { + void activeProfilesCanBeConfiguredUsingPlaceholdersResolvedAgainstTheEnvironment() { Map source = new HashMap<>(); source.put("activeProfile", "testPropertySource"); org.springframework.core.env.PropertySource propertySource = new MapPropertySource("test", source); @@ -898,7 +897,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void additionalLocationTakesPrecedenceOverDefaultLocation() { + void additionalLocationTakesPrecedenceOverDefaultLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.additional-location=classpath:override.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -907,7 +906,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void lastAdditionalLocationWins() { + void lastAdditionalLocationWins() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.additional-location=classpath:override.properties," + "classpath:some.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -916,7 +915,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void locationReplaceDefaultLocation() { + void locationReplaceDefaultLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=classpath:override.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); @@ -925,7 +924,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void includeLoop() { + void includeLoop() { // gh-13361 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -935,7 +934,7 @@ public class ConfigFileApplicationListenerTests { } @Test - public void multiValueSpringProfiles() { + void multiValueSpringProfiles() { // gh-13362 SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); @@ -947,13 +946,13 @@ public class ConfigFileApplicationListenerTests { } @Test - public void propertiesFromCustomPropertySourceLoaderShouldBeUsed() { + void propertiesFromCustomPropertySourceLoaderShouldBeUsed() { this.initializer.postProcessEnvironment(this.environment, this.application); assertThat(this.environment.getProperty("customloader1")).isEqualTo("true"); } @Test - public void propertiesFromCustomPropertySourceLoaderShouldBeUsedWithSpecificResource() { + void propertiesFromCustomPropertySourceLoaderShouldBeUsedWithSpecificResource() { String location = "classpath:application.custom"; TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.config.location=" + location); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java index 1981d40b343..53c8034a40c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerYamlProfileNegationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.context.config; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -32,11 +32,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class ConfigFileApplicationListenerYamlProfileNegationTests { +class ConfigFileApplicationListenerYamlProfileNegationTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -44,7 +44,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileNegationDefaultProfile() { + void yamlProfileNegationDefaultProfile() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=profilenegation"; @@ -53,7 +53,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileNegationWithActiveProfile() { + void yamlProfileNegationWithActiveProfile() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=profilenegation"; @@ -62,7 +62,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileNegationLocalActiveProfiles() { + void yamlProfileNegationLocalActiveProfiles() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=profilenegation-local-active-profiles"; @@ -71,7 +71,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileNegationOverrideLocalActiveProfiles() { + void yamlProfileNegationOverrideLocalActiveProfiles() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=profilenegation-local-active-profiles"; @@ -80,7 +80,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileNegationWithProfileSpecificFile() { + void yamlProfileNegationWithProfileSpecificFile() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=profilenegation"; @@ -89,7 +89,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileCascading() { + void yamlProfileCascading() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=cascadingprofiles"; @@ -103,7 +103,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileCascadingOverrideProfilesA() { + void yamlProfileCascadingOverrideProfilesA() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=cascadingprofiles"; @@ -117,7 +117,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileCascadingMultipleActiveProfilesViaPropertiesShouldPreserveOrder() { + void yamlProfileCascadingMultipleActiveProfilesViaPropertiesShouldPreserveOrder() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=cascadingprofiles"; @@ -131,7 +131,7 @@ public class ConfigFileApplicationListenerYamlProfileNegationTests { } @Test - public void yamlProfileCascadingOverrideProfilesB() { + void yamlProfileCascadingOverrideProfilesB() { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); String configName = "--spring.config.name=cascadingprofiles"; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index 33c6bc2e26d..a18eb41c682 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationContextInitializer; @@ -36,12 +36,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class DelegatingApplicationContextInitializerTests { +class DelegatingApplicationContextInitializerTests { private final DelegatingApplicationContextInitializer initializer = new DelegatingApplicationContextInitializer(); @Test - public void orderedInitialize() { + void orderedInitialize() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); @@ -51,20 +51,20 @@ public class DelegatingApplicationContextInitializerTests { } @Test - public void noInitializers() { + void noInitializers() { StaticApplicationContext context = new StaticApplicationContext(); this.initializer.initialize(context); } @Test - public void emptyInitializers() { + void emptyInitializers() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes:"); this.initializer.initialize(context); } @Test - public void noSuchInitializerClass() { + void noSuchInitializerClass() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=missing.madeup.class"); @@ -73,7 +73,7 @@ public class DelegatingApplicationContextInitializerTests { } @Test - public void notAnInitializerClass() { + void notAnInitializerClass() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + Object.class.getName()); @@ -81,7 +81,7 @@ public class DelegatingApplicationContextInitializerTests { } @Test - public void genericNotSuitable() { + void genericNotSuitable() { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + NotSuitableInit.class.getName()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index 7d36faf2744..58cc81bad1b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.context.config; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class DelegatingApplicationListenerTests { +class DelegatingApplicationListenerTests { private final DelegatingApplicationListener listener = new DelegatingApplicationListener(); private final StaticApplicationContext context = new StaticApplicationContext(); - @After + @AfterEach public void close() { if (this.context != null) { this.context.close(); @@ -50,7 +50,7 @@ public class DelegatingApplicationListenerTests { } @Test - public void orderedInitialize() { + void orderedInitialize() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], @@ -62,13 +62,13 @@ public class DelegatingApplicationListenerTests { } @Test - public void noInitializers() { + void noInitializers() { this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], this.context.getEnvironment())); } @Test - public void emptyInitializers() { + void emptyInitializers() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes:"); this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], this.context.getEnvironment())); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java index 89ffe1444f1..1672c48d9ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.context.logging; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +25,8 @@ import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.event.ApplicationStartingEvent; import org.springframework.boot.logging.LoggingSystem; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; @@ -37,13 +38,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class LoggingApplicationListenerIntegrationTests { - - @Rule - public OutputCapture outputCapture = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class LoggingApplicationListenerIntegrationTests { @Test - public void loggingSystemRegisteredInTheContext() { + void loggingSystemRegisteredInTheContext() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) .web(WebApplicationType.NONE).run()) { SampleService service = context.getBean(SampleService.class); @@ -52,7 +51,7 @@ public class LoggingApplicationListenerIntegrationTests { } @Test - public void loggingPerformedDuringChildApplicationStartIsNotLost() { + void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput capturedOutput) { new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class) .web(WebApplicationType.NONE).listeners(new ApplicationListener() { @@ -64,7 +63,7 @@ public class LoggingApplicationListenerIntegrationTests { } }).run(); - assertThat(this.outputCapture.toString()).contains("Child application starting"); + assertThat(capturedOutput).contains("Child application starting"); } @Component diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 128ab8ac754..209f54b4fe8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -28,6 +28,7 @@ import java.util.logging.Handler; import java.util.logging.LogManager; import java.util.logging.Logger; +import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -53,9 +54,9 @@ import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; import org.springframework.boot.logging.java.JavaLoggingSystem; import org.springframework.boot.system.ApplicationPid; -import org.springframework.boot.testsupport.rule.OutputCapture; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.system.OutputCaptureRule; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; @@ -89,7 +90,7 @@ public class LoggingApplicationListenerTests { private static final String[] NO_ARGS = {}; @Rule - public OutputCapture outputCapture = new OutputCapture(); + public OutputCaptureRule outputCapture = new OutputCaptureRule(); @Rule public final TemporaryFolder temp = new TemporaryFolder(); @@ -366,6 +367,7 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsFails() { + this.logger.setLevel(Level.INFO); addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java index 7905841fe57..723e3c92945 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java @@ -17,7 +17,7 @@ package org.springframework.boot.context.properties; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -40,14 +40,14 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Madhura Bhave * @author Stephane Nicoll */ -public class ConfigurationPropertiesBeanRegistrarTests { +class ConfigurationPropertiesBeanRegistrarTests { private final ConfigurationPropertiesBeanRegistrar registrar = new ConfigurationPropertiesBeanRegistrar(); private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @Test - public void typeWithDefaultConstructorShouldRegisterGenericBeanDefinition() throws Exception { + void typeWithDefaultConstructorShouldRegisterGenericBeanDefinition() throws Exception { this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "foo-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$FooProperties"); @@ -55,8 +55,7 @@ public class ConfigurationPropertiesBeanRegistrarTests { } @Test - public void typeWithOneConstructorWithParametersShouldRegisterConfigurationPropertiesBeanDefinition() - throws Exception { + void typeWithOneConstructorWithParametersShouldRegisterConfigurationPropertiesBeanDefinition() throws Exception { this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "bar-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$BarProperties"); @@ -64,7 +63,7 @@ public class ConfigurationPropertiesBeanRegistrarTests { } @Test - public void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() throws Exception { + void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() throws Exception { this.registrar.registerBeanDefinitions(getAnnotationMetadata(TestConfiguration.class), this.beanFactory); BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition( "bing-org.springframework.boot.context.properties.ConfigurationPropertiesBeanRegistrarTests$BingProperties"); @@ -72,7 +71,7 @@ public class ConfigurationPropertiesBeanRegistrarTests { } @Test - public void typeWithNoAnnotationShouldFail() { + void typeWithNoAnnotationShouldFail() { assertThatIllegalArgumentException() .isThrownBy(() -> this.registrar .registerBeanDefinitions(getAnnotationMetadata(InvalidConfiguration.class), this.beanFactory)) @@ -81,14 +80,14 @@ public class ConfigurationPropertiesBeanRegistrarTests { } @Test - public void registrationWithDuplicatedTypeShouldRegisterSingleBeanDefinition() throws IOException { + void registrationWithDuplicatedTypeShouldRegisterSingleBeanDefinition() throws IOException { DefaultListableBeanFactory factory = spy(this.beanFactory); this.registrar.registerBeanDefinitions(getAnnotationMetadata(DuplicateConfiguration.class), factory); verify(factory, times(1)).registerBeanDefinition(anyString(), any()); } @Test - public void registrationWithNoTypeShouldNotRegisterAnything() throws IOException { + void registrationWithNoTypeShouldNotRegisterAnything() throws IOException { DefaultListableBeanFactory factory = spy(this.beanFactory); this.registrar.registerBeanDefinitions(getAnnotationMetadata(EmptyConfiguration.class), factory); verifyZeroInteractions(factory); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java index 610b043f2ec..bcdf73475cd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindHandlerAdvisorTests.java @@ -20,8 +20,8 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.AbstractBindHandler; import org.springframework.boot.context.properties.bind.BindContext; @@ -41,17 +41,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConfigurationPropertiesBindHandlerAdvisorTests { +class ConfigurationPropertiesBindHandlerAdvisorTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @After + @AfterEach public void cleanup() { this.context.close(); } @Test - public void loadWithoutConfigurationPropertiesBindHandlerAdvisor() { + void loadWithoutConfigurationPropertiesBindHandlerAdvisor() { load(WithoutConfigurationPropertiesBindHandlerAdvisor.class, "foo.bar.default.content-type=text/plain", "foo.bar.bindings.input.destination=d1", "foo.bar.bindings.input.content-type=text/xml", "foo.bar.bindings.output.destination=d2"); @@ -65,7 +65,7 @@ public class ConfigurationPropertiesBindHandlerAdvisorTests { } @Test - public void loadWithConfigurationPropertiesBindHandlerAdvisor() { + void loadWithConfigurationPropertiesBindHandlerAdvisor() { load(WithConfigurationPropertiesBindHandlerAdvisor.class, "foo.bar.default.content-type=text/plain", "foo.bar.bindings.input.destination=d1", "foo.bar.bindings.input.content-type=text/xml", "foo.bar.bindings.output.destination=d2"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java index 67e7964dd23..dc19f65feb8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java @@ -17,8 +17,8 @@ package org.springframework.boot.context.properties; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -38,19 +38,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Madhura Bhave */ -public class ConfigurationPropertiesScanRegistrarTests { +class ConfigurationPropertiesScanRegistrarTests { private final ConfigurationPropertiesScanRegistrar registrar = new ConfigurationPropertiesScanRegistrar(); private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - @Before + @BeforeEach public void setup() { this.registrar.setEnvironment(new MockEnvironment()); } @Test - public void registerBeanDefintionsShouldScanForConfigurationProperties() throws IOException { + void registerBeanDefintionsShouldScanForConfigurationProperties() throws IOException { this.registrar.registerBeanDefinitions(getAnnotationMetadata(ConfigurationPropertiesScanConfiguration.class), this.beanFactory); BeanDefinition bingDefinition = this.beanFactory.getBeanDefinition( @@ -65,7 +65,7 @@ public class ConfigurationPropertiesScanRegistrarTests { } @Test - public void scanWhenBeanDefinitionExistsShouldSkip() throws IOException { + void scanWhenBeanDefinitionExistsShouldSkip() throws IOException { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); this.registrar.registerBeanDefinitions( @@ -76,7 +76,7 @@ public class ConfigurationPropertiesScanRegistrarTests { } @Test - public void scanWhenBasePackagesAndBasePackcageClassesProvidedShouldUseThat() throws IOException { + void scanWhenBasePackagesAndBasePackcageClassesProvidedShouldUseThat() throws IOException { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); this.registrar.registerBeanDefinitions( @@ -94,7 +94,7 @@ public class ConfigurationPropertiesScanRegistrarTests { } @Test - public void scanWhenComponentAnnotationPresentShouldThrowException() { + void scanWhenComponentAnnotationPresentShouldThrowException() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); assertThatExceptionOfType(InvalidConfigurationPropertiesException.class) @@ -105,7 +105,7 @@ public class ConfigurationPropertiesScanRegistrarTests { } @Test - public void scanWhenOtherComponentAnnotationPresentShouldThrowException() { + void scanWhenOtherComponentAnnotationPresentShouldThrowException() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(false); assertThatExceptionOfType(InvalidConfigurationPropertiesException.class) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java index 3e5a247dd51..4870982c8b8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.context.properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration; @@ -36,16 +36,16 @@ import static org.mockito.BDDMockito.willCallRealMethod; * @author Madhura Bhave * @author Johnny Lim */ -public class ConfigurationPropertiesScanTests { +class ConfigurationPropertiesScanTests { private AnnotationConfigApplicationContext context; - @Before + @BeforeEach public void setup() { this.context = new AnnotationConfigApplicationContext(); } - @After + @AfterEach public void teardown() { if (this.context != null) { this.context.close(); @@ -53,7 +53,7 @@ public class ConfigurationPropertiesScanTests { } @Test - public void scanImportBeanRegistrarShouldBeEnvironmentAwareWithRequiredProfile() { + void scanImportBeanRegistrarShouldBeEnvironmentAwareWithRequiredProfile() { this.context.getEnvironment().addActiveProfile("test"); load(TestConfiguration.class); assertThat(this.context.containsBean( @@ -62,7 +62,7 @@ public class ConfigurationPropertiesScanTests { } @Test - public void scanImportBeanRegistrarShouldBeEnvironmentAwareWithoutRequiredProfile() { + void scanImportBeanRegistrarShouldBeEnvironmentAwareWithoutRequiredProfile() { load(TestConfiguration.class); assertThat(this.context.containsBean( "profile-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyProfileProperties")) @@ -70,7 +70,7 @@ public class ConfigurationPropertiesScanTests { } @Test - public void scanImportBeanRegistrarShouldBeResourceLoaderAwareWithRequiredResource() { + void scanImportBeanRegistrarShouldBeResourceLoaderAwareWithRequiredResource() { DefaultResourceLoader resourceLoader = Mockito.mock(DefaultResourceLoader.class); this.context.setResourceLoader(resourceLoader); willCallRealMethod().given(resourceLoader).getClassLoader(); @@ -82,7 +82,7 @@ public class ConfigurationPropertiesScanTests { } @Test - public void scanImportBeanRegistrarShouldBeResourceLoaderAwareWithoutRequiredResource() { + void scanImportBeanRegistrarShouldBeResourceLoaderAwareWithoutRequiredResource() { load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index d0bf7c493c9..c5f614da297 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java @@ -33,9 +33,9 @@ import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; @@ -50,7 +50,8 @@ import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.DefaultValue; import org.springframework.boot.context.properties.bind.validation.BindValidationException; import org.springframework.boot.convert.DataSizeUnit; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -103,14 +104,12 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Madhura Bhave */ -public class ConfigurationPropertiesTests { +@ExtendWith(OutputCaptureExtension.class) +class ConfigurationPropertiesTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @Rule - public OutputCapture output = new OutputCapture(); - - @After + @AfterEach public void cleanup() { this.context.close(); System.clearProperty("name"); @@ -119,7 +118,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldBind() { + void loadShouldBind() { load(BasicConfiguration.class, "name=foo"); assertThat(this.context.getBeanNamesForType(BasicProperties.class)).hasSize(1); assertThat(this.context.containsBean(BasicProperties.class.getName())).isTrue(); @@ -127,7 +126,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldBindNested() { + void loadShouldBindNested() { load(NestedConfiguration.class, "name=foo", "nested.name=bar"); assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); @@ -135,7 +134,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenUsingSystemPropertiesShouldBind() { + void loadWhenUsingSystemPropertiesShouldBind() { System.setProperty("name", "foo"); load(BasicConfiguration.class); assertThat(this.context.getBeanNamesForType(BasicProperties.class)).hasSize(1); @@ -143,7 +142,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenUsingSystemPropertiesShouldBindNested() { + void loadWhenUsingSystemPropertiesShouldBindNested() { System.setProperty("name", "foo"); System.setProperty("nested.name", "bar"); load(NestedConfiguration.class); @@ -153,7 +152,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasIgnoreUnknownFieldsFalseAndNoUnknownFieldsShouldBind() { + void loadWhenHasIgnoreUnknownFieldsFalseAndNoUnknownFieldsShouldBind() { removeSystemProperties(); load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo"); IgnoreUnknownFieldsFalseProperties bean = this.context.getBean(IgnoreUnknownFieldsFalseProperties.class); @@ -161,7 +160,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { + void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) @@ -169,42 +168,42 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasIgnoreInvalidFieldsTrueAndInvalidFieldsShouldBind() { + void loadWhenHasIgnoreInvalidFieldsTrueAndInvalidFieldsShouldBind() { load(IgnoreInvalidFieldsFalseProperties.class, "com.example.bar=spam"); IgnoreInvalidFieldsFalseProperties bean = this.context.getBean(IgnoreInvalidFieldsFalseProperties.class); assertThat(bean.getBar()).isEqualTo(0); } @Test - public void loadWhenHasPrefixShouldBind() { + void loadWhenHasPrefixShouldBind() { load(PrefixConfiguration.class, "spring.foo.name=foo"); PrefixProperties bean = this.context.getBean(PrefixProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test - public void loadWhenPropertiesHaveAnnotationOnBaseClassShouldBind() { + void loadWhenPropertiesHaveAnnotationOnBaseClassShouldBind() { load(AnnotationOnBaseClassConfiguration.class, "name=foo"); AnnotationOnBaseClassProperties bean = this.context.getBean(AnnotationOnBaseClassProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test - public void loadWhenBindingArrayShouldBind() { + void loadWhenBindingArrayShouldBind() { load(BasicConfiguration.class, "name=foo", "array=1,2,3"); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.array).containsExactly(1, 2, 3); } @Test - public void loadWhenBindingArrayFromYamlArrayShouldBind() { + void loadWhenBindingArrayFromYamlArrayShouldBind() { load(BasicConfiguration.class, "name=foo", "list[0]=1", "list[1]=2", "list[2]=3"); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.list).containsExactly(1, 2, 3); } @Test - public void loadWhenBindingOver256ElementsShouldBind() { + void loadWhenBindingOver256ElementsShouldBind() { List pairs = new ArrayList<>(); pairs.add("name:foo"); for (int i = 0; i < 1000; i++) { @@ -216,41 +215,41 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingWithoutAndAnnotationShouldFail() { + void loadWhenBindingWithoutAndAnnotationShouldFail() { assertThatIllegalArgumentException().isThrownBy(() -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) .withMessageContaining("No ConfigurationProperties annotation found"); } @Test - public void loadWhenBindingWithoutAnnotationValueShouldBind() { + void loadWhenBindingWithoutAnnotationValueShouldBind() { load(WithoutAnnotationValueConfiguration.class, "name=foo"); WithoutAnnotationValueProperties bean = this.context.getBean(WithoutAnnotationValueProperties.class); assertThat(bean.name).isEqualTo("foo"); } @Test - public void loadWhenBindingWithDefaultsInXmlShouldBind() { + void loadWhenBindingWithDefaultsInXmlShouldBind() { load(new Class[] { BasicConfiguration.class, DefaultsInXmlConfiguration.class }); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("bar"); } @Test - public void loadWhenBindingWithDefaultsInJavaConfigurationShouldBind() { + void loadWhenBindingWithDefaultsInJavaConfigurationShouldBind() { load(DefaultsInJavaConfiguration.class); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("bar"); } @Test - public void loadWhenBindingTwoBeansShouldBind() { + void loadWhenBindingTwoBeansShouldBind() { load(new Class[] { WithoutAnnotationValueConfiguration.class, BasicConfiguration.class }); assertThat(this.context.getBean(BasicProperties.class)).isNotNull(); assertThat(this.context.getBean(WithoutAnnotationValueProperties.class)).isNotNull(); } @Test - public void loadWhenBindingWithParentContextShouldBind() { + void loadWhenBindingWithParentContextShouldBind() { AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, "name=parent"); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); @@ -262,7 +261,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingOnlyParentContextShouldBind() { + void loadWhenBindingOnlyParentContextShouldBind() { AnnotationConfigApplicationContext parent = load(BasicConfiguration.class, "name=foo"); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); @@ -273,14 +272,14 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenPrefixedPropertiesDeclaredAsBeanShouldBind() { + void loadWhenPrefixedPropertiesDeclaredAsBeanShouldBind() { load(PrefixPropertiesDeclaredAsBeanConfiguration.class, "spring.foo.name=foo"); PrefixProperties bean = this.context.getBean(PrefixProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test - public void loadWhenPrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { + void loadWhenPrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { load(PrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, "spring.foo.name=foo"); PrefixProperties bean = this.context.getBean("spring.foo-" + PrefixProperties.class.getName(), PrefixProperties.class); @@ -288,7 +287,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenMultiplePrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { + void loadWhenMultiplePrefixedPropertiesDeclaredAsAnnotationValueShouldBind() { load(MultiplePrefixPropertiesDeclaredAsAnnotationValueConfiguration.class, "spring.foo.name=foo", "spring.bar.name=bar"); PrefixProperties bean1 = this.context.getBean(PrefixProperties.class); @@ -298,35 +297,35 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingToMapKeyWithPeriodShouldBind() { + void loadWhenBindingToMapKeyWithPeriodShouldBind() { load(MapProperties.class, "mymap.key1.key2:value12", "mymap.key3:value3"); MapProperties bean = this.context.getBean(MapProperties.class); assertThat(bean.mymap).containsOnly(entry("key3", "value3"), entry("key1.key2", "value12")); } @Test - public void loadWhenPrefixedPropertiesAreReplacedOnBeanMethodShouldBind() { + void loadWhenPrefixedPropertiesAreReplacedOnBeanMethodShouldBind() { load(PrefixedPropertiesReplacedOnBeanMethodConfiguration.class, "external.name=bar", "spam.name=foo"); PrefixProperties bean = this.context.getBean(PrefixProperties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test - public void loadShouldBindToJavaTimeDuration() { + void loadShouldBindToJavaTimeDuration() { load(BasicConfiguration.class, "duration=PT1M"); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.getDuration().getSeconds()).isEqualTo(60); } @Test - public void loadWhenBindingToValidatedImplementationOfInterfaceShouldBind() { + void loadWhenBindingToValidatedImplementationOfInterfaceShouldBind() { load(ValidatedImplementationConfiguration.class, "test.foo=bar"); ValidatedImplementationProperties bean = this.context.getBean(ValidatedImplementationProperties.class); assertThat(bean.getFoo()).isEqualTo("bar"); } @Test - public void loadWithPropertyPlaceholderValueShouldBind() { + void loadWithPropertyPlaceholderValueShouldBind() { load(WithPropertyPlaceholderValueConfiguration.class, "default.value=foo"); WithPropertyPlaceholderValueProperties bean = this.context .getBean(WithPropertyPlaceholderValueProperties.class); @@ -334,14 +333,14 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWithPropertyPlaceholderShouldNotAlterPropertySourceOrder() { + void loadWithPropertyPlaceholderShouldNotAlterPropertySourceOrder() { load(WithPropertyPlaceholderWithLocalPropertiesValueConfiguration.class, "com.example.bar=a"); SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getBar()).isEqualTo("a"); } @Test - public void loadWhenHasPostConstructShouldTriggerPostConstructWithBoundBean() { + void loadWhenHasPostConstructShouldTriggerPostConstructWithBoundBean() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("bar", "foo"); this.context.setEnvironment(environment); @@ -352,7 +351,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldNotInitializeFactoryBeans() { + void loadShouldNotInitializeFactoryBeans() { WithFactoryBeanConfiguration.factoryBeanInitialized = false; this.context = new AnnotationConfigApplicationContext() { @@ -373,7 +372,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenUsingRelaxedFormsShouldBindToEnum() { + void loadWhenUsingRelaxedFormsShouldBindToEnum() { bindToEnum("test.theValue=FOO"); bindToEnum("test.theValue=foo"); bindToEnum("test.the-value=FoO"); @@ -388,7 +387,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenUsingRelaxedFormsShouldBindToEnumSet() { + void loadWhenUsingRelaxedFormsShouldBindToEnumSet() { bindToEnumSet("test.the-values=foo,bar", FooEnum.FOO, FooEnum.BAR); bindToEnumSet("test.the-values=foo", FooEnum.FOO); } @@ -401,14 +400,14 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldBindToCharArray() { + void loadShouldBindToCharArray() { load(WithCharArrayProperties.class, "test.chars=word"); WithCharArrayProperties bean = this.context.getBean(WithCharArrayProperties.class); assertThat(bean.getChars()).isEqualTo("word".toCharArray()); } @Test - public void loadWhenUsingRelaxedFormsAndOverrideShouldBind() { + void loadWhenUsingRelaxedFormsAndOverrideShouldBind() { load(WithRelaxedNamesProperties.class, "test.FOO_BAR=test1", "test.FOO_BAR=test2", "test.BAR-B-A-Z=testa", "test.BAR-B-A-Z=testb"); WithRelaxedNamesProperties bean = this.context.getBean(WithRelaxedNamesProperties.class); @@ -417,21 +416,21 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldBindToMap() { + void loadShouldBindToMap() { load(WithMapProperties.class, "test.map.foo=bar"); WithMapProperties bean = this.context.getBean(WithMapProperties.class); assertThat(bean.getMap()).containsOnly(entry("foo", "bar")); } @Test - public void loadShouldBindToMapWithNumericKey() { + void loadShouldBindToMapWithNumericKey() { load(MapWithNumericKeyProperties.class, "sample.properties.1.name=One"); MapWithNumericKeyProperties bean = this.context.getBean(MapWithNumericKeyProperties.class); assertThat(bean.getProperties().get("1").name).isEqualTo("One"); } @Test - public void loadWhenUsingSystemPropertiesShouldBindToMap() { + void loadWhenUsingSystemPropertiesShouldBindToMap() { this.context.getEnvironment().getPropertySources().addLast( new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); @@ -442,7 +441,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenDotsInSystemEnvironmentPropertiesShouldBind() { + void loadWhenDotsInSystemEnvironmentPropertiesShouldBind() { this.context.getEnvironment().getPropertySources().addLast( new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("com.example.bar", "baz"))); @@ -452,7 +451,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenOverridingPropertiesShouldBind() { + void loadWhenOverridingPropertiesShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); sources.addFirst( new SystemEnvironmentPropertySource("system", Collections.singletonMap("SPRING_FOO_NAME", "Jane"))); @@ -463,55 +462,55 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { + void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) .withCauseInstanceOf(BindException.class); } @Test - public void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { + void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) .withCauseInstanceOf(BindException.class); } @Test - public void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { + void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) .withCauseInstanceOf(BindException.class); } @Test - public void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedButIsValidShouldFail() { + void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedButIsValidShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) .withCauseInstanceOf(BindException.class); } @Test - public void loadWhenJsr303ConstraintMatchesShouldBind() { + void loadWhenJsr303ConstraintMatchesShouldBind() { load(ValidatedJsr303Configuration.class, "description=foo"); ValidatedJsr303Properties bean = this.context.getBean(ValidatedJsr303Properties.class); assertThat(bean.getDescription()).isEqualTo("foo"); } @Test - public void loadWhenJsr303ConstraintDoesNotMatchAndNotValidatedAnnotationShouldBind() { + void loadWhenJsr303ConstraintDoesNotMatchAndNotValidatedAnnotationShouldBind() { load(NonValidatedJsr303Configuration.class, "name=foo"); NonValidatedJsr303Properties bean = this.context.getBean(NonValidatedJsr303Properties.class); assertThat(((BasicProperties) bean).name).isEqualTo("foo"); } @Test - public void loadWhenHasMultiplePropertySourcesPlaceholderConfigurerShouldLogWarning() { + void loadWhenHasMultiplePropertySourcesPlaceholderConfigurerShouldLogWarning(CapturedOutput capturedOutput) { load(MultiplePropertySourcesPlaceholderConfigurerConfiguration.class); - assertThat(this.output.toString()).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered"); + assertThat(capturedOutput).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered"); } @Test - public void loadWhenOverridingPropertiesWithPlaceholderResolutionInEnvironmentShouldBindWithOverride() { + void loadWhenOverridingPropertiesWithPlaceholderResolutionInEnvironmentShouldBindWithOverride() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); sources.addFirst( new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); @@ -525,7 +524,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasUnboundElementsFromSystemEnvironmentShouldNotThrowException() { + void loadWhenHasUnboundElementsFromSystemEnvironmentShouldNotThrowException() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); sources.addFirst(new MapPropertySource("test", Collections.singletonMap("com.example.foo", 5))); sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, @@ -536,7 +535,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldSupportRebindableConfigurationProperties() { + void loadShouldSupportRebindableConfigurationProperties() { // gh-9160 MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new LinkedHashMap<>(); @@ -554,7 +553,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasPropertySourcesPlaceholderConfigurerShouldSupportRebindableConfigurationProperties() { + void loadWhenHasPropertySourcesPlaceholderConfigurerShouldSupportRebindableConfigurationProperties() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new LinkedHashMap<>(); source.put("example.one", "foo"); @@ -572,7 +571,7 @@ public class ConfigurationPropertiesTests { } @Test - public void customProtocolResolverIsInvoked() { + void customProtocolResolverIsInvoked() { this.context = new AnnotationConfigApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.resource=application.properties"); ProtocolResolver protocolResolver = mock(ProtocolResolver.class); @@ -584,7 +583,7 @@ public class ConfigurationPropertiesTests { } @Test - public void customProtocolResolver() { + void customProtocolResolver() { this.context = new AnnotationConfigApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "test.resource=test:/application.properties"); @@ -599,7 +598,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldUseConfigurationConverter() { + void loadShouldUseConfigurationConverter() { prepareConverterContext(ConverterConfiguration.class, PersonProperties.class); Person person = this.context.getBean(PersonProperties.class).getPerson(); assertThat(person.firstName).isEqualTo("John"); @@ -607,7 +606,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { + void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class) .isThrownBy( () -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) @@ -615,7 +614,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadShouldUseGenericConfigurationConverter() { + void loadShouldUseGenericConfigurationConverter() { prepareConverterContext(GenericConverterConfiguration.class, PersonProperties.class); Person person = this.context.getBean(PersonProperties.class).getPerson(); assertThat(person.firstName).isEqualTo("John"); @@ -623,7 +622,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { + void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy( () -> prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, PersonProperties.class)) .withCauseInstanceOf(BindException.class); @@ -631,7 +630,7 @@ public class ConfigurationPropertiesTests { @Test @SuppressWarnings("rawtypes") - public void loadShouldBindToBeanWithGenerics() { + void loadShouldBindToBeanWithGenerics() { load(GenericConfiguration.class, "foo.bar=hello"); AGenericClass foo = this.context.getBean(AGenericClass.class); assertThat(foo.getBar()).isNotNull(); @@ -642,7 +641,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { + void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) .satisfies((ex) -> { assertThat(ex).hasCauseInstanceOf(BindException.class); @@ -651,7 +650,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasUnsupportedConfigurationPropertiesValidatorShouldBind() { + void loadWhenHasUnsupportedConfigurationPropertiesValidatorShouldBind() { load(WithUnsupportedCustomValidatorConfiguration.class, "test.foo=bar"); WithSetterThatThrowsValidationExceptionProperties bean = this.context .getBean(WithSetterThatThrowsValidationExceptionProperties.class); @@ -659,7 +658,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() { + void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() { assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(ValidatorProperties.class)).satisfies((ex) -> { assertThat(ex).hasCauseInstanceOf(BindException.class); assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); @@ -667,14 +666,14 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenSetterThrowsValidationExceptionShouldFail() { + void loadWhenSetterThrowsValidationExceptionShouldFail() { assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) .withCauseInstanceOf(BindException.class); } @Test - public void loadWhenFailsShouldIncludeAnnotationDetails() { + void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) @@ -684,7 +683,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenHasCustomPropertyEditorShouldBind() { + void loadWhenHasCustomPropertyEditorShouldBind() { this.context.getBeanFactory().registerCustomEditor(Person.class, PersonPropertyEditor.class); load(PersonProperties.class, "test.person=boot,spring"); PersonProperties bean = this.context.getBean(PersonProperties.class); @@ -693,7 +692,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingToListOfGenericClassShouldBind() { + void loadWhenBindingToListOfGenericClassShouldBind() { // gh-12166 load(ListOfGenericClassProperties.class, "test.list=java.lang.RuntimeException"); ListOfGenericClassProperties bean = this.context.getBean(ListOfGenericClassProperties.class); @@ -701,14 +700,14 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingCurrentDirectoryToFileShouldBind() { + void loadWhenBindingCurrentDirectoryToFileShouldBind() { load(FileProperties.class, "test.file=."); FileProperties bean = this.context.getBean(FileProperties.class); assertThat(bean.getFile()).isEqualTo(new File(".")); } @Test - public void loadWhenBindingToDataSizeShouldBind() { + void loadWhenBindingToDataSizeShouldBind() { load(DataSizeProperties.class, "test.size=10GB", "test.another-size=5"); DataSizeProperties bean = this.context.getBean(DataSizeProperties.class); assertThat(bean.getSize()).isEqualTo(DataSize.ofGigabytes(10)); @@ -716,12 +715,12 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenTopLevelConverterNotFoundExceptionShouldNotFail() { + void loadWhenTopLevelConverterNotFoundExceptionShouldNotFail() { load(PersonProperties.class, "test=boot"); } @Test - public void loadWhenConfigurationPropertiesContainsMapWithPositiveAndNegativeIntegerKeys() { + void loadWhenConfigurationPropertiesContainsMapWithPositiveAndNegativeIntegerKeys() { // gh-14136 MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new HashMap<>(); @@ -739,7 +738,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenConfigurationPropertiesInjectsAnotherBeanShouldNotFail() { + void loadWhenConfigurationPropertiesInjectsAnotherBeanShouldNotFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) .isThrownBy(() -> load(OtherInjectPropertiesConfiguration.class)) .withMessageContaining(OtherInjectedProperties.class.getName()) @@ -747,7 +746,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingToConstructorParametersShouldBind() { + void loadWhenBindingToConstructorParametersShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map source = new HashMap<>(); source.put("test.foo", "baz"); @@ -760,7 +759,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingToConstructorParametersWithDefaultValuesShouldBind() { + void loadWhenBindingToConstructorParametersWithDefaultValuesShouldBind() { load(ConstructorParameterConfiguration.class); ConstructorParameterProperties bean = this.context.getBean(ConstructorParameterProperties.class); assertThat(bean.getFoo()).isEqualTo("hello"); @@ -768,7 +767,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingToConstructorParametersShouldValidate() { + void loadWhenBindingToConstructorParametersShouldValidate() { assertThatExceptionOfType(Exception.class) .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)).satisfies((ex) -> { assertThat(ex).hasCauseInstanceOf(BindException.class); @@ -777,7 +776,7 @@ public class ConfigurationPropertiesTests { } @Test - public void loadWhenBindingOnBeanWithoutBeanDefinitionShouldBind() { + void loadWhenBindingOnBeanWithoutBeanDefinitionShouldBind() { load(BasicConfiguration.class, "name=test"); BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("test"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index 0861b238808..61be2605373 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.context.properties; import java.util.function.Supplier; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -29,49 +29,49 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class PropertyMapperTests { +class PropertyMapperTests { private PropertyMapper map = PropertyMapper.get(); @Test - public void fromNullValue() { + void fromNullValue() { ExampleDest dest = new ExampleDest(); this.map.from((String) null).to(dest::setName); assertThat(dest.getName()).isNull(); } @Test - public void fromValue() { + void fromValue() { ExampleDest dest = new ExampleDest(); this.map.from("Hello World").to(dest::setName); assertThat(dest.getName()).isEqualTo("Hello World"); } @Test - public void fromValueAsIntShouldAdaptValue() { + void fromValueAsIntShouldAdaptValue() { Integer result = this.map.from("123").asInt(Long::valueOf).toInstance(Integer::valueOf); assertThat(result).isEqualTo(123); } @Test - public void fromValueAlwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() { - this.map.alwaysApplyingWhenNonNull().from((String) null).toCall(Assert::fail); + void fromValueAlwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() { + this.map.alwaysApplyingWhenNonNull().from((String) null).toCall(Assertions::fail); } @Test - public void fromWhenSupplierIsNullShouldThrowException() { + void fromWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from((Supplier) null)) .withMessageContaining("Supplier must not be null"); } @Test - public void toWhenConsumerIsNullShouldThrowException() { + void toWhenConsumerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").to(null)) .withMessageContaining("Consumer must not be null"); } @Test - public void toShouldMapFromSupplier() { + void toShouldMapFromSupplier() { ExampleSource source = new ExampleSource("test"); ExampleDest dest = new ExampleDest(); this.map.from(source::getName).to(dest::setName); @@ -79,110 +79,110 @@ public class PropertyMapperTests { } @Test - public void asIntShouldAdaptSupplier() { + void asIntShouldAdaptSupplier() { Integer result = this.map.from(() -> "123").asInt(Long::valueOf).toInstance(Integer::valueOf); assertThat(result).isEqualTo(123); } @Test - public void asWhenAdapterIsNullShouldThrowException() { + void asWhenAdapterIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").as(null)) .withMessageContaining("Adapter must not be null"); } @Test - public void asShouldAdaptSupplier() { + void asShouldAdaptSupplier() { ExampleDest dest = new ExampleDest(); this.map.from(() -> 123).as(String::valueOf).to(dest::setName); assertThat(dest.getName()).isEqualTo("123"); } @Test - public void whenNonNullWhenSuppliedNullShouldNotMap() { - this.map.from(() -> null).whenNonNull().as(String::valueOf).toCall(Assert::fail); + void whenNonNullWhenSuppliedNullShouldNotMap() { + this.map.from(() -> null).whenNonNull().as(String::valueOf).toCall(Assertions::fail); } @Test - public void whenNonNullWhenSuppliedThrowsNullPointerExceptionShouldNotMap() { + void whenNonNullWhenSuppliedThrowsNullPointerExceptionShouldNotMap() { this.map.from(() -> { throw new NullPointerException(); - }).whenNonNull().as(String::valueOf).toCall(Assert::fail); + }).whenNonNull().as(String::valueOf).toCall(Assertions::fail); } @Test - public void whenTrueWhenValueIsTrueShouldMap() { + void whenTrueWhenValueIsTrueShouldMap() { Boolean result = this.map.from(true).whenTrue().toInstance(Boolean::valueOf); assertThat(result).isTrue(); } @Test - public void whenTrueWhenValueIsFalseShouldNotMap() { - this.map.from(false).whenTrue().toCall(Assert::fail); + void whenTrueWhenValueIsFalseShouldNotMap() { + this.map.from(false).whenTrue().toCall(Assertions::fail); } @Test - public void whenFalseWhenValueIsFalseShouldMap() { + void whenFalseWhenValueIsFalseShouldMap() { Boolean result = this.map.from(false).whenFalse().toInstance(Boolean::valueOf); assertThat(result).isFalse(); } @Test - public void whenFalseWhenValueIsTrueShouldNotMap() { - this.map.from(true).whenFalse().toCall(Assert::fail); + void whenFalseWhenValueIsTrueShouldNotMap() { + this.map.from(true).whenFalse().toCall(Assertions::fail); } @Test - public void whenHasTextWhenValueIsNullShouldNotMap() { - this.map.from(() -> null).whenHasText().toCall(Assert::fail); + void whenHasTextWhenValueIsNullShouldNotMap() { + this.map.from(() -> null).whenHasText().toCall(Assertions::fail); } @Test - public void whenHasTextWhenValueIsEmptyShouldNotMap() { - this.map.from("").whenHasText().toCall(Assert::fail); + void whenHasTextWhenValueIsEmptyShouldNotMap() { + this.map.from("").whenHasText().toCall(Assertions::fail); } @Test - public void whenHasTextWhenValueHasTextShouldMap() { + void whenHasTextWhenValueHasTextShouldMap() { Integer result = this.map.from(123).whenHasText().toInstance(Integer::valueOf); assertThat(result).isEqualTo(123); } @Test - public void whenEqualToWhenValueIsEqualShouldMatch() { + void whenEqualToWhenValueIsEqualShouldMatch() { String result = this.map.from("123").whenEqualTo("123").toInstance(String::new); assertThat(result).isEqualTo("123"); } @Test - public void whenEqualToWhenValueIsNotEqualShouldNotMatch() { - this.map.from("123").whenEqualTo("321").toCall(Assert::fail); + void whenEqualToWhenValueIsNotEqualShouldNotMatch() { + this.map.from("123").whenEqualTo("321").toCall(Assertions::fail); } @Test - public void whenInstanceOfWhenValueIsTargetTypeShouldMatch() { + void whenInstanceOfWhenValueIsTargetTypeShouldMatch() { Long result = this.map.from(123L).whenInstanceOf(Long.class).toInstance((value) -> value + 1); assertThat(result).isEqualTo(124L); } @Test - public void whenInstanceOfWhenValueIsNotTargetTypeShouldNotMatch() { + void whenInstanceOfWhenValueIsNotTargetTypeShouldNotMatch() { Supplier supplier = () -> 123L; - this.map.from(supplier).whenInstanceOf(Double.class).toCall(Assert::fail); + this.map.from(supplier).whenInstanceOf(Double.class).toCall(Assertions::fail); } @Test - public void whenWhenValueMatchesShouldMap() { + void whenWhenValueMatchesShouldMap() { String result = this.map.from("123").when("123"::equals).toInstance(String::new); assertThat(result).isEqualTo("123"); } @Test - public void whenWhenValueDoesNotMatchShouldNotMap() { - this.map.from("123").when("321"::equals).toCall(Assert::fail); + void whenWhenValueDoesNotMatchShouldNotMap() { + this.map.from("123").when("321"::equals).toCall(Assertions::fail); } @Test - public void whenWhenCombinedWithAsUsesSourceValue() { + void whenWhenCombinedWithAsUsesSourceValue() { Count source = new Count<>(() -> "123"); Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf).when((v) -> v == 123) .as(Integer::longValue).toInstance(Long::valueOf); @@ -191,8 +191,8 @@ public class PropertyMapperTests { } @Test - public void alwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() { - this.map.alwaysApplyingWhenNonNull().from(() -> null).toCall(Assert::fail); + void alwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() { + this.map.alwaysApplyingWhenNonNull().from(() -> null).toCall(Assertions::fail); } private static class Count implements Supplier { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java index 9bb5df3e055..5882c4a9494 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java @@ -20,8 +20,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.InOrder; @@ -45,7 +44,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class ArrayBinderTests { +class ArrayBinderTests { private static final Bindable> INTEGER_LIST = Bindable.listOf(Integer.class); @@ -53,15 +52,10 @@ public class ArrayBinderTests { private List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private final Binder binder = new Binder(this.sources); @Test - public void bindToArrayShouldReturnArray() { + void bindToArrayShouldReturnArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "1"); source.put("foo[1]", "2"); @@ -72,7 +66,7 @@ public class ArrayBinderTests { } @Test - public void bindToCollectionShouldTriggerOnSuccess() { + void bindToCollectionShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); this.binder.bind("foo", INTEGER_LIST, handler); @@ -84,7 +78,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayShouldReturnPrimitiveArray() { + void bindToArrayShouldReturnPrimitiveArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "1"); source.put("foo[1]", "2"); @@ -95,7 +89,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNestedShouldReturnPopulatedArray() { + void bindToArrayWhenNestedShouldReturnPopulatedArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0][0]", "1"); source.put("foo[0][1]", "2"); @@ -111,7 +105,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNestedListShouldReturnPopulatedArray() { + void bindToArrayWhenNestedListShouldReturnPopulatedArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0][0]", "1"); source.put("foo[0][1]", "2"); @@ -127,7 +121,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNotInOrderShouldReturnPopulatedArray() { + void bindToArrayWhenNotInOrderShouldReturnPopulatedArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[1]", "2"); source.put("foo[0]", "1"); @@ -138,7 +132,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNonSequentialShouldThrowException() { + void bindToArrayWhenNonSequentialShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "2"); source.put("foo[1]", "1"); @@ -156,7 +150,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNonIterableShouldReturnPopulatedArray() { + void bindToArrayWhenNonIterableShouldReturnPopulatedArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[1]", "2"); source.put("foo[0]", "1"); @@ -167,7 +161,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenMultipleSourceShouldOnlyUseFirst() { + void bindToArrayWhenMultipleSourceShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("bar", "baz"); this.sources.add(source1); @@ -185,7 +179,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenHasExistingCollectionShouldReplaceAllContents() { + void bindToArrayWhenHasExistingCollectionShouldReplaceAllContents() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1")); Integer[] existing = new Integer[2]; existing[0] = 1000; @@ -195,14 +189,14 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenNoValueShouldReturnUnbound() { + void bindToArrayWhenNoValueShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource("faf.bar", "1")); BindResult result = this.binder.bind("foo", INTEGER_ARRAY); assertThat(result.isBound()).isFalse(); } @Test - public void bindToArrayShouldTriggerOnSuccess() { + void bindToArrayShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable target = INTEGER_ARRAY; @@ -215,14 +209,14 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenCommaListShouldReturnPopulatedArray() { + void bindToArrayWhenCommaListShouldReturnPopulatedArray() { this.sources.add(new MockConfigurationPropertySource("foo", "1,2,3")); int[] result = this.binder.bind("foo", Bindable.of(int[].class)).get(); assertThat(result).containsExactly(1, 2, 3); } @Test - public void bindToArrayWhenCommaListAndIndexedShouldOnlyUseFirst() { + void bindToArrayWhenCommaListAndIndexedShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("foo", "1,2"); this.sources.add(source1); @@ -234,7 +228,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenIndexedAndCommaListShouldOnlyUseFirst() { + void bindToArrayWhenIndexedAndCommaListShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("foo[0]", "1"); source1.put("foo[1]", "2"); @@ -246,14 +240,14 @@ public class ArrayBinderTests { } @Test - public void bindToArrayShouldBindCharArray() { + void bindToArrayShouldBindCharArray() { this.sources.add(new MockConfigurationPropertySource("foo", "word")); char[] result = this.binder.bind("foo", Bindable.of(char[].class)).get(); assertThat(result).containsExactly("word".toCharArray()); } @Test - public void bindToArrayWhenEmptyStringShouldReturnEmptyArray() { + void bindToArrayWhenEmptyStringShouldReturnEmptyArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", ""); this.sources.add(source); @@ -262,7 +256,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenHasSpacesShouldTrim() { + void bindToArrayWhenHasSpacesShouldTrim() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "1, 2,3"); this.sources.add(source); @@ -271,7 +265,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayShouldUsePropertyEditor() { + void bindToArrayShouldUsePropertyEditor() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "java.lang.RuntimeException"); @@ -282,7 +276,7 @@ public class ArrayBinderTests { } @Test - public void bindToArrayWhenStringShouldUsePropertyEditor() { + void bindToArrayWhenStringShouldUsePropertyEditor() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "java.lang.RuntimeException,java.lang.IllegalStateException"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java index f82d5be1b3b..c43335ba107 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.context.properties.bind; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.SystemEnvironmentPropertySource; @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class BackCompatibilityBinderIntegrationTests { +class BackCompatibilityBinderIntegrationTests { @Test - public void bindWhenBindingCamelCaseToEnvironmentWithExtractUnderscore() { + void bindWhenBindingCamelCaseToEnvironmentWithExtractUnderscore() { // gh-10873 MockEnvironment environment = new MockEnvironment(); SystemEnvironmentPropertySource propertySource = new SystemEnvironmentPropertySource( @@ -48,7 +48,7 @@ public class BackCompatibilityBinderIntegrationTests { } @Test - public void bindWhenUsingSystemEnvironmentToOverride() { + void bindWhenUsingSystemEnvironmentToOverride() { MockEnvironment environment = new MockEnvironment(); SystemEnvironmentPropertySource propertySource = new SystemEnvironmentPropertySource("override", Collections.singletonMap("foo.password", "test")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BeanPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BeanPropertyNameTests.java index 226e015406a..398241ae761 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BeanPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BeanPropertyNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.bind; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class BeanPropertyNameTests { +class BeanPropertyNameTests { @Test - public void toDashedCaseShouldConvertValue() { + void toDashedCaseShouldConvertValue() { assertThat(BeanPropertyName.toDashedForm("Foo")).isEqualTo("foo"); assertThat(BeanPropertyName.toDashedForm("foo")).isEqualTo("foo"); assertThat(BeanPropertyName.toDashedForm("fooBar")).isEqualTo("foo-bar"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java index c71e941772b..702a50a0ac8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java @@ -22,8 +22,8 @@ import java.time.Duration; import java.util.List; import java.util.function.Consumer; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -48,100 +48,100 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Andy Wilkinson */ -public class BindConverterTests { +class BindConverterTests { @Mock private Consumer propertyEditorInitializer; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void createWhenConversionServiceIsNullShouldThrowException() { + void createWhenConversionServiceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> BindConverter.get(null, null)) .withMessageContaining("ConversionService must not be null"); } @Test - public void createWhenPropertyEditorInitializerIsNullShouldCreate() { + void createWhenPropertyEditorInitializerIsNullShouldCreate() { BindConverter.get(ApplicationConversionService.getSharedInstance(), null); } @Test - public void createWhenPropertyEditorInitializerIsNotNullShouldUseToInitialize() { + void createWhenPropertyEditorInitializerIsNotNullShouldUseToInitialize() { BindConverter.get(ApplicationConversionService.getSharedInstance(), this.propertyEditorInitializer); verify(this.propertyEditorInitializer).accept(any(PropertyEditorRegistry.class)); } @Test - public void canConvertWhenHasDefaultEditorShouldReturnTrue() { + void canConvertWhenHasDefaultEditorShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); assertThat(bindConverter.canConvert("java.lang.RuntimeException", ResolvableType.forClass(Class.class))) .isTrue(); } @Test - public void canConvertWhenHasCustomEditorShouldReturnTrue() { + void canConvertWhenHasCustomEditorShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isTrue(); } @Test - public void canConvertWhenHasEditorByConventionShouldReturnTrue() { + void canConvertWhenHasEditorByConventionShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); assertThat(bindConverter.canConvert("test", ResolvableType.forClass(ConventionType.class))).isTrue(); } @Test - public void canConvertWhenHasEditorForCollectionElementShouldReturnTrue() { + void canConvertWhenHasEditorForCollectionElementShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); assertThat(bindConverter.canConvert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class))) .isTrue(); } @Test - public void canConvertWhenHasEditorForArrayElementShouldReturnTrue() { + void canConvertWhenHasEditorForArrayElementShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType[].class))).isTrue(); } @Test - public void canConvertWhenConversionServiceCanConvertShouldReturnTrue() { + void canConvertWhenConversionServiceCanConvertShouldReturnTrue() { BindConverter bindConverter = getBindConverter(new SampleTypeConverter()); assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isTrue(); } @Test - public void canConvertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldReturnFalse() { + void canConvertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldReturnFalse() { BindConverter bindConverter = BindConverter.get(ApplicationConversionService.getSharedInstance(), null); assertThat(bindConverter.canConvert("test", ResolvableType.forClass(SampleType.class))).isFalse(); } @Test - public void convertWhenHasDefaultEditorShouldConvert() { + void convertWhenHasDefaultEditorShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); Class converted = bindConverter.convert("java.lang.RuntimeException", ResolvableType.forClass(Class.class)); assertThat(converted).isEqualTo(RuntimeException.class); } @Test - public void convertWhenHasCustomEditorShouldConvert() { + void convertWhenHasCustomEditorShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); SampleType converted = bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test - public void convertWhenHasEditorByConventionShouldConvert() { + void convertWhenHasEditorByConventionShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); ConventionType converted = bindConverter.convert("test", ResolvableType.forClass(ConventionType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test - public void convertWhenHasEditorForCollectionElementShouldConvert() { + void convertWhenHasEditorForCollectionElementShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); List converted = bindConverter.convert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class)); @@ -150,7 +150,7 @@ public class BindConverterTests { } @Test - public void convertWhenHasEditorForArrayElementShouldConvert() { + void convertWhenHasEditorForArrayElementShouldConvert() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); SampleType[] converted = bindConverter.convert("test", ResolvableType.forClass(SampleType[].class)); assertThat(converted).isNotEmpty(); @@ -158,21 +158,21 @@ public class BindConverterTests { } @Test - public void convertWhenConversionServiceCanConvertShouldConvert() { + void convertWhenConversionServiceCanConvertShouldConvert() { BindConverter bindConverter = getBindConverter(new SampleTypeConverter()); SampleType converted = bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); assertThat(converted.getText()).isEqualTo("test"); } @Test - public void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { + void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { BindConverter bindConverter = BindConverter.get(ApplicationConversionService.getSharedInstance(), null); assertThatExceptionOfType(ConverterNotFoundException.class) .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); } @Test - public void convertWhenConvertingToFileShouldExcludeFileEditor() { + void convertWhenConvertingToFileShouldExcludeFileEditor() { // For back compatibility we want true file conversion and not an accidental // classpath resource reference. See gh-12163 BindConverter bindConverter = BindConverter.get(new GenericConversionService(), null); @@ -181,7 +181,7 @@ public class BindConverterTests { } @Test - public void fallsBackToApplicationConversionService() { + void fallsBackToApplicationConversionService() { BindConverter bindConverter = BindConverter.get(new GenericConversionService(), null); Duration result = bindConverter.convert("10s", ResolvableType.forClass(Duration.class)); assertThat(result.getSeconds()).isEqualTo(10); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java index 6cad4172c62..c7c77358cd5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java @@ -22,8 +22,8 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -41,7 +41,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Phillip Webb * @author Madhura Bhave */ -public class BindResultTests { +class BindResultTests { @Mock private Consumer consumer; @@ -52,137 +52,137 @@ public class BindResultTests { @Mock private Supplier supplier; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void getWhenHasValueShouldReturnValue() { + void getWhenHasValueShouldReturnValue() { BindResult result = BindResult.of("foo"); assertThat(result.get()).isEqualTo("foo"); } @Test - public void getWhenHasNoValueShouldThrowException() { + void getWhenHasNoValueShouldThrowException() { BindResult result = BindResult.of(null); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(result::get) .withMessageContaining("No value bound"); } @Test - public void isBoundWhenHasValueShouldReturnTrue() { + void isBoundWhenHasValueShouldReturnTrue() { BindResult result = BindResult.of("foo"); assertThat(result.isBound()).isTrue(); } @Test - public void isBoundWhenHasNoValueShouldFalse() { + void isBoundWhenHasNoValueShouldFalse() { BindResult result = BindResult.of(null); assertThat(result.isBound()).isFalse(); } @Test - public void ifBoundWhenConsumerIsNullShouldThrowException() { + void ifBoundWhenConsumerIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.ifBound(null)) .withMessageContaining("Consumer must not be null"); } @Test - public void ifBoundWhenHasValueShouldCallConsumer() { + void ifBoundWhenHasValueShouldCallConsumer() { BindResult result = BindResult.of("foo"); result.ifBound(this.consumer); verify(this.consumer).accept("foo"); } @Test - public void ifBoundWhenHasNoValueShouldNotCallConsumer() { + void ifBoundWhenHasNoValueShouldNotCallConsumer() { BindResult result = BindResult.of(null); result.ifBound(this.consumer); verifyZeroInteractions(this.consumer); } @Test - public void mapWhenMapperIsNullShouldThrowException() { + void mapWhenMapperIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.map(null)) .withMessageContaining("Mapper must not be null"); } @Test - public void mapWhenHasValueShouldCallMapper() { + void mapWhenHasValueShouldCallMapper() { BindResult result = BindResult.of("foo"); given(this.mapper.apply("foo")).willReturn("bar"); assertThat(result.map(this.mapper).get()).isEqualTo("bar"); } @Test - public void mapWhenHasNoValueShouldNotCallMapper() { + void mapWhenHasNoValueShouldNotCallMapper() { BindResult result = BindResult.of(null); result.map(this.mapper); verifyZeroInteractions(this.mapper); } @Test - public void orElseWhenHasValueShouldReturnValue() { + void orElseWhenHasValueShouldReturnValue() { BindResult result = BindResult.of("foo"); assertThat(result.orElse("bar")).isEqualTo("foo"); } @Test - public void orElseWhenHasValueNoShouldReturnOther() { + void orElseWhenHasValueNoShouldReturnOther() { BindResult result = BindResult.of(null); assertThat(result.orElse("bar")).isEqualTo("bar"); } @Test - public void orElseGetWhenHasValueShouldReturnValue() { + void orElseGetWhenHasValueShouldReturnValue() { BindResult result = BindResult.of("foo"); assertThat(result.orElseGet(this.supplier)).isEqualTo("foo"); verifyZeroInteractions(this.supplier); } @Test - public void orElseGetWhenHasValueNoShouldReturnOther() { + void orElseGetWhenHasValueNoShouldReturnOther() { BindResult result = BindResult.of(null); given(this.supplier.get()).willReturn("bar"); assertThat(result.orElseGet(this.supplier)).isEqualTo("bar"); } @Test - public void orElseCreateWhenTypeIsNullShouldThrowException() { + void orElseCreateWhenTypeIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.orElseCreate(null)) .withMessageContaining("Type must not be null"); } @Test - public void orElseCreateWhenHasValueShouldReturnValue() { + void orElseCreateWhenHasValueShouldReturnValue() { BindResult result = BindResult.of(new ExampleBean("foo")); assertThat(result.orElseCreate(ExampleBean.class).getValue()).isEqualTo("foo"); } @Test - public void orElseCreateWhenHasValueNoShouldReturnCreatedValue() { + void orElseCreateWhenHasValueNoShouldReturnCreatedValue() { BindResult result = BindResult.of(null); assertThat(result.orElseCreate(ExampleBean.class).getValue()).isEqualTo("new"); } @Test - public void orElseThrowWhenHasValueShouldReturnValue() throws Exception { + void orElseThrowWhenHasValueShouldReturnValue() throws Exception { BindResult result = BindResult.of("foo"); assertThat(result.orElseThrow(IOException::new)).isEqualTo("foo"); } @Test - public void orElseThrowWhenHasNoValueShouldThrowException() throws Exception { + void orElseThrowWhenHasNoValueShouldThrowException() throws Exception { BindResult result = BindResult.of(null); assertThatIOException().isThrownBy(() -> result.orElseThrow(IOException::new)); } @Test - public void hashCodeAndEquals() { + void hashCodeAndEquals() { BindResult result1 = BindResult.of("foo"); BindResult result2 = BindResult.of("foo"); BindResult result3 = BindResult.of("bar"); @@ -192,14 +192,14 @@ public class BindResultTests { } @Test - public void ofWhenHasValueShouldReturnBoundResultOfValue() { + void ofWhenHasValueShouldReturnBoundResultOfValue() { BindResult result = BindResult.of("foo"); assertThat(result.isBound()).isTrue(); assertThat(result.get()).isEqualTo("foo"); } @Test - public void ofWhenValueIsNullShouldReturnUnbound() { + void ofWhenValueIsNullShouldReturnUnbound() { BindResult result = BindResult.of(null); assertThat(result.isBound()).isFalse(); assertThat(result).isSameAs(BindResult.of(null)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java index 48be7b3f8dc..5c93e884b73 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java @@ -20,7 +20,7 @@ import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Bean; import org.springframework.core.ResolvableType; @@ -36,33 +36,33 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class BindableTests { +class BindableTests { @Test - public void ofClassWhenTypeIsNullShouldThrowException() { + void ofClassWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((Class) null)) .withMessageContaining("Type must not be null"); } @Test - public void ofTypeWhenTypeIsNullShouldThrowException() { + void ofTypeWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((ResolvableType) null)) .withMessageContaining("Type must not be null"); } @Test - public void ofClassShouldSetType() { + void ofClassShouldSetType() { assertThat(Bindable.of(String.class).getType()).isEqualTo(ResolvableType.forClass(String.class)); } @Test - public void ofTypeShouldSetType() { + void ofTypeShouldSetType() { ResolvableType type = ResolvableType.forClass(String.class); assertThat(Bindable.of(type).getType()).isEqualTo(type); } @Test - public void ofInstanceShouldSetTypeAndExistingValue() { + void ofInstanceShouldSetTypeAndExistingValue() { String instance = "foo"; ResolvableType type = ResolvableType.forClass(String.class); assertThat(Bindable.ofInstance(instance).getType()).isEqualTo(type); @@ -70,45 +70,45 @@ public class BindableTests { } @Test - public void ofClassWithExistingValueShouldSetTypeAndExistingValue() { + void ofClassWithExistingValueShouldSetTypeAndExistingValue() { assertThat(Bindable.of(String.class).withExistingValue("foo").getValue().get()).isEqualTo("foo"); } @Test - public void ofTypeWithExistingValueShouldSetTypeAndExistingValue() { + void ofTypeWithExistingValueShouldSetTypeAndExistingValue() { assertThat(Bindable.of(ResolvableType.forClass(String.class)).withExistingValue("foo").getValue().get()) .isEqualTo("foo"); } @Test - public void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { + void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); } @Test - public void ofTypeWhenPrimitiveWithExistingValueWrapperShouldNotThrowException() { + void ofTypeWhenPrimitiveWithExistingValueWrapperShouldNotThrowException() { Bindable bindable = Bindable.of(ResolvableType.forClass(int.class)).withExistingValue(123); assertThat(bindable.getType().resolve()).isEqualTo(int.class); assertThat(bindable.getValue().get()).isEqualTo(123); } @Test - public void getBoxedTypeWhenNotBoxedShouldReturnType() { + void getBoxedTypeWhenNotBoxedShouldReturnType() { Bindable bindable = Bindable.of(String.class); assertThat(bindable.getBoxedType()).isEqualTo(ResolvableType.forClass(String.class)); } @Test - public void getBoxedTypeWhenPrimitiveShouldReturnBoxedType() { + void getBoxedTypeWhenPrimitiveShouldReturnBoxedType() { Bindable bindable = Bindable.of(int.class); assertThat(bindable.getType()).isEqualTo(ResolvableType.forClass(int.class)); assertThat(bindable.getBoxedType()).isEqualTo(ResolvableType.forClass(Integer.class)); } @Test - public void getBoxedTypeWhenPrimitiveArrayShouldReturnBoxedType() { + void getBoxedTypeWhenPrimitiveArrayShouldReturnBoxedType() { Bindable bindable = Bindable.of(int[].class); assertThat(bindable.getType().getComponentType()).isEqualTo(ResolvableType.forClass(int.class)); assertThat(bindable.getBoxedType().isArray()).isTrue(); @@ -116,31 +116,31 @@ public class BindableTests { } @Test - public void getAnnotationsShouldReturnEmptyArray() { + void getAnnotationsShouldReturnEmptyArray() { assertThat(Bindable.of(String.class).getAnnotations()).isEmpty(); } @Test - public void withAnnotationsShouldSetAnnotations() { + void withAnnotationsShouldSetAnnotations() { Annotation annotation = mock(Annotation.class); assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotations()).containsExactly(annotation); } @Test - public void getAnnotationWhenMatchShouldReturnAnnotation() { + void getAnnotationWhenMatchShouldReturnAnnotation() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Test.class)) .isSameAs(annotation); } @Test - public void getAnnotationWhenNoMatchShouldReturnNull() { + void getAnnotationWhenNoMatchShouldReturnNull() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Bean.class)).isNull(); } @Test - public void toStringShouldShowDetails() { + void toStringShouldShowDetails() { Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); Bindable bindable = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); System.out.println(bindable.toString()); @@ -150,7 +150,7 @@ public class BindableTests { } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); Bindable bindable1 = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); Bindable bindable2 = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java index 0be36681c77..af0a01b37d0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java @@ -26,8 +26,7 @@ import java.util.Map; import javax.validation.Validation; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.InOrder; @@ -63,52 +62,47 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class BinderTests { +class BinderTests { - private List sources = new ArrayList<>(); + private final List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private Binder binder = new Binder(this.sources); @Test - public void createWhenSourcesIsNullShouldThrowException() { + void createWhenSourcesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder((Iterable) null)) .withMessageContaining("Sources must not be null"); } @Test - public void bindWhenNameIsNullShouldThrowException() { + void bindWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), BindHandler.DEFAULT)).withMessageContaining("Name must not be null"); } @Test - public void bindWhenTargetIsNullShouldThrowException() { + void bindWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) .withMessageContaining("Target must not be null"); } @Test - public void bindToValueWhenPropertyIsMissingShouldReturnUnbound() { + void bindToValueWhenPropertyIsMissingShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource()); BindResult result = this.binder.bind("foo", Bindable.of(String.class)); assertThat(result.isBound()).isFalse(); } @Test - public void bindToValueShouldReturnPropertyValue() { + void bindToValueShouldReturnPropertyValue() { this.sources.add(new MockConfigurationPropertySource("foo", 123)); BindResult result = this.binder.bind("foo", Bindable.of(Integer.class)); assertThat(result.get()).isEqualTo(123); } @Test - public void bindToValueShouldReturnPropertyValueFromSecondSource() { + void bindToValueShouldReturnPropertyValueFromSecondSource() { this.sources.add(new MockConfigurationPropertySource("foo", 123)); this.sources.add(new MockConfigurationPropertySource("bar", 234)); BindResult result = this.binder.bind("bar", Bindable.of(Integer.class)); @@ -116,14 +110,14 @@ public class BinderTests { } @Test - public void bindToValueShouldReturnConvertedPropertyValue() { + void bindToValueShouldReturnConvertedPropertyValue() { this.sources.add(new MockConfigurationPropertySource("foo", "123")); BindResult result = this.binder.bind("foo", Bindable.of(Integer.class)); assertThat(result.get()).isEqualTo(123); } @Test - public void bindToValueWhenMultipleCandidatesShouldReturnFirst() { + void bindToValueWhenMultipleCandidatesShouldReturnFirst() { this.sources.add(new MockConfigurationPropertySource("foo", 123)); this.sources.add(new MockConfigurationPropertySource("foo", 234)); BindResult result = this.binder.bind("foo", Bindable.of(Integer.class)); @@ -131,7 +125,7 @@ public class BinderTests { } @Test - public void bindToValueWithPlaceholdersShouldResolve() { + void bindToValueWithPlaceholdersShouldResolve() { StandardEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "bar=23"); this.sources.add(new MockConfigurationPropertySource("foo", "1${bar}")); @@ -141,7 +135,7 @@ public class BinderTests { } @Test - public void bindToValueWithMissingPlaceholderShouldResolveToValueWithPlaceholder() { + void bindToValueWithMissingPlaceholderShouldResolveToValueWithPlaceholder() { StandardEnvironment environment = new StandardEnvironment(); this.sources.add(new MockConfigurationPropertySource("foo", "${bar}")); this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); @@ -150,7 +144,7 @@ public class BinderTests { } @Test - public void bindToValueWithCustomPropertyEditorShouldReturnConvertedValue() { + void bindToValueWithCustomPropertyEditorShouldReturnConvertedValue() { this.binder = new Binder(this.sources, null, null, (registry) -> registry.registerCustomEditor(JavaBean.class, new JavaBeanPropertyEditor())); this.sources.add(new MockConfigurationPropertySource("foo", "123")); @@ -159,7 +153,7 @@ public class BinderTests { } @Test - public void bindToValueShouldTriggerOnSuccess() { + void bindToValueShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo", "1", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable target = Bindable.of(Integer.class); @@ -169,14 +163,14 @@ public class BinderTests { } @Test - public void bindToJavaBeanShouldReturnPopulatedBean() { + void bindToJavaBeanShouldReturnPopulatedBean() { this.sources.add(new MockConfigurationPropertySource("foo.value", "bar")); JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get(); assertThat(result.getValue()).isEqualTo("bar"); } @Test - public void bindToJavaBeanWhenNonIterableShouldReturnPopulatedBean() { + void bindToJavaBeanWhenNonIterableShouldReturnPopulatedBean() { MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.value", "bar"); this.sources.add(source.nonIterable()); JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get(); @@ -184,7 +178,7 @@ public class BinderTests { } @Test - public void bindToJavaBeanWhenHasPropertyWithSameNameShouldStillBind() { + void bindToJavaBeanWhenHasPropertyWithSameNameShouldStillBind() { // gh-10945 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "boom"); @@ -195,7 +189,7 @@ public class BinderTests { } @Test - public void bindToJavaBeanShouldTriggerOnSuccess() { + void bindToJavaBeanShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo.value", "bar", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable target = Bindable.of(JavaBean.class); @@ -208,7 +202,7 @@ public class BinderTests { } @Test - public void bindWhenHasMalformedDateShouldThrowException() { + void bindWhenHasMalformedDateShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) @@ -216,7 +210,7 @@ public class BinderTests { } @Test - public void bindWhenHasAnnotationsShouldChangeConvertedValue() { + void bindWhenHasAnnotationsShouldChangeConvertedValue() { this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); DateTimeFormat annotation = AnnotationUtils.synthesizeAnnotation( Collections.singletonMap("iso", DateTimeFormat.ISO.DATE_TIME), DateTimeFormat.class, null); @@ -225,7 +219,7 @@ public class BinderTests { } @Test - public void bindExceptionWhenBeanBindingFailsShouldHaveNullConfigurationProperty() { + void bindExceptionWhenBeanBindingFailsShouldHaveNullConfigurationProperty() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "hello"); source.put("foo.items", "bar,baz"); @@ -241,7 +235,7 @@ public class BinderTests { } @Test - public void bindToValidatedBeanWithResourceAndNonEnumerablePropertySource() { + void bindToValidatedBeanWithResourceAndNonEnumerablePropertySource() { ConfigurationPropertySources.from(new PropertySource("test") { @Override @@ -256,7 +250,7 @@ public class BinderTests { } @Test - public void bindToBeanWithCycle() { + void bindToBeanWithCycle() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); this.sources.add(source.nonIterable()); Bindable target = Bindable.of(CycleBean1.class); @@ -265,7 +259,7 @@ public class BinderTests { @Test @SuppressWarnings("rawtypes") - public void bindToBeanWithUnresolvableGenerics() { + void bindToBeanWithUnresolvableGenerics() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "hello"); this.sources.add(source); @@ -274,7 +268,7 @@ public class BinderTests { } @Test - public void bindWithEmptyPrefixShouldIgnorePropertiesWithEmptyName() { + void bindWithEmptyPrefixShouldIgnorePropertiesWithEmptyName() { Map source = new HashMap<>(); source.put("value", "hello"); source.put("", "bar"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java index e31ee99826e..c2022252c53 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java @@ -25,8 +25,7 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.BinderTests.ExampleEnum; import org.springframework.boot.context.properties.bind.BinderTests.JavaBean; @@ -46,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Madhura Bhave */ -public class CollectionBinderTests { +class CollectionBinderTests { private static final Bindable> INTEGER_LIST = Bindable.listOf(Integer.class); @@ -54,17 +53,12 @@ public class CollectionBinderTests { private static final Bindable> STRING_SET = Bindable.setOf(String.class); - private List sources = new ArrayList<>(); + private final List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private Binder binder = new Binder(this.sources); @Test - public void bindToCollectionShouldReturnPopulatedCollection() { + void bindToCollectionShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "1"); source.put("foo[1]", "2"); @@ -75,7 +69,7 @@ public class CollectionBinderTests { } @Test - public void bindToSetShouldReturnPopulatedCollection() { + void bindToSetShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "a"); source.put("foo[1]", "b"); @@ -86,7 +80,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenNestedShouldReturnPopulatedCollection() { + void bindToCollectionWhenNestedShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0][0]", "1"); source.put("foo[0][1]", "2"); @@ -102,7 +96,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenNotInOrderShouldReturnPopulatedCollection() { + void bindToCollectionWhenNotInOrderShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[1]", "2"); source.put("foo[0]", "1"); @@ -113,7 +107,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenNonSequentialShouldThrowException() { + void bindToCollectionWhenNonSequentialShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "2"); source.put("foo[1]", "1"); @@ -131,7 +125,7 @@ public class CollectionBinderTests { } @Test - public void bindToNonScalarCollectionWhenNonSequentialShouldThrowException() { + void bindToNonScalarCollectionWhenNonSequentialShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0].value", "1"); source.put("foo[1].value", "2"); @@ -150,7 +144,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenNonIterableShouldReturnPopulatedCollection() { + void bindToCollectionWhenNonIterableShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[1]", "2"); source.put("foo[0]", "1"); @@ -161,7 +155,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenMultipleSourceShouldOnlyUseFirst() { + void bindToCollectionWhenMultipleSourceShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("bar", "baz"); this.sources.add(source1); @@ -179,7 +173,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenHasExistingCollectionShouldReplaceAllContents() { + void bindToCollectionWhenHasExistingCollectionShouldReplaceAllContents() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1")); List existing = new LinkedList<>(); existing.add(1000); @@ -190,7 +184,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenHasExistingCollectionButNoValueShouldReturnUnbound() { + void bindToCollectionWhenHasExistingCollectionButNoValueShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource("faf[0]", "1")); List existing = new LinkedList<>(); existing.add(1000); @@ -199,7 +193,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionShouldRespectCollectionType() { + void bindToCollectionShouldRespectCollectionType() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1")); ResolvableType type = ResolvableType.forClassWithGenerics(LinkedList.class, Integer.class); Object defaultList = this.binder.bind("foo", INTEGER_LIST).get(); @@ -208,21 +202,21 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenNoValueShouldReturnUnbound() { + void bindToCollectionWhenNoValueShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource("faf.bar", "1")); BindResult> result = this.binder.bind("foo", INTEGER_LIST); assertThat(result.isBound()).isFalse(); } @Test - public void bindToCollectionWhenCommaListShouldReturnPopulatedCollection() { + void bindToCollectionWhenCommaListShouldReturnPopulatedCollection() { this.sources.add(new MockConfigurationPropertySource("foo", "1,2,3")); List result = this.binder.bind("foo", INTEGER_LIST).get(); assertThat(result).containsExactly(1, 2, 3); } @Test - public void bindToCollectionWhenCommaListWithPlaceholdersShouldReturnPopulatedCollection() { + void bindToCollectionWhenCommaListWithPlaceholdersShouldReturnPopulatedCollection() { StandardEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "bar=1,2,3"); this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); @@ -233,7 +227,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenCommaListAndIndexedShouldOnlyUseFirst() { + void bindToCollectionWhenCommaListAndIndexedShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("foo", "1,2"); this.sources.add(source1); @@ -245,7 +239,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenIndexedAndCommaListShouldOnlyUseFirst() { + void bindToCollectionWhenIndexedAndCommaListShouldOnlyUseFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("foo[0]", "1"); source1.put("foo[1]", "2"); @@ -257,7 +251,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenItemContainsCommasShouldReturnPopulatedCollection() { + void bindToCollectionWhenItemContainsCommasShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "1,2"); source.put("foo[1]", "3"); @@ -267,7 +261,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenEmptyStringShouldReturnEmptyCollection() { + void bindToCollectionWhenEmptyStringShouldReturnEmptyCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", ""); this.sources.add(source); @@ -276,7 +270,7 @@ public class CollectionBinderTests { } @Test - public void bindToNonScalarCollectionShouldReturnPopulatedCollection() { + void bindToNonScalarCollectionShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0].value", "a"); source.put("foo[1].value", "b"); @@ -290,7 +284,7 @@ public class CollectionBinderTests { } @Test - public void bindToImmutableCollectionShouldReturnPopulatedCollection() { + void bindToImmutableCollectionShouldReturnPopulatedCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values", "a,b,c"); this.sources.add(source); @@ -299,7 +293,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionShouldAlsoCallSetterIfPresent() { + void bindToCollectionShouldAlsoCallSetterIfPresent() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c"); this.sources.add(source); @@ -309,7 +303,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWithNoDefaultConstructor() { + void bindToCollectionWithNoDefaultConstructor() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c,c"); this.sources.add(source); @@ -320,7 +314,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWithDefaultConstructor() { + void bindToCollectionWithDefaultConstructor() { // gh-12322 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c,c"); @@ -332,7 +326,7 @@ public class CollectionBinderTests { } @Test - public void bindToListShouldAllowDuplicateValues() { + void bindToListShouldAllowDuplicateValues() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items", "a,b,c,c"); this.sources.add(source); @@ -342,7 +336,7 @@ public class CollectionBinderTests { } @Test - public void bindToSetShouldNotAllowDuplicateValues() { + void bindToSetShouldNotAllowDuplicateValues() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items-set", "a,b,c,c"); this.sources.add(source); @@ -352,7 +346,7 @@ public class CollectionBinderTests { } @Test - public void bindToBeanWithNestedCollectionShouldPopulateCollection() { + void bindToBeanWithNestedCollectionShouldPopulateCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "one"); source.put("foo.foos[0].value", "two"); @@ -366,7 +360,7 @@ public class CollectionBinderTests { } @Test - public void bindToNestedCollectionWhenEmptyStringShouldReturnEmptyCollection() { + void bindToNestedCollectionWhenEmptyStringShouldReturnEmptyCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "one"); source.put("foo.foos", ""); @@ -378,7 +372,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionShouldUsePropertyEditor() { + void bindToCollectionShouldUsePropertyEditor() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "java.lang.RuntimeException"); @@ -389,7 +383,7 @@ public class CollectionBinderTests { } @Test - public void bindToCollectionWhenStringShouldUsePropertyEditor() { + void bindToCollectionWhenStringShouldUsePropertyEditor() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "java.lang.RuntimeException,java.lang.IllegalStateException"); @@ -399,7 +393,7 @@ public class CollectionBinderTests { } @Test - public void bindToBeanWithNestedCollectionAndNonIterableSourceShouldNotFail() { + void bindToBeanWithNestedCollectionAndNonIterableSourceShouldNotFail() { // gh-10702 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); this.sources.add(source.nonIterable()); @@ -408,7 +402,7 @@ public class CollectionBinderTests { } @Test - public void bindToBeanWithClonedArray() { + void bindToBeanWithClonedArray() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar[0]", "hello"); this.sources.add(source); @@ -418,7 +412,7 @@ public class CollectionBinderTests { } @Test - public void bindToBeanWithExceptionInGetterForExistingValue() { + void bindToBeanWithExceptionInGetterForExistingValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values", "a,b,c"); this.sources.add(source); @@ -427,7 +421,7 @@ public class CollectionBinderTests { } @Test - public void bindToBeanWithEnumSetCollection() { + void bindToBeanWithEnumSetCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values[0]", "foo-bar,bar-baz"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java index 6ee166be757..3fb992a9668 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ConstructorParametersBinderTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.context.properties.bind; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.source.ConfigurationPropertyName; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; @@ -32,19 +31,14 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class ConstructorParametersBinderTests { +class ConstructorParametersBinderTests { - private List sources = new ArrayList<>(); + private final List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private final Binder binder = new Binder(this.sources); @Test - public void bindToClassShouldCreateBoundBean() { + void bindToClassShouldCreateBoundBean() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); source.put("foo.long-value", "34"); @@ -61,7 +55,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassWhenHasNoPrefixShouldCreateBoundBean() { + void bindToClassWhenHasNoPrefixShouldCreateBoundBean() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("int-value", "12"); source.put("long-value", "34"); @@ -79,7 +73,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToAbstractClassWithShouldNotBind() { + void bindToAbstractClassWithShouldNotBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.name", "test"); this.sources.add(source); @@ -88,7 +82,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassWithMultipleConstructorsShouldNotBind() { + void bindToClassWithMultipleConstructorsShouldNotBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); this.sources.add(source); @@ -97,7 +91,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassWithOnlyDefaultConstructorShouldNotBind() { + void bindToClassWithOnlyDefaultConstructorShouldNotBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); this.sources.add(source); @@ -106,7 +100,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassShouldBindNested() { + void bindToClassShouldBindNested() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.long-value", "34"); @@ -121,7 +115,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassWithNoValueForPrimitiveShouldUseDefault() { + void bindToClassWithNoValueForPrimitiveShouldUseDefault() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.string-value", "foo"); this.sources.add(source); @@ -133,7 +127,7 @@ public class ConstructorParametersBinderTests { } @Test - public void bindToClassWithNoValueAndDefaultValueShouldUseDefault() { + void bindToClassWithNoValueAndDefaultValueShouldUseDefault() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.string-value", "foo"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java index 120b08bd3dc..d4449a6e5fb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java @@ -27,8 +27,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.JavaBeanBinder.Bean; import org.springframework.boot.context.properties.bind.JavaBeanBinder.BeanProperty; @@ -51,19 +50,14 @@ import static org.assertj.core.api.Assertions.entry; * @author Madhura Bhave * @author Andy Wilkinson */ -public class JavaBeanBinderTests { +class JavaBeanBinderTests { - private List sources = new ArrayList<>(); + private final List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private final Binder binder = new Binder(this.sources); @Test - public void bindToClassShouldCreateBoundBean() { + void bindToClassShouldCreateBoundBean() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); source.put("foo.long-value", "34"); @@ -78,7 +72,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoPrefixShouldCreateBoundBean() { + void bindToClassWhenHasNoPrefixShouldCreateBoundBean() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("int-value", "12"); source.put("long-value", "34"); @@ -94,7 +88,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToInstanceShouldBindToInstance() { + void bindToInstanceShouldBindToInstance() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); source.put("foo.long-value", "34"); @@ -112,7 +106,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToInstanceWithNoPropertiesShouldReturnUnbound() { + void bindToInstanceWithNoPropertiesShouldReturnUnbound() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); this.sources.add(source); ExampleDefaultsBean bean = new ExampleDefaultsBean(); @@ -124,7 +118,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldLeaveDefaults() { + void bindToClassShouldLeaveDefaults() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "999"); this.sources.add(source); @@ -134,7 +128,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToExistingInstanceShouldLeaveDefaults() { + void bindToExistingInstanceShouldLeaveDefaults() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "999"); this.sources.add(source); @@ -148,7 +142,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindToMap() { + void bindToClassShouldBindToMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.map.foo-bar", "1"); source.put("foo.map.bar-baz", "2"); @@ -158,7 +152,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindToList() { + void bindToClassShouldBindToList() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.list[0]", "foo-bar"); source.put("foo.list[1]", "bar-baz"); @@ -168,7 +162,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToListIfUnboundElementsPresentShouldThrowException() { + void bindToListIfUnboundElementsPresentShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.list[0]", "foo-bar"); source.put("foo.list[2]", "bar-baz"); @@ -179,7 +173,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindToSet() { + void bindToClassShouldBindToSet() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.set[0]", "foo-bar"); source.put("foo.set[1]", "bar-baz"); @@ -189,7 +183,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindToCollection() { + void bindToClassShouldBindToCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.collection[0]", "foo-bar"); source.put("foo.collection[1]", "bar-baz"); @@ -199,7 +193,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindToCollectionWithDelimiter() { + void bindToClassShouldBindToCollectionWithDelimiter() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.collection", "foo-bar|bar-baz"); this.sources.add(source); @@ -209,7 +203,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterShouldBindToMap() { + void bindToClassWhenHasNoSetterShouldBindToMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.map.foo-bar", "1"); source.put("foo.map.bar-baz", "2"); @@ -220,7 +214,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterShouldBindToList() { + void bindToClassWhenHasNoSetterShouldBindToList() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.list[0]", "foo-bar"); source.put("foo.list[1]", "bar-baz"); @@ -231,7 +225,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterShouldBindToSet() { + void bindToClassWhenHasNoSetterShouldBindToSet() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.set[0]", "foo-bar"); source.put("foo.set[1]", "bar-baz"); @@ -242,7 +236,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterShouldBindToCollection() { + void bindToClassWhenHasNoSetterShouldBindToCollection() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.collection[0]", "foo-bar"); source.put("foo.collection[1]", "bar-baz"); @@ -253,7 +247,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindNested() { + void bindToClassShouldBindNested() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.string-value", "foo"); @@ -264,7 +258,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenIterableShouldBindNestedBasedOnInstance() { + void bindToClassWhenIterableShouldBindNestedBasedOnInstance() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.string-value", "foo"); @@ -277,7 +271,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenNotIterableShouldNotBindNestedBasedOnInstance() { + void bindToClassWhenNotIterableShouldNotBindNestedBasedOnInstance() { // If we can't tell that binding will happen, we don't want to randomly invoke // getters on the class and cause side effects MockConfigurationPropertySource source = new MockConfigurationPropertySource(); @@ -290,7 +284,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterShouldBindNested() { + void bindToClassWhenHasNoSetterShouldBindNested() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value-bean.int-value", "123"); source.put("foo.value-bean.string-value", "foo"); @@ -302,7 +296,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenHasNoSetterAndImmutableShouldThrowException() { + void bindToClassWhenHasNoSetterAndImmutableShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.foo", "bar"); this.sources.add(source); @@ -311,7 +305,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToInstanceWhenNoNestedShouldLeaveNestedAsNull() { + void bindToInstanceWhenNoNestedShouldLeaveNestedAsNull() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("faf.value-bean.int-value", "123"); this.sources.add(source); @@ -323,7 +317,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenPropertiesMissingShouldReturnUnbound() { + void bindToClassWhenPropertiesMissingShouldReturnUnbound() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("faf.int-value", "12"); this.sources.add(source); @@ -332,7 +326,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenNoDefaultConstructorShouldBind() { + void bindToClassWhenNoDefaultConstructorShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "bar"); this.sources.add(source); @@ -344,7 +338,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToInstanceWhenNoDefaultConstructorShouldBind() { + void bindToInstanceWhenNoDefaultConstructorShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "bar"); this.sources.add(source); @@ -356,7 +350,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldBindHierarchy() { + void bindToClassShouldBindHierarchy() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "123"); source.put("foo.long-value", "456"); @@ -367,14 +361,14 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { + void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo.int-value", "foo")); assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); } @Test - public void bindToClassWhenPropertyCannotBeConvertedAndIgnoreErrorsShouldNotSetValue() { + void bindToClassWhenPropertyCannotBeConvertedAndIgnoreErrorsShouldNotSetValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.int-value", "12"); source.put("foo.long-value", "bang"); @@ -390,7 +384,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWhenMismatchedGetSetShouldBind() { + void bindToClassWhenMismatchedGetSetShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "123"); this.sources.add(source); @@ -399,7 +393,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldNotInvokeExtraMethods() { + void bindToClassShouldNotInvokeExtraMethods() { MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.value", "123"); this.sources.add(source.nonIterable()); ExampleWithThrowingGetters bean = this.binder.bind("foo", Bindable.of(ExampleWithThrowingGetters.class)).get(); @@ -407,7 +401,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWithSelfReferenceShouldBind() { + void bindToClassWithSelfReferenceShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "123"); this.sources.add(source); @@ -416,7 +410,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToInstanceWithExistingValueShouldReturnUnbound() { + void bindToInstanceWithExistingValueShouldReturnUnbound() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); this.sources.add(source); ExampleNestedBean existingValue = new ExampleNestedBean(); @@ -428,7 +422,7 @@ public class JavaBeanBinderTests { } @Test - public void bindWithAnnotations() { + void bindWithAnnotations() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.date", "2014-04-01"); this.sources.add(source); @@ -438,7 +432,7 @@ public class JavaBeanBinderTests { } @Test - public void bindWhenValueIsConvertedWithPropertyEditorShouldBind() { + void bindWhenValueIsConvertedWithPropertyEditorShouldBind() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "java.lang.RuntimeException"); @@ -449,7 +443,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldIgnoreInvalidAccessors() { + void bindToClassShouldIgnoreInvalidAccessors() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.name", "something"); this.sources.add(source); @@ -459,7 +453,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldIgnoreStaticAccessors() { + void bindToClassShouldIgnoreStaticAccessors() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.name", "invalid"); source.put("foo.counter", "42"); @@ -470,7 +464,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassShouldCacheWithGenerics() { + void bindToClassShouldCacheWithGenerics() { // gh-16821 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.integers[a].value", "1"); @@ -482,7 +476,7 @@ public class JavaBeanBinderTests { } @Test - public void bindToClassWithOverloadedSetterShouldUseSetterThatMatchesField() { + void bindToClassWithOverloadedSetterShouldUseSetterThatMatchesField() { // gh-16206 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.property", "some string"); @@ -493,7 +487,7 @@ public class JavaBeanBinderTests { } @Test - public void beanPropertiesPreferMatchingType() { + void beanPropertiesPreferMatchingType() { // gh-16206 ResolvableType type = ResolvableType.forClass(PropertyWithOverloadedSetter.class); Bean bean = new Bean(type, type.resolve()) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java index bf096bea33c..36b30f26577 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java @@ -25,8 +25,7 @@ import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -59,7 +58,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class MapBinderTests { +class MapBinderTests { private static final Bindable> STRING_STRING_MAP = Bindable.mapOf(String.class, String.class); @@ -74,17 +73,12 @@ public class MapBinderTests { private static final Bindable> STRING_ARRAY_MAP = Bindable.mapOf(String.class, String[].class); - private List sources = new ArrayList<>(); + private final List sources = new ArrayList<>(); - private Binder binder; - - @Before - public void setup() { - this.binder = new Binder(this.sources); - } + private Binder binder = new Binder(this.sources); @Test - public void bindToMapShouldReturnPopulatedMap() { + void bindToMapShouldReturnPopulatedMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "1"); source.put("foo.[baz]", "2"); @@ -99,7 +93,7 @@ public class MapBinderTests { @Test @SuppressWarnings("unchecked") - public void bindToMapWithEmptyPrefix() { + void bindToMapWithEmptyPrefix() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "1"); this.sources.add(source); @@ -108,7 +102,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldConvertMapValue() { + void bindToMapShouldConvertMapValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "1"); source.put("foo.[baz]", "2"); @@ -123,7 +117,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldBindToMapValue() { + void bindToMapShouldBindToMapValue() { ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), STRING_INTEGER_MAP.getType()); MockConfigurationPropertySource source = new MockConfigurationPropertySource(); @@ -141,7 +135,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldBindNestedMapValue() { + void bindToMapShouldBindNestedMapValue() { ResolvableType nestedType = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), STRING_INTEGER_MAP.getType()); ResolvableType type = ResolvableType.forClassWithGenerics(Map.class, ResolvableType.forClass(String.class), @@ -163,7 +157,7 @@ public class MapBinderTests { @Test @SuppressWarnings("unchecked") - public void bindToMapWhenMapValueIsObjectShouldBindNestedMapValue() { + void bindToMapWhenMapValueIsObjectShouldBindNestedMapValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.bar.baz", "1"); source.put("foo.nested.bar.bin", "2"); @@ -181,7 +175,7 @@ public class MapBinderTests { } @Test - public void bindToMapWhenMapValueIsObjectAndNoRootShouldBindNestedMapValue() { + void bindToMapWhenMapValueIsObjectAndNoRootShouldBindNestedMapValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("commit.id", "abcdefg"); source.put("branch", "master"); @@ -194,7 +188,7 @@ public class MapBinderTests { } @Test - public void bindToMapWhenEmptyRootNameShouldBindMap() { + void bindToMapWhenEmptyRootNameShouldBindMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("bar.baz", "1"); source.put("bar.bin", "2"); @@ -205,7 +199,7 @@ public class MapBinderTests { } @Test - public void bindToMapWhenMultipleCandidateShouldBindFirst() { + void bindToMapWhenMultipleCandidateShouldBindFirst() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("foo.bar", "1"); source1.put("foo.baz", "2"); @@ -222,7 +216,7 @@ public class MapBinderTests { } @Test - public void bindToMapWhenMultipleInSameSourceCandidateShouldBindFirst() { + void bindToMapWhenMultipleInSameSourceCandidateShouldBindFirst() { Map map = new HashMap<>(); map.put("foo.bar", "1"); map.put("foo.b-az", "2"); @@ -239,7 +233,7 @@ public class MapBinderTests { } @Test - public void bindToMapWhenHasExistingMapShouldReplaceOnlyNewContents() { + void bindToMapWhenHasExistingMapShouldReplaceOnlyNewContents() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "1")); Map existing = new HashMap<>(); existing.put("bar", 1000); @@ -253,7 +247,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldRespectMapType() { + void bindToMapShouldRespectMapType() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "1")); ResolvableType type = ResolvableType.forClassWithGenerics(HashMap.class, String.class, Integer.class); Object defaultMap = this.binder.bind("foo", STRING_INTEGER_MAP).get(); @@ -262,14 +256,14 @@ public class MapBinderTests { } @Test - public void bindToMapWhenNoValueShouldReturnUnbound() { + void bindToMapWhenNoValueShouldReturnUnbound() { this.sources.add(new MockConfigurationPropertySource("faf.bar", "1")); BindResult> result = this.binder.bind("foo", STRING_INTEGER_MAP); assertThat(result.isBound()).isFalse(); } @Test - public void bindToMapShouldConvertKey() { + void bindToMapShouldConvertKey() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo[0]", "1"); source.put("foo[1]", "2"); @@ -283,7 +277,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldBeGreedyForStrings() { + void bindToMapShouldBeGreedyForStrings() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.aaa.bbb.ccc", "b"); source.put("foo.bbb.ccc.ddd", "a"); @@ -297,7 +291,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldBeGreedyForScalars() { + void bindToMapShouldBeGreedyForScalars() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.aaa.bbb.ccc", "foo-bar"); source.put("foo.bbb.ccc.ddd", "BAR_BAZ"); @@ -312,7 +306,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithPlaceholdersShouldBeGreedyForScalars() { + void bindToMapWithPlaceholdersShouldBeGreedyForScalars() { StandardEnvironment environment = new StandardEnvironment(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, "foo=boo"); MockConfigurationPropertySource source = new MockConfigurationPropertySource("foo.aaa.bbb.ccc", "baz-${foo}"); @@ -324,7 +318,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithNoPropertiesShouldReturnUnbound() { + void bindToMapWithNoPropertiesShouldReturnUnbound() { this.binder = new Binder(this.sources); BindResult> result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)); @@ -332,7 +326,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldTriggerOnSuccess() { + void bindToMapShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "1", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable> target = STRING_INTEGER_MAP; @@ -344,7 +338,7 @@ public class MapBinderTests { } @Test - public void bindToMapStringArrayShouldTriggerOnSuccess() { + void bindToMapStringArrayShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "a,b,c", "line1")); BindHandler handler = mock(BindHandler.class, Answers.CALLS_REAL_METHODS); Bindable> target = STRING_ARRAY_MAP; @@ -358,7 +352,7 @@ public class MapBinderTests { } @Test - public void bindToMapNonScalarCollectionShouldPopulateMap() { + void bindToMapNonScalarCollectionShouldPopulateMap() { Bindable> valueType = Bindable.listOf(JavaBean.class); Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource source = new MockConfigurationPropertySource(); @@ -373,7 +367,7 @@ public class MapBinderTests { } @Test - public void bindToPropertiesShouldBeEquivalentToMapOfStringString() { + void bindToPropertiesShouldBeEquivalentToMapOfStringString() { this.sources.add(new MockConfigurationPropertySource("foo.bar.baz", "1", "line1")); Bindable target = Bindable.of(Properties.class); Properties properties = this.binder.bind("foo", target).get(); @@ -381,7 +375,7 @@ public class MapBinderTests { } @Test - public void bindToMapShouldNotTreatClassWithStringConstructorAsScalar() { + void bindToMapShouldNotTreatClassWithStringConstructorAsScalar() { this.sources.add(new MockConfigurationPropertySource("foo.bar.pattern", "1", "line1")); Bindable> target = Bindable.mapOf(String.class, Foo.class); Map map = this.binder.bind("foo", target).get(); @@ -389,7 +383,7 @@ public class MapBinderTests { } @Test - public void bindToMapStringArrayWithDotKeysShouldPreserveDot() { + void bindToMapStringArrayWithDotKeysShouldPreserveDot() { MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo.bar.baz[0]", "a"); mockSource.put("foo.bar.baz[1]", "b"); @@ -400,7 +394,7 @@ public class MapBinderTests { } @Test - public void bindToMapStringArrayWithDotKeysAndCommaSeparatedShouldPreserveDot() { + void bindToMapStringArrayWithDotKeysAndCommaSeparatedShouldPreserveDot() { MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); mockSource.put("foo.bar.baz", "a,b,c"); this.sources.add(mockSource); @@ -409,7 +403,7 @@ public class MapBinderTests { } @Test - public void bindToMapStringCollectionWithDotKeysShouldPreserveDot() { + void bindToMapStringCollectionWithDotKeysShouldPreserveDot() { Bindable> valueType = Bindable.listOf(String.class); Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); @@ -423,7 +417,7 @@ public class MapBinderTests { } @Test - public void bindToMapNonScalarCollectionWithDotKeysShouldBind() { + void bindToMapNonScalarCollectionWithDotKeysShouldBind() { Bindable> valueType = Bindable.listOf(JavaBean.class); Bindable>> target = getMapBindable(String.class, valueType.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); @@ -437,7 +431,7 @@ public class MapBinderTests { } @Test - public void bindToListOfMaps() { + void bindToListOfMaps() { Bindable> listBindable = Bindable.listOf(Integer.class); Bindable>> mapBindable = getMapBindable(String.class, listBindable.getType()); Bindable>>> target = getListBindable(mapBindable.getType()); @@ -451,7 +445,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithNumberKeyAndCommaSeparated() { + void bindToMapWithNumberKeyAndCommaSeparated() { Bindable> listBindable = Bindable.listOf(String.class); Bindable>> target = getMapBindable(Integer.class, listBindable.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); @@ -464,7 +458,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithNumberKeyAndIndexed() { + void bindToMapWithNumberKeyAndIndexed() { Bindable> listBindable = Bindable.listOf(Integer.class); Bindable>> target = getMapBindable(Integer.class, listBindable.getType()); MockConfigurationPropertySource mockSource = new MockConfigurationPropertySource(); @@ -476,7 +470,7 @@ public class MapBinderTests { } @Test - public void bindingWithSquareBracketMap() { + void bindingWithSquareBracketMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.[x [B] y]", "[ball]"); this.sources.add(source); @@ -485,7 +479,7 @@ public class MapBinderTests { } @Test - public void nestedMapsShouldNotBindToNull() { + void nestedMapsShouldNotBindToNull() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value", "one"); source.put("foo.foos.foo1.value", "two"); @@ -498,7 +492,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithCustomConverter() { + void bindToMapWithCustomConverter() { DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new MapConverter()); Binder binder = new Binder(this.sources, null, conversionService, null); @@ -511,7 +505,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithCustomConverterAndChildElements() { + void bindToMapWithCustomConverterAndChildElements() { // gh-11892 DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new MapConverter()); @@ -527,7 +521,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithNoConverterForValue() { + void bindToMapWithNoConverterForValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "a,b"); this.sources.add(source); @@ -536,7 +530,7 @@ public class MapBinderTests { @Test @SuppressWarnings("rawtypes") - public void bindToMapWithPropertyEditorForKey() { + void bindToMapWithPropertyEditorForKey() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.[java.lang.RuntimeException]", "bar"); @@ -547,7 +541,7 @@ public class MapBinderTests { @Test @SuppressWarnings("rawtypes") - public void bindToMapWithPropertyEditorForValue() { + void bindToMapWithPropertyEditorForValue() { // gh-12166 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "java.lang.RuntimeException"); @@ -557,7 +551,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithNoDefaultConstructor() { + void bindToMapWithNoDefaultConstructor() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items.a", "b"); this.sources.add(source); @@ -567,7 +561,7 @@ public class MapBinderTests { } @Test - public void bindToMapWithDefaultConstructor() { + void bindToMapWithDefaultConstructor() { // gh-12322 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.items.a", "b"); @@ -578,7 +572,7 @@ public class MapBinderTests { } @Test - public void bindToImmutableMapShouldReturnPopulatedMap() { + void bindToImmutableMapShouldReturnPopulatedMap() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values.c", "d"); source.put("foo.values.e", "f"); @@ -590,7 +584,7 @@ public class MapBinderTests { } @Test - public void bindToBeanWithExceptionInGetterForExistingValue() { + void bindToBeanWithExceptionInGetterForExistingValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.values.a", "b"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java index bc4227d4c49..7ef7214b525 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.bind; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; @@ -36,19 +36,19 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ -public class PropertySourcesPlaceholdersResolverTests { +class PropertySourcesPlaceholdersResolverTests { private PropertySourcesPlaceholdersResolver resolver; @Test - public void placeholderResolverIfEnvironmentNullShouldThrowException() { + void placeholderResolverIfEnvironmentNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) .withMessageContaining("Environment must not be null"); } @Test - public void resolveIfPlaceholderPresentResolvesProperty() { + void resolveIfPlaceholderPresentResolvesProperty() { MutablePropertySources sources = getPropertySources(); this.resolver = new PropertySourcesPlaceholdersResolver(sources); Object resolved = this.resolver.resolvePlaceholders("${FOO}"); @@ -56,21 +56,21 @@ public class PropertySourcesPlaceholdersResolverTests { } @Test - public void resolveIfPlaceholderAbsentUsesDefault() { + void resolveIfPlaceholderAbsentUsesDefault() { this.resolver = new PropertySourcesPlaceholdersResolver((PropertySources) null); Object resolved = this.resolver.resolvePlaceholders("${FOO:bar}"); assertThat(resolved).isEqualTo("bar"); } @Test - public void resolveIfPlaceholderAbsentAndNoDefaultUsesPlaceholder() { + void resolveIfPlaceholderAbsentAndNoDefaultUsesPlaceholder() { this.resolver = new PropertySourcesPlaceholdersResolver((PropertySources) null); Object resolved = this.resolver.resolvePlaceholders("${FOO}"); assertThat(resolved).isEqualTo("${FOO}"); } @Test - public void resolveIfHelperPresentShouldUseIt() { + void resolveIfHelperPresentShouldUseIt() { MutablePropertySources sources = getPropertySources(); TestPropertyPlaceholderHelper helper = new TestPropertyPlaceholderHelper("$<", ">"); this.resolver = new PropertySourcesPlaceholdersResolver(sources, helper); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java index 6fe8601dd63..fad5177b65c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.context.properties.bind.handler; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Madhura Bhave */ -public class IgnoreErrorsBindHandlerTests { +class IgnoreErrorsBindHandlerTests { private List sources = new ArrayList<>(); private Binder binder; - @Before + @BeforeEach public void setup() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); @@ -52,13 +52,13 @@ public class IgnoreErrorsBindHandlerTests { } @Test - public void bindWhenNotIgnoringErrorsShouldFail() { + void bindWhenNotIgnoringErrorsShouldFail() { assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); } @Test - public void bindWhenIgnoringErrorsShouldBind() { + void bindWhenIgnoringErrorsShouldBind() { Example bound = this.binder.bind("example", Bindable.of(Example.class), new IgnoreErrorsBindHandler()).get(); assertThat(bound.getFoo()).isEqualTo(0); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java index a78d0507fae..acc50763b96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java @@ -20,8 +20,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; @@ -37,13 +37,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Madhura Bhave */ -public class IgnoreTopLevelConverterNotFoundBindHandlerTests { +class IgnoreTopLevelConverterNotFoundBindHandlerTests { private List sources = new ArrayList<>(); private Binder binder; - @Before + @BeforeEach public void setup() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example", "bar"); @@ -52,19 +52,19 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { } @Test - public void bindWhenHandlerNotPresentShouldFail() { + void bindWhenHandlerNotPresentShouldFail() { assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) .withCauseInstanceOf(ConverterNotFoundException.class); } @Test - public void bindWhenTopLevelContextAndExceptionIgnorableShouldNotFail() { + void bindWhenTopLevelContextAndExceptionIgnorableShouldNotFail() { this.binder.bind("example", Bindable.of(Example.class), new IgnoreTopLevelConverterNotFoundBindHandler()); } @Test - public void bindWhenExceptionNotIgnorableShouldFail() { + void bindWhenExceptionNotIgnorableShouldFail() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "1"); this.sources.add(source); @@ -75,7 +75,7 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { } @Test - public void bindWhenExceptionInNestedContextShouldFail() { + void bindWhenExceptionInNestedContextShouldFail() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.map", "hello"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java index a6d84ceed11..07e0967c712 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.bind.handler; import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.BindHandler; @@ -38,14 +38,14 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Madhura Bhave */ -public class NoUnboundElementsBindHandlerTests { +class NoUnboundElementsBindHandlerTests { private List sources = new ArrayList<>(); private Binder binder; @Test - public void bindWhenNotUsingNoUnboundElementsHandlerShouldBind() { + void bindWhenNotUsingNoUnboundElementsHandlerShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); source.put("example.baz", "bar"); @@ -56,7 +56,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerShouldBind() { + void bindWhenUsingNoUnboundElementsHandlerShouldBind() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); this.sources.add(source); @@ -67,7 +67,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerThrowException() { + void bindWhenUsingNoUnboundElementsHandlerThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); source.put("example.baz", "bar"); @@ -80,7 +80,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerShouldBindIfPrefixDifferent() { + void bindWhenUsingNoUnboundElementsHandlerShouldBindIfPrefixDifferent() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); source.put("other.baz", "bar"); @@ -92,7 +92,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerShouldBindIfUnboundSystemProperties() { + void bindWhenUsingNoUnboundElementsHandlerShouldBindIfUnboundSystemProperties() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "bar"); source.put("example.other", "baz"); @@ -105,7 +105,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerShouldBindIfUnboundCollectionProperties() { + void bindWhenUsingNoUnboundElementsHandlerShouldBindIfUnboundCollectionProperties() { MockConfigurationPropertySource source1 = new MockConfigurationPropertySource(); source1.put("example.foo[0]", "bar"); MockConfigurationPropertySource source2 = new MockConfigurationPropertySource(); @@ -120,7 +120,7 @@ public class NoUnboundElementsBindHandlerTests { } @Test - public void bindWhenUsingNoUnboundElementsHandlerAndUnboundListElementsShouldThrowException() { + void bindWhenUsingNoUnboundElementsHandlerAndUnboundListElementsShouldThrowException() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo[0]", "bar"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java index e642842609f..896c4e81e8d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.context.properties.bind.test; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class PackagePrivateBeanBindingTests { +class PackagePrivateBeanBindingTests { private List sources = new ArrayList<>(); @@ -43,14 +43,14 @@ public class PackagePrivateBeanBindingTests { private ConfigurationPropertyName name; - @Before + @BeforeEach public void setup() { this.binder = new Binder(this.sources); this.name = ConfigurationPropertyName.of("foo"); } @Test - public void bindToPackagePrivateClassShouldBindToInstance() { + void bindToPackagePrivateClassShouldBindToInstance() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "999"); this.sources.add(source); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java index d7de2ebbb86..29cd41ed8bb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.bind.validation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -28,16 +28,16 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class BindValidationExceptionTests { +class BindValidationExceptionTests { @Test - public void createWhenValidationErrorsIsNullShouldThrowException() { + void createWhenValidationErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BindValidationException(null)) .withMessageContaining("ValidationErrors must not be null"); } @Test - public void getValidationErrorsShouldReturnValidationErrors() { + void getValidationErrorsShouldReturnValidationErrors() { ValidationErrors errors = mock(ValidationErrors.class); BindValidationException exception = new BindValidationException(errors); assertThat(exception.getValidationErrors()).isEqualTo(errors); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java index 5476ebe4e15..61c3ca98752 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.bind.validation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.MockOrigin; import org.springframework.boot.origin.Origin; @@ -30,24 +30,24 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class OriginTrackedFieldErrorTests { +class OriginTrackedFieldErrorTests { private static final FieldError FIELD_ERROR = new FieldError("foo", "bar", "faf"); private static final Origin ORIGIN = MockOrigin.of("afile"); @Test - public void ofWhenFieldErrorIsNullShouldReturnNull() { + void ofWhenFieldErrorIsNullShouldReturnNull() { assertThat(OriginTrackedFieldError.of(null, ORIGIN)).isNull(); } @Test - public void ofWhenOriginIsNullShouldReturnFieldErrorWithoutOrigin() { + void ofWhenOriginIsNullShouldReturnFieldErrorWithoutOrigin() { assertThat(OriginTrackedFieldError.of(FIELD_ERROR, null)).isSameAs(FIELD_ERROR); } @Test - public void ofShouldReturnOriginCapableFieldError() { + void ofShouldReturnOriginCapableFieldError() { FieldError fieldError = OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN); assertThat(fieldError.getObjectName()).isEqualTo("foo"); assertThat(fieldError.getField()).isEqualTo("bar"); @@ -55,7 +55,7 @@ public class OriginTrackedFieldErrorTests { } @Test - public void toStringShouldAddOrigin() { + void toStringShouldAddOrigin() { assertThat(OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN).toString()) .isEqualTo("Field error in object 'foo' on field 'bar': rejected value [null]" + "; codes []; arguments []; default message [faf]; origin afile"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java index fe4307c4440..d6e740860f3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java @@ -24,8 +24,8 @@ import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.AbstractBindHandler; import org.springframework.boot.context.properties.bind.BindContext; @@ -52,7 +52,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Madhura Bhave */ -public class ValidationBindHandlerTests { +class ValidationBindHandlerTests { private List sources = new ArrayList<>(); @@ -62,7 +62,7 @@ public class ValidationBindHandlerTests { private LocalValidatorFactoryBean validator; - @Before + @BeforeEach public void setup() { this.binder = new Binder(this.sources); this.validator = new LocalValidatorFactoryBean(); @@ -71,14 +71,14 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldBindWithoutHandler() { + void bindShouldBindWithoutHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); ExampleValidatedBean bean = this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class)).get(); assertThat(bean.getAge()).isEqualTo(4); } @Test - public void bindShouldFailWithHandler() { + void bindShouldFailWithHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); assertThatExceptionOfType(BindException.class) .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) @@ -86,7 +86,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldValidateNestedProperties() { + void bindShouldValidateNestedProperties() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); assertThatExceptionOfType(BindException.class) .isThrownBy( @@ -95,7 +95,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldFailWithAccessToOrigin() { + void bindShouldFailWithAccessToOrigin() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4, "file")); BindValidationException cause = bindAndExpectValidationError(() -> this.binder .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); @@ -104,7 +104,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldFailWithAccessToBoundProperties() { + void bindShouldFailWithAccessToBoundProperties() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.name", "baz"); source.put("foo.nested.age", "4"); @@ -118,7 +118,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldFailWithAccessToName() { + void bindShouldFailWithAccessToName() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", "4")); BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind( ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); @@ -127,7 +127,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldFailIfExistingValueIsInvalid() { + void bindShouldFailIfExistingValueIsInvalid() { ExampleValidatedBean existingValue = new ExampleValidatedBean(); BindValidationException cause = bindAndExpectValidationError( () -> this.binder.bind(ConfigurationPropertyName.of("foo"), @@ -137,14 +137,14 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldValidateWithoutAnnotation() { + void bindShouldValidateWithoutAnnotation() { ExampleNonValidatedBean existingValue = new ExampleNonValidatedBean(); bindAndExpectValidationError(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleNonValidatedBean.class).withExistingValue(existingValue), this.handler)); } @Test - public void bindShouldNotValidateDepthGreaterThanZero() { + void bindShouldNotValidateDepthGreaterThanZero() { // gh-12227 MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "baz"); @@ -156,7 +156,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldNotValidateIfOtherHandlersInChainThrowError() { + void bindShouldNotValidateIfOtherHandlersInChainThrowError() { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) @@ -166,7 +166,7 @@ public class ValidationBindHandlerTests { } @Test - public void bindShouldValidateIfOtherHandlersInChainIgnoreError() { + void bindShouldValidateIfOtherHandlersInChainIgnoreError() { TestHandler testHandler = new TestHandler(); this.handler = new ValidationBindHandler(testHandler, this.validator); this.sources.add(new MockConfigurationPropertySource("foo", "hello")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java index 7b6f6739bc0..a3657e60651 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java @@ -22,7 +22,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.source.ConfigurationProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertyName; @@ -40,38 +40,38 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ -public class ValidationErrorsTests { +class ValidationErrorsTests { private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Test - public void createWhenNameIsNullShouldThrowException() { + void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) .withMessageContaining("Name must not be null"); } @Test - public void createWhenBoundPropertiesIsNullShouldThrowException() { + void createWhenBoundPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, null, Collections.emptyList())) .withMessageContaining("BoundProperties must not be null"); } @Test - public void createWhenErrorsIsNullShouldThrowException() { + void createWhenErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, Collections.emptySet(), null)) .withMessageContaining("Errors must not be null"); } @Test - public void getNameShouldReturnName() { + void getNameShouldReturnName() { ConfigurationPropertyName name = NAME; ValidationErrors errors = new ValidationErrors(name, Collections.emptySet(), Collections.emptyList()); assertThat((Object) errors.getName()).isEqualTo(name); } @Test - public void getBoundPropertiesShouldReturnBoundProperties() { + void getBoundPropertiesShouldReturnBoundProperties() { Set boundProperties = new LinkedHashSet<>(); boundProperties.add(new ConfigurationProperty(NAME, "foo", null)); ValidationErrors errors = new ValidationErrors(NAME, boundProperties, Collections.emptyList()); @@ -79,7 +79,7 @@ public class ValidationErrorsTests { } @Test - public void getErrorsShouldReturnErrors() { + void getErrorsShouldReturnErrors() { List allErrors = new ArrayList<>(); allErrors.add(new ObjectError("foo", "bar")); ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), allErrors); @@ -87,7 +87,7 @@ public class ValidationErrorsTests { } @Test - public void iteratorShouldIterateErrors() { + void iteratorShouldIterateErrors() { List allErrors = new ArrayList<>(); allErrors.add(new ObjectError("foo", "bar")); ValidationErrors errors = new ValidationErrors(NAME, Collections.emptySet(), allErrors); @@ -95,7 +95,7 @@ public class ValidationErrorsTests { } @Test - public void getErrorsShouldAdaptFieldErrorsToBeOriginProviders() { + void getErrorsShouldAdaptFieldErrorsToBeOriginProviders() { Set boundProperties = new LinkedHashSet<>(); ConfigurationPropertyName name1 = ConfigurationPropertyName.of("foo.bar"); Origin origin1 = MockOrigin.of("line1"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java index 7c42a0d6d07..5578dcd30b1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.context.properties.source; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.assertj.core.api.Assertions.assertThat; @@ -31,10 +31,10 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class AliasedConfigurationPropertySourceTests { +class AliasedConfigurationPropertySourceTests { @Test - public void getConfigurationPropertyShouldConsiderAliases() { + void getConfigurationPropertyShouldConsiderAliases() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); @@ -45,7 +45,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void getConfigurationPropertyWhenNotAliasesShouldReturnValue() { + void getConfigurationPropertyWhenNotAliasesShouldReturnValue() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); @@ -55,7 +55,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void containsDescendantOfWhenSourceReturnsUnknownShouldReturnUnknown() { + void containsDescendantOfWhenSourceReturnsUnknownShouldReturnUnknown() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.UNKNOWN); @@ -65,7 +65,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { + void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.PRESENT); @@ -77,7 +77,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void containsDescendantOfWhenAllAreAbsentShouldReturnAbsent() { + void containsDescendantOfWhenAllAreAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); @@ -88,7 +88,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void containsDescendantOfWhenAnyIsPresentShouldReturnPresent() { + void containsDescendantOfWhenAnyIsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); @@ -99,7 +99,7 @@ public class AliasedConfigurationPropertySourceTests { } @Test - public void containsDescendantOfWhenPresentInAliasShouldReturnPresent() { + void containsDescendantOfWhenPresentInAliasShouldReturnPresent() { ConfigurationPropertySource source = new MapConfigurationPropertySource( Collections.singletonMap("foo.bar", "foobar")); ConfigurationPropertySource aliased = source diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java index fbd6074fc18..761d656642f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class AliasedIterableConfigurationPropertySourceTests extends AliasedConfigurationPropertySourceTests { +class AliasedIterableConfigurationPropertySourceTests extends AliasedConfigurationPropertySourceTests { @Test - public void streamShouldIncludeAliases() { + void streamShouldIncludeAliases() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java index d1a8b438aee..3ae273f1b5b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -27,23 +27,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ -public class ConfigurationPropertyNameAliasesTests { +class ConfigurationPropertyNameAliasesTests { @Test - public void createWithStringWhenNullNameShouldThrowException() { + void createWithStringWhenNullNameShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) .withMessageContaining("Name must not be null"); } @Test - public void createWithStringShouldAddMapping() { + void createWithStringShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test - public void createWithNameShouldAddMapping() { + void createWithNameShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases( ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); @@ -52,7 +52,7 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void addAliasesFromStringShouldAddMapping() { + void addAliasesFromStringShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) @@ -60,7 +60,7 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void addAliasesFromNameShouldAddMapping() { + void addAliasesFromNameShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases(ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); @@ -69,7 +69,7 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void addWhenHasExistingShouldAddAdditionalMappings() { + void addWhenHasExistingShouldAddAdditionalMappings() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); @@ -78,13 +78,13 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void getAliasesWhenNotMappedShouldReturnEmptyList() { + void getAliasesWhenNotMappedShouldReturnEmptyList() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))).isEmpty(); } @Test - public void getAliasesWhenMappedShouldReturnMapping() { + void getAliasesWhenMappedShouldReturnMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) @@ -92,7 +92,7 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void getNameForAliasWhenHasMappingShouldReturnName() { + void getNameForAliasWhenHasMappingShouldReturnName() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); @@ -103,7 +103,7 @@ public class ConfigurationPropertyNameAliasesTests { } @Test - public void getNameForAliasWhenNotMappedShouldReturnNull() { + void getNameForAliasWhenNotMappedShouldReturnNull() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("baz"))).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java index 7ae4f064025..876066ecf54 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java @@ -21,7 +21,7 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form; @@ -36,40 +36,40 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Madhura Bhave * @author Eddú Meléndez */ -public class ConfigurationPropertyNameTests { +class ConfigurationPropertyNameTests { @Test - public void ofNameShouldNotBeNull() { + void ofNameShouldNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of(null)) .withMessageContaining("Name must not be null"); } @Test - public void ofNameShouldNotStartWithDash() { + void ofNameShouldNotStartWithDash() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("-foo")).withMessageContaining("is not valid"); } @Test - public void ofNameShouldNotStartWithDot() { + void ofNameShouldNotStartWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of(".foo")).withMessageContaining("is not valid"); } @Test - public void ofNameShouldNotEndWithDot() { + void ofNameShouldNotEndWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("foo.")).withMessageContaining("is not valid"); } @Test - public void ofNameShouldNotContainUppercase() { + void ofNameShouldNotContainUppercase() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("fOo")).withMessageContaining("is not valid"); } @Test - public void ofNameShouldNotContainInvalidChars() { + void ofNameShouldNotContainInvalidChars() { String invalid = "_@$%*+=':;"; for (char c : invalid.toCharArray()) { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) @@ -79,7 +79,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenSimple() { + void ofNameWhenSimple() { ConfigurationPropertyName name = ConfigurationPropertyName.of("name"); assertThat(name.toString()).isEqualTo("name"); assertThat(name.getNumberOfElements()).isEqualTo(1); @@ -88,7 +88,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenStartsWithNumber() { + void ofNameWhenStartsWithNumber() { ConfigurationPropertyName name = ConfigurationPropertyName.of("1foo"); assertThat(name.toString()).isEqualTo("1foo"); assertThat(name.getNumberOfElements()).isEqualTo(1); @@ -97,7 +97,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenRunOnAssociative() { + void ofNameWhenRunOnAssociative() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo[bar]"); assertThat(name.toString()).isEqualTo("foo[bar]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -107,7 +107,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenDotOnAssociative() { + void ofNameWhenDotOnAssociative() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.bar"); assertThat(name.toString()).isEqualTo("foo.bar"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -117,7 +117,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenDotAndAssociative() { + void ofNameWhenDotAndAssociative() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.[bar]"); assertThat(name.toString()).isEqualTo("foo[bar]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -127,7 +127,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenDoubleRunOnAndAssociative() { + void ofNameWhenDoubleRunOnAndAssociative() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo[bar]baz"); assertThat(name.toString()).isEqualTo("foo[bar].baz"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -139,7 +139,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenDoubleDotAndAssociative() { + void ofNameWhenDoubleDotAndAssociative() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.[bar].baz"); assertThat(name.toString()).isEqualTo("foo[bar].baz"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -151,25 +151,25 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWhenMissingCloseBracket() { + void ofNameWhenMissingCloseBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("[bar")).withMessageContaining("is not valid"); } @Test - public void ofNameWhenMissingOpenBracket() { + void ofNameWhenMissingOpenBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("bar]")).withMessageContaining("is not valid"); } @Test - public void ofNameWhenMultipleMismatchedBrackets() { + void ofNameWhenMultipleMismatchedBrackets() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")).withMessageContaining("is not valid"); } @Test - public void ofNameWhenNestedBrackets() { + void ofNameWhenNestedBrackets() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo[a[c][[b]ar]]"); assertThat(name.toString()).isEqualTo("foo[a[c][[b]ar]]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -177,13 +177,13 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWithWhitespaceInName() { + void ofNameWithWhitespaceInName() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")).withMessageContaining("is not valid"); } @Test - public void ofNameWithWhitespaceInAssociativeElement() { + void ofNameWithWhitespaceInAssociativeElement() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo[b a r]"); assertThat(name.toString()).isEqualTo("foo[b a r]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -193,7 +193,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofNameWithUppercaseInAssociativeElement() { + void ofNameWithUppercaseInAssociativeElement() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo[BAR]"); assertThat(name.toString()).isEqualTo("foo[BAR]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); @@ -203,33 +203,33 @@ public class ConfigurationPropertyNameTests { } @Test - public void ofWhenNameIsEmptyShouldReturnEmptyName() { + void ofWhenNameIsEmptyShouldReturnEmptyName() { ConfigurationPropertyName name = ConfigurationPropertyName.of(""); assertThat(name.toString()).isEqualTo(""); assertThat(name.append("foo").toString()).isEqualTo("foo"); } @Test - public void adaptWhenNameIsNullShouldThrowException() { + void adaptWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) .withMessageContaining("Name must not be null"); } @Test - public void adaptWhenElementValueProcessorIsNullShouldAdapt() { + void adaptWhenElementValueProcessorIsNullShouldAdapt() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo", '.', null); assertThat(name.toString()).isEqualTo("foo"); } @Test - public void adaptShouldCreateName() { + void adaptShouldCreateName() { ConfigurationPropertyName expected = ConfigurationPropertyName.of("foo.bar.baz"); ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo.bar.baz", '.'); assertThat(name).isEqualTo(expected); } @Test - public void adaptShouldStripInvalidChars() { + void adaptShouldStripInvalidChars() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("f@@.b%r", '.'); assertThat(name.getElement(0, Form.UNIFORM)).isEqualTo("f"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("f"); @@ -239,7 +239,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void adaptShouldSupportUnderscore() { + void adaptShouldSupportUnderscore() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("f-_o.b_r", '.'); assertThat(name.getElement(0, Form.UNIFORM)).isEqualTo("fo"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("f-_o"); @@ -249,7 +249,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void adaptShouldSupportMixedCase() { + void adaptShouldSupportMixedCase() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("fOo.bAr", '.'); assertThat(name.getElement(0, Form.UNIFORM)).isEqualTo("foo"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("fOo"); @@ -259,14 +259,14 @@ public class ConfigurationPropertyNameTests { } @Test - public void adaptShouldUseElementValueProcessor() { + void adaptShouldUseElementValueProcessor() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("FOO_THE-BAR", '_', (c) -> c.toString().replace("-", "")); assertThat(name.toString()).isEqualTo("foo.thebar"); } @Test - public void adaptShouldSupportIndexedElements() { + void adaptShouldSupportIndexedElements() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo", '.'); assertThat(name.toString()).isEqualTo("foo"); assertThat(name.getNumberOfElements()).isEqualTo(1); @@ -285,62 +285,62 @@ public class ConfigurationPropertyNameTests { } @Test - public void adaptUnderscoreShouldReturnEmpty() { + void adaptUnderscoreShouldReturnEmpty() { assertThat(ConfigurationPropertyName.adapt("_", '_').isEmpty()).isTrue(); assertThat(ConfigurationPropertyName.adapt("_", '.').isEmpty()).isTrue(); } @Test - public void isEmptyWhenEmptyShouldReturnTrue() { + void isEmptyWhenEmptyShouldReturnTrue() { assertThat(ConfigurationPropertyName.of("").isEmpty()).isTrue(); } @Test - public void isEmptyWhenNotEmptyShouldReturnFalse() { + void isEmptyWhenNotEmptyShouldReturnFalse() { assertThat(ConfigurationPropertyName.of("x").isEmpty()).isFalse(); } @Test - public void isLastElementIndexedWhenIndexedShouldReturnTrue() { + void isLastElementIndexedWhenIndexedShouldReturnTrue() { assertThat(ConfigurationPropertyName.of("foo[0]").isLastElementIndexed()).isTrue(); } @Test - public void isLastElementIndexedWhenNotIndexedShouldReturnFalse() { + void isLastElementIndexedWhenNotIndexedShouldReturnFalse() { assertThat(ConfigurationPropertyName.of("foo.bar").isLastElementIndexed()).isFalse(); assertThat(ConfigurationPropertyName.of("foo[0].bar").isLastElementIndexed()).isFalse(); } @Test - public void getLastElementShouldGetLastElement() { + void getLastElementShouldGetLastElement() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("foo.bAr", '.'); assertThat(name.getLastElement(Form.ORIGINAL)).isEqualTo("bAr"); assertThat(name.getLastElement(Form.UNIFORM)).isEqualTo("bar"); } @Test - public void getLastElementWhenEmptyShouldReturnEmptyString() { + void getLastElementWhenEmptyShouldReturnEmptyString() { ConfigurationPropertyName name = ConfigurationPropertyName.EMPTY; assertThat(name.getLastElement(Form.ORIGINAL)).isEqualTo(""); assertThat(name.getLastElement(Form.UNIFORM)).isEqualTo(""); } @Test - public void getElementShouldNotIncludeAngleBrackets() { + void getElementShouldNotIncludeAngleBrackets() { ConfigurationPropertyName name = ConfigurationPropertyName.of("[foo]"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("foo"); assertThat(name.getElement(0, Form.UNIFORM)).isEqualTo("foo"); } @Test - public void getElementInUniformFormShouldNotIncludeDashes() { + void getElementInUniformFormShouldNotIncludeDashes() { ConfigurationPropertyName name = ConfigurationPropertyName.of("f-o-o"); assertThat(name.getElement(0, Form.ORIGINAL)).isEqualTo("f-o-o"); assertThat(name.getElement(0, Form.UNIFORM)).isEqualTo("foo"); } @Test - public void getElementInOriginalFormShouldReturnElement() { + void getElementInOriginalFormShouldReturnElement() { assertThat(getElements("foo.bar", Form.ORIGINAL)).containsExactly("foo", "bar"); assertThat(getElements("foo[0]", Form.ORIGINAL)).containsExactly("foo", "0"); assertThat(getElements("foo.[0]", Form.ORIGINAL)).containsExactly("foo", "0"); @@ -352,7 +352,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void getElementInUniformFormShouldReturnElement() { + void getElementInUniformFormShouldReturnElement() { assertThat(getElements("foo.bar", Form.UNIFORM)).containsExactly("foo", "bar"); assertThat(getElements("foo[0]", Form.UNIFORM)).containsExactly("foo", "0"); assertThat(getElements("foo.[0]", Form.UNIFORM)).containsExactly("foo", "0"); @@ -373,7 +373,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void getNumberOfElementsShouldReturnNumberOfElement() { + void getNumberOfElementsShouldReturnNumberOfElement() { assertThat(ConfigurationPropertyName.of("").getNumberOfElements()).isEqualTo(0); assertThat(ConfigurationPropertyName.of("x").getNumberOfElements()).isEqualTo(1); assertThat(ConfigurationPropertyName.of("x.y").getNumberOfElements()).isEqualTo(2); @@ -381,64 +381,64 @@ public class ConfigurationPropertyNameTests { } @Test - public void appendWhenNotIndexedShouldAppendWithDot() { + void appendWhenNotIndexedShouldAppendWithDot() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); assertThat(name.append("bar").toString()).isEqualTo("foo.bar"); } @Test - public void appendWhenIndexedShouldAppendWithBrackets() { + void appendWhenIndexedShouldAppendWithBrackets() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo").append("[bar]"); assertThat(name.isLastElementIndexed()).isTrue(); assertThat(name.toString()).isEqualTo("foo[bar]"); } @Test - public void appendWhenElementNameIsNotValidShouldThrowException() { + void appendWhenElementNameIsNotValidShouldThrowException() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) .withMessageContaining("Configuration property name '-bar' is not valid"); } @Test - public void appendWhenElementNameMultiDotShouldThrowException() { + void appendWhenElementNameMultiDotShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of("foo").append("bar.baz")) .withMessageContaining("Element value 'bar.baz' must be a single item"); } @Test - public void appendWhenElementNameIsNullShouldReturnName() { + void appendWhenElementNameIsNullShouldReturnName() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); assertThat((Object) name.append((String) null)).isSameAs(name); } @Test - public void chopWhenLessThenSizeShouldReturnChopped() { + void chopWhenLessThenSizeShouldReturnChopped() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.chop(1).toString()).isEqualTo("foo"); assertThat(name.chop(2).toString()).isEqualTo("foo.bar"); } @Test - public void chopWhenGreaterThanSizeShouldReturnExisting() { + void chopWhenGreaterThanSizeShouldReturnExisting() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.chop(4)).isEqualTo(name); } @Test - public void chopWhenEqualToSizeShouldReturnExisting() { + void chopWhenEqualToSizeShouldReturnExisting() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.chop(3)).isEqualTo(name); } @Test - public void isParentOfWhenSameShouldReturnFalse() { + void isParentOfWhenSameShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); assertThat(name.isParentOf(name)).isFalse(); } @Test - public void isParentOfWhenParentShouldReturnTrue() { + void isParentOfWhenParentShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertyName child = ConfigurationPropertyName.of("foo.bar"); assertThat(name.isParentOf(child)).isTrue(); @@ -446,7 +446,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isParentOfWhenGrandparentShouldReturnFalse() { + void isParentOfWhenGrandparentShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isParentOf(grandchild)).isFalse(); @@ -454,7 +454,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isParentOfWhenRootReturnTrue() { + void isParentOfWhenRootReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of(""); ConfigurationPropertyName child = ConfigurationPropertyName.of("foo"); ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar"); @@ -464,13 +464,13 @@ public class ConfigurationPropertyNameTests { } @Test - public void isAncestorOfWhenSameShouldReturnFalse() { + void isAncestorOfWhenSameShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); assertThat(name.isAncestorOf(name)).isFalse(); } @Test - public void isAncestorOfWhenParentShouldReturnTrue() { + void isAncestorOfWhenParentShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertyName child = ConfigurationPropertyName.of("foo.bar"); assertThat(name.isAncestorOf(child)).isTrue(); @@ -478,7 +478,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isAncestorOfWhenGrandparentShouldReturnTrue() { + void isAncestorOfWhenGrandparentShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isAncestorOf(grandchild)).isTrue(); @@ -486,7 +486,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isAncestorOfWhenRootShouldReturnTrue() { + void isAncestorOfWhenRootShouldReturnTrue() { ConfigurationPropertyName name = ConfigurationPropertyName.of(""); ConfigurationPropertyName grandchild = ConfigurationPropertyName.of("foo.bar.baz"); assertThat(name.isAncestorOf(grandchild)).isTrue(); @@ -494,7 +494,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void compareShouldSortNames() { + void compareShouldSortNames() { List names = new ArrayList<>(); names.add(ConfigurationPropertyName.of("foo[10]")); names.add(ConfigurationPropertyName.of("foo.bard")); @@ -508,7 +508,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void compareDifferentLengthsShouldSortNames() { + void compareDifferentLengthsShouldSortNames() { ConfigurationPropertyName name = ConfigurationPropertyName.of("spring.resources.chain.strategy.content"); ConfigurationPropertyName other = ConfigurationPropertyName .of("spring.resources.chain.strategy.content.enabled"); @@ -516,19 +516,19 @@ public class ConfigurationPropertyNameTests { } @Test - public void toStringShouldBeLowerCaseDashed() { + void toStringShouldBeLowerCaseDashed() { ConfigurationPropertyName name = ConfigurationPropertyName.adapt("fOO.b_-a-r", '.'); assertThat(name.toString()).isEqualTo("foo.b-a-r"); } @Test - public void toStringFromOfShouldBeLowerCaseDashed() { + void toStringFromOfShouldBeLowerCaseDashed() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo.bar-baz"); assertThat(name.toString()).isEqualTo("foo.bar-baz"); } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { ConfigurationPropertyName n01 = ConfigurationPropertyName.of("foo[bar]"); ConfigurationPropertyName n02 = ConfigurationPropertyName.of("foo[bar]"); ConfigurationPropertyName n03 = ConfigurationPropertyName.of("foo.bar"); @@ -565,7 +565,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void equalsWhenStartsWith() { + void equalsWhenStartsWith() { // gh-14665 ConfigurationPropertyName n1 = ConfigurationPropertyName.of("my.sources[0].xame"); ConfigurationPropertyName n2 = ConfigurationPropertyName.of("my.sources[0].xamespace"); @@ -573,7 +573,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void equalsWhenStartsWithOfAdaptedName() { + void equalsWhenStartsWithOfAdaptedName() { // gh-15152 ConfigurationPropertyName n1 = ConfigurationPropertyName.adapt("example.mymap.ALPHA", '.'); ConfigurationPropertyName n2 = ConfigurationPropertyName.adapt("example.mymap.ALPHA_BRAVO", '.'); @@ -581,7 +581,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void equalsWhenStartsWithOfAdaptedNameOfIllegalChars() { + void equalsWhenStartsWithOfAdaptedNameOfIllegalChars() { // gh-15152 ConfigurationPropertyName n1 = ConfigurationPropertyName.adapt("example.mymap.ALPH!", '.'); ConfigurationPropertyName n2 = ConfigurationPropertyName.adapt("example.mymap.ALPHA!BRAVO", '.'); @@ -589,7 +589,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void equalsWhenNameStartsTheSameUsingDashedCompare() { + void equalsWhenNameStartsTheSameUsingDashedCompare() { // gh-16855 ConfigurationPropertyName n1 = ConfigurationPropertyName.of("management.metrics.web.server.auto-time-request"); ConfigurationPropertyName n2 = ConfigurationPropertyName.of("management.metrics.web.server.auto-time-requests"); @@ -598,7 +598,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isValidWhenValidShouldReturnTrue() { + void isValidWhenValidShouldReturnTrue() { assertThat(ConfigurationPropertyName.isValid("")).isTrue(); assertThat(ConfigurationPropertyName.isValid("foo")).isTrue(); assertThat(ConfigurationPropertyName.isValid("foo.bar")).isTrue(); @@ -610,7 +610,7 @@ public class ConfigurationPropertyNameTests { } @Test - public void isValidWhenNotValidShouldReturnFalse() { + void isValidWhenNotValidShouldReturnFalse() { assertThat(ConfigurationPropertyName.isValid(null)).isFalse(); assertThat(ConfigurationPropertyName.isValid("-foo")).isFalse(); assertThat(ConfigurationPropertyName.isValid("FooBar")).isFalse(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java index d392d0c0c84..6378f433226 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertySourceTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class ConfigurationPropertySourcesPropertySourceTests { +class ConfigurationPropertySourcesPropertySourceTests { private List configurationSources = new ArrayList<>(); @@ -37,13 +37,13 @@ public class ConfigurationPropertySourcesPropertySourceTests { "test", this.configurationSources); @Test - public void getPropertyShouldReturnValue() { + void getPropertyShouldReturnValue() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("foo.bar")).isEqualTo("baz"); } @Test - public void getPropertyWhenNameIsNotValidShouldReturnNull() { + void getPropertyWhenNameIsNotValidShouldReturnNull() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("FOO.B-A-R")).isNull(); assertThat(this.propertySource.getProperty("FOO.B A R")).isNull(); @@ -51,37 +51,37 @@ public class ConfigurationPropertySourcesPropertySourceTests { } @Test - public void getPropertyWhenMultipleShouldReturnFirst() { + void getPropertyWhenMultipleShouldReturnFirst() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "bill")); assertThat(this.propertySource.getProperty("foo.bar")).isEqualTo("baz"); } @Test - public void getPropertyWhenNoneShouldReturnFirst() { + void getPropertyWhenNoneShouldReturnFirst() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz")); assertThat(this.propertySource.getProperty("foo.foo")).isNull(); } @Test - public void getPropertyOriginShouldReturnOrigin() { + void getPropertyOriginShouldReturnOrigin() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); assertThat(this.propertySource.getOrigin("foo.bar").toString()).isEqualTo("line1"); } @Test - public void getPropertyOriginWhenMissingShouldReturnNull() { + void getPropertyOriginWhenMissingShouldReturnNull() { this.configurationSources.add(new MockConfigurationPropertySource("foo.bar", "baz", "line1")); assertThat(this.propertySource.getOrigin("foo.foo")).isNull(); } @Test - public void getNameShouldReturnName() { + void getNameShouldReturnName() { assertThat(this.propertySource.getName()).isEqualTo("test"); } @Test - public void getSourceShouldReturnSource() { + void getSourceShouldReturnSource() { assertThat(this.propertySource.getSource()).isSameAs(this.configurationSources); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java index d30480d9364..52e9f9be3b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; @@ -39,10 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ConfigurationPropertySourcesTests { +class ConfigurationPropertySourcesTests { @Test - public void attachShouldAddAdapterAtBeginning() { + void attachShouldAddAdapterAtBeginning() { ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources sources = environment.getPropertySources(); sources.addLast(new SystemEnvironmentPropertySource("system", Collections.singletonMap("SERVER_PORT", "1234"))); @@ -55,7 +55,7 @@ public class ConfigurationPropertySourcesTests { } @Test - public void attachShouldReAttachInMergedSetup() { + void attachShouldReAttachInMergedSetup() { ConfigurableEnvironment parent = new StandardEnvironment(); ConfigurationPropertySources.attach(parent); ConfigurableEnvironment child = new StandardEnvironment(); @@ -67,13 +67,13 @@ public class ConfigurationPropertySourcesTests { } @Test - public void getWhenNotAttachedShouldReturnAdapted() { + void getWhenNotAttachedShouldReturnAdapted() { ConfigurableEnvironment environment = new StandardEnvironment(); assertThat(ConfigurationPropertySources.get(environment)).isNotEmpty(); } @Test - public void getWhenAttachedShouldReturnAttached() { + void getWhenAttachedShouldReturnAttached() { ConfigurableEnvironment environment = new StandardEnvironment(); MutablePropertySources sources = environment.getPropertySources(); sources.addFirst(new MapPropertySource("test", Collections.singletonMap("a", "b"))); @@ -83,7 +83,7 @@ public class ConfigurationPropertySourcesTests { } @Test - public void environmentPropertyExpansionShouldWorkWhenAttached() { + void environmentPropertyExpansionShouldWorkWhenAttached() { ConfigurableEnvironment environment = new StandardEnvironment(); Map source = new LinkedHashMap<>(); source.put("fooBar", "Spring ${barBaz} ${bar-baz}"); @@ -95,7 +95,7 @@ public class ConfigurationPropertySourcesTests { } @Test - public void fromPropertySourceShouldReturnSpringConfigurationPropertySource() { + void fromPropertySourceShouldReturnSpringConfigurationPropertySource() { PropertySource source = new MapPropertySource("foo", Collections.singletonMap("foo", "bar")); ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source).iterator() .next(); @@ -103,7 +103,7 @@ public class ConfigurationPropertySourcesTests { } @Test - public void fromPropertySourceShouldFlattenPropertySources() { + void fromPropertySourceShouldFlattenPropertySources() { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); environment.getPropertySources().addFirst(new MapPropertySource("far", Collections.singletonMap("far", "far"))); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java index ef83463ea3e..6663cb26ced 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java @@ -20,7 +20,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -30,30 +30,30 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ConfigurationPropertyStateTests { +class ConfigurationPropertyStateTests { @Test - public void searchWhenIterableIsNullShouldThrowException() { + void searchWhenIterableIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) .withMessageContaining("Source must not be null"); } @Test - public void searchWhenPredicateIsNullShouldThrowException() { + void searchWhenPredicateIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) .withMessageContaining("Predicate must not be null"); } @Test - public void searchWhenContainsItemShouldReturnPresent() { + void searchWhenContainsItemShouldReturnPresent() { List source = Arrays.asList("a", "b", "c"); ConfigurationPropertyState result = ConfigurationPropertyState.search(source, "b"::equals); assertThat(result).isEqualTo(ConfigurationPropertyState.PRESENT); } @Test - public void searchWhenContainsNoItemShouldReturnAbsent() { + void searchWhenContainsNoItemShouldReturnAbsent() { List source = Arrays.asList("a", "x", "c"); ConfigurationPropertyState result = ConfigurationPropertyState.search(source, "b"::equals); assertThat(result).isEqualTo(ConfigurationPropertyState.ABSENT); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java index b7922f412a3..b00822b7ba7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginProvider; @@ -31,43 +31,43 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class ConfigurationPropertyTests { +class ConfigurationPropertyTests { private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Test - public void createWhenNameIsNullShouldThrowException() { + void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) .withMessageContaining("Name must not be null"); } @Test - public void createWhenValueIsNullShouldThrowException() { + void createWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) .withMessageContaining("Value must not be null"); } @Test - public void getNameShouldReturnName() { + void getNameShouldReturnName() { ConfigurationProperty property = ConfigurationProperty.of(NAME, "foo", null); assertThat((Object) property.getName()).isEqualTo(NAME); } @Test - public void getValueShouldReturnValue() { + void getValueShouldReturnValue() { ConfigurationProperty property = ConfigurationProperty.of(NAME, "foo", null); assertThat(property.getValue()).isEqualTo("foo"); } @Test - public void getPropertyOriginShouldReturnValuePropertyOrigin() { + void getPropertyOriginShouldReturnValuePropertyOrigin() { Origin origin = mock(Origin.class); OriginProvider property = ConfigurationProperty.of(NAME, "foo", origin); assertThat(property.getOrigin()).isEqualTo(origin); } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { ConfigurationProperty property1 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "bar", null); ConfigurationProperty property2 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "bar", null); ConfigurationProperty property3 = new ConfigurationProperty(ConfigurationPropertyName.of("foo"), "baz", null); @@ -77,7 +77,7 @@ public class ConfigurationPropertyTests { } @Test - public void toStringShouldReturnValue() { + void toStringShouldReturnValue() { ConfigurationProperty property = ConfigurationProperty.of(NAME, "foo", null); assertThat(property.toString()).contains("name").contains("value"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java index b52fcd0b27d..3ee430b5227 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/DefaultPropertyMapperTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { +class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { @Override protected PropertyMapper getMapper() { @@ -34,7 +34,7 @@ public class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { } @Test - public void mapFromStringShouldReturnBestGuess() { + void mapFromStringShouldReturnBestGuess() { assertThat(namesFromString("server")).toIterable().containsExactly("server"); assertThat(namesFromString("server.port")).toIterable().containsExactly("server.port"); assertThat(namesFromString("host[0]")).toIterable().containsExactly("host[0]"); @@ -49,7 +49,7 @@ public class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { } @Test - public void mapFromConfigurationShouldReturnBestGuess() { + void mapFromConfigurationShouldReturnBestGuess() { assertThat(namesFromConfiguration("server")).toIterable().containsExactly("server"); assertThat(namesFromConfiguration("server.port")).toIterable().containsExactly("server.port"); assertThat(namesFromConfiguration("host[0]")).toIterable().containsExactly("host[0]"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java index 1794eeaeab2..262dbf4d7d2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.context.properties.source; import java.util.Objects; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.assertj.core.api.Assertions.assertThat; @@ -32,17 +32,17 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class FilteredConfigurationPropertiesSourceTests { +class FilteredConfigurationPropertiesSourceTests { @Test - public void createWhenSourceIsNullShouldThrowException() { + void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) .withMessageContaining("Source must not be null"); } @Test - public void createWhenFilterIsNullShouldThrowException() { + void createWhenFilterIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) @@ -50,7 +50,7 @@ public class FilteredConfigurationPropertiesSourceTests { } @Test - public void getValueShouldFilterNames() { + void getValueShouldFilterNames() { ConfigurationPropertySource source = createTestSource(); ConfigurationPropertySource filtered = source.filter(this::noBrackets); ConfigurationPropertyName name = ConfigurationPropertyName.of("a"); @@ -62,7 +62,7 @@ public class FilteredConfigurationPropertiesSourceTests { } @Test - public void containsDescendantOfWhenSourceReturnsEmptyShouldReturnEmpty() { + void containsDescendantOfWhenSourceReturnsEmptyShouldReturnEmpty() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.UNKNOWN); @@ -71,7 +71,7 @@ public class FilteredConfigurationPropertiesSourceTests { } @Test - public void containsDescendantOfWhenSourceReturnsFalseShouldReturnFalse() { + void containsDescendantOfWhenSourceReturnsFalseShouldReturnFalse() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.ABSENT); @@ -80,7 +80,7 @@ public class FilteredConfigurationPropertiesSourceTests { } @Test - public void containsDescendantOfWhenSourceReturnsTrueShouldReturnEmpty() { + void containsDescendantOfWhenSourceReturnsTrueShouldReturnEmpty() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, Answers.CALLS_REAL_METHODS); given(source.containsDescendantOf(name)).willReturn(ConfigurationPropertyState.PRESENT); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java index bbc309f48da..124f082e256 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigurationPropertiesSourceTests { +class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigurationPropertiesSourceTests { @Test - public void iteratorShouldFilterNames() { + void iteratorShouldFilterNames() { MockConfigurationPropertySource source = (MockConfigurationPropertySource) createTestSource(); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); assertThat(filtered.iterator()).toIterable().extracting(ConfigurationPropertyName::toString) @@ -42,7 +42,7 @@ public class FilteredIterableConfigurationPropertiesSourceTests extends Filtered } @Test - public void containsDescendantOfShouldUseContents() { + void containsDescendantOfShouldUseContents() { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.bar.baz", "1"); source.put("foo.bar[0]", "1"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java index 9b2d625ba07..c7b4b2798ee 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -30,16 +30,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ -public class MapConfigurationPropertySourceTests { +class MapConfigurationPropertySourceTests { @Test - public void createWhenMapIsNullShouldThrowException() { + void createWhenMapIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new MapConfigurationPropertySource(null)) .withMessageContaining("Map must not be null"); } @Test - public void createWhenMapHasEntriesShouldAdaptMap() { + void createWhenMapHasEntriesShouldAdaptMap() { Map map = new LinkedHashMap<>(); map.put("foo.BAR", "spring"); map.put(ConfigurationPropertyName.of("foo.baz"), "boot"); @@ -49,14 +49,14 @@ public class MapConfigurationPropertySourceTests { } @Test - public void putAllWhenMapIsNullShouldThrowException() { + void putAllWhenMapIsNullShouldThrowException() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); assertThatIllegalArgumentException().isThrownBy(() -> source.putAll(null)) .withMessageContaining("Map must not be null"); } @Test - public void putAllShouldPutEntries() { + void putAllShouldPutEntries() { Map map = new LinkedHashMap<>(); map.put("foo.BAR", "spring"); map.put("foo.baz", "boot"); @@ -67,14 +67,14 @@ public class MapConfigurationPropertySourceTests { } @Test - public void putShouldPutEntry() { + void putShouldPutEntry() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.bar", "baz"); assertThat(getValue(source, "foo.bar")).isEqualTo("baz"); } @Test - public void getConfigurationPropertyShouldGetFromMemory() { + void getConfigurationPropertyShouldGetFromMemory() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.bar", "baz"); assertThat(getValue(source, "foo.bar")).isEqualTo("baz"); @@ -83,7 +83,7 @@ public class MapConfigurationPropertySourceTests { } @Test - public void iteratorShouldGetFromMemory() { + void iteratorShouldGetFromMemory() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); @@ -92,7 +92,7 @@ public class MapConfigurationPropertySourceTests { } @Test - public void streamShouldGetFromMemory() { + void streamShouldGetFromMemory() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java index b7a02c24ec5..bbcb0466d62 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginLookup; @@ -36,24 +36,24 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Madhura Bhave */ -public class SpringConfigurationPropertySourceTests { +class SpringConfigurationPropertySourceTests { @Test - public void createWhenPropertySourceIsNullShouldThrowException() { + void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class), null)) .withMessageContaining("PropertySource must not be null"); } @Test - public void createWhenMapperIsNullShouldThrowException() { + void createWhenMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringConfigurationPropertySource(mock(PropertySource.class), null, null)) .withMessageContaining("Mapper must not be null"); } @Test - public void getValueShouldUseDirectMapping() { + void getValueShouldUseDirectMapping() { Map source = new LinkedHashMap<>(); source.put("key1", "value1"); source.put("key2", "value2"); @@ -67,7 +67,7 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void getValueOrigin() { + void getValueOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); PropertySource propertySource = new MapPropertySource("test", source); @@ -80,7 +80,7 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void getValueWhenOriginCapableShouldIncludeSourceOrigin() { + void getValueWhenOriginCapableShouldIncludeSourceOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); PropertySource propertySource = new OriginCapablePropertySource<>(new MapPropertySource("test", source)); @@ -92,7 +92,7 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void containsDescendantOfShouldReturnEmpty() { + void containsDescendantOfShouldReturnEmpty() { Map source = new LinkedHashMap<>(); source.put("foo.bar", "value"); PropertySource propertySource = new MapPropertySource("test", source); @@ -103,13 +103,13 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void fromWhenPropertySourceIsNullShouldThrowException() { + void fromWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> SpringConfigurationPropertySource.from(null)) .withMessageContaining("Source must not be null"); } @Test - public void fromWhenNonEnumerableShouldReturnNonIterable() { + void fromWhenNonEnumerableShouldReturnNonIterable() { PropertySource propertySource = new PropertySource("test", new Object()) { @Override @@ -124,7 +124,7 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void fromWhenEnumerableButRestrictedShouldReturnNonIterable() { + void fromWhenEnumerableButRestrictedShouldReturnNonIterable() { Map source = new LinkedHashMap() { @Override @@ -139,7 +139,7 @@ public class SpringConfigurationPropertySourceTests { } @Test - public void getWhenEnumerableShouldBeIterable() { + void getWhenEnumerableShouldBeIterable() { Map source = new LinkedHashMap<>(); source.put("fooBar", "Spring ${barBaz} ${bar-baz}"); source.put("barBaz", "Boot"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java index 98879de964b..6fed843b7c8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.Collections; import java.util.Iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; @@ -37,16 +37,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ -public class SpringConfigurationPropertySourcesTests { +class SpringConfigurationPropertySourcesTests { @Test - public void createWhenPropertySourcesIsNullShouldThrowException() { + void createWhenPropertySourcesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringConfigurationPropertySources(null)) .withMessageContaining("Sources must not be null"); } @Test - public void shouldAdaptPropertySource() { + void shouldAdaptPropertySource() { MutablePropertySources sources = new MutablePropertySources(); sources.addFirst(new MapPropertySource("test", Collections.singletonMap("a", "b"))); Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); @@ -56,7 +56,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldAdaptSystemEnvironmentPropertySource() { + void shouldAdaptSystemEnvironmentPropertySource() { MutablePropertySources sources = new MutablePropertySources(); sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("SERVER_PORT", "1234"))); @@ -67,7 +67,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldExtendedAdaptSystemEnvironmentPropertySource() { + void shouldExtendedAdaptSystemEnvironmentPropertySource() { MutablePropertySources sources = new MutablePropertySources(); sources.addLast(new SystemEnvironmentPropertySource( "test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, @@ -79,7 +79,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() { + void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() { MutablePropertySources sources = new MutablePropertySources(); sources.addLast( new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); @@ -90,7 +90,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldAdaptSystemEnvironmentPropertySourceWithUnderscoreValue() { + void shouldAdaptSystemEnvironmentPropertySourceWithUnderscoreValue() { MutablePropertySources sources = new MutablePropertySources(); sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("_", "1234"))); @@ -101,7 +101,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldAdaptMultiplePropertySources() { + void shouldAdaptMultiplePropertySources() { MutablePropertySources sources = new MutablePropertySources(); sources.addLast(new SystemEnvironmentPropertySource("system", Collections.singletonMap("SERVER_PORT", "1234"))); sources.addLast(new MapPropertySource("test1", Collections.singletonMap("server.po-rt", "4567"))); @@ -116,7 +116,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldFlattenEnvironment() { + void shouldFlattenEnvironment() { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("foo", Collections.singletonMap("foo", "bar"))); environment.getPropertySources().addFirst(new MapPropertySource("far", Collections.singletonMap("far", "far"))); @@ -135,7 +135,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldTrackChanges() { + void shouldTrackChanges() { MutablePropertySources sources = new MutablePropertySources(); SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); assertThat(configurationSources.iterator()).toIterable().hasSize(0); @@ -148,7 +148,7 @@ public class SpringConfigurationPropertySourcesTests { } @Test - public void shouldTrackWhenSourceHasIdenticalName() { + void shouldTrackWhenSourceHasIdenticalName() { MutablePropertySources sources = new MutablePropertySources(); SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); ConfigurationPropertyName name = ConfigurationPropertyName.of("a"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java index d14139d5f3c..2b72b916e86 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java @@ -23,7 +23,7 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.env.OriginTrackedMapPropertySource; import org.springframework.boot.origin.Origin; @@ -43,17 +43,17 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Fahim Farook */ -public class SpringIterableConfigurationPropertySourceTests { +class SpringIterableConfigurationPropertySourceTests { @Test - public void createWhenPropertySourceIsNullShouldThrowException() { + void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) .withMessageContaining("PropertySource must not be null"); } @Test - public void createWhenMapperIsNullShouldThrowException() { + void createWhenMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new SpringIterableConfigurationPropertySource(mock(EnumerablePropertySource.class), null)) @@ -61,7 +61,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void iteratorShouldAdaptNames() { + void iteratorShouldAdaptNames() { Map source = new LinkedHashMap<>(); source.put("key1", "value1"); source.put("key2", "value2"); @@ -79,7 +79,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void getValueShouldUseDirectMapping() { + void getValueShouldUseDirectMapping() { Map source = new LinkedHashMap<>(); source.put("key1", "value1"); source.put("key2", "value2"); @@ -94,7 +94,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void getValueShouldUseEnumerableMapping() { + void getValueShouldUseEnumerableMapping() { Map source = new LinkedHashMap<>(); source.put("key1", "value1"); source.put("key2", "value2"); @@ -110,7 +110,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void getValueOrigin() { + void getValueOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); EnumerablePropertySource propertySource = new MapPropertySource("test", source); @@ -124,7 +124,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void getValueWhenOriginCapableShouldIncludeSourceOrigin() { + void getValueWhenOriginCapableShouldIncludeSourceOrigin() { Map source = new LinkedHashMap<>(); source.put("key", "value"); EnumerablePropertySource propertySource = new OriginCapablePropertySource<>( @@ -138,7 +138,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void containsDescendantOfShouldCheckSourceNames() { + void containsDescendantOfShouldCheckSourceNames() { Map source = new LinkedHashMap<>(); source.put("foo.bar", "value"); source.put("faf", "value"); @@ -155,7 +155,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void simpleMapPropertySourceKeyDataChangeInvalidatesCache() { + void simpleMapPropertySourceKeyDataChangeInvalidatesCache() { // gh-13344 Map map = new LinkedHashMap<>(); map.put("key1", "value1"); @@ -169,7 +169,7 @@ public class SpringIterableConfigurationPropertySourceTests { } @Test - public void concurrentModificationExceptionInvalidatesCache() { + void concurrentModificationExceptionInvalidatesCache() { // gh-17013 ConcurrentModificationThrowingMap map = new ConcurrentModificationThrowingMap<>(); map.put("key1", "value1"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java index 2d5cba0228f..64f03abaac8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.context.properties.source; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapperTests { +class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapperTests { @Override protected PropertyMapper getMapper() { @@ -34,7 +34,7 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper } @Test - public void mapFromStringShouldReturnBestGuess() { + void mapFromStringShouldReturnBestGuess() { assertThat(namesFromString("SERVER")).toIterable().containsExactly("server"); assertThat(namesFromString("SERVER_PORT")).toIterable().containsExactly("server.port"); assertThat(namesFromString("HOST_0")).toIterable().containsExactly("host[0]"); @@ -45,7 +45,7 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper } @Test - public void mapFromConfigurationShouldReturnBestGuess() { + void mapFromConfigurationShouldReturnBestGuess() { assertThat(namesFromConfiguration("server")).toIterable().containsExactly("SERVER"); assertThat(namesFromConfiguration("server.port")).toIterable().containsExactly("SERVER_PORT"); assertThat(namesFromConfiguration("host[0]")).toIterable().containsExactly("HOST_0"); @@ -56,7 +56,7 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper } @Test - public void underscoreShouldNotMapToEmptyString() { + void underscoreShouldNotMapToEmptyString() { PropertyMapping[] mappings = getMapper().map("_"); boolean applicable = false; for (PropertyMapping mapping : mappings) { @@ -66,7 +66,7 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper } @Test - public void underscoreWithWhitespaceShouldNotMapToEmptyString() { + void underscoreWithWhitespaceShouldNotMapToEmptyString() { PropertyMapping[] mappings = getMapper().map(" _"); boolean applicable = false; for (PropertyMapping mapping : mappings) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilterTests.java index faa39822e5d..76c746d1154 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.boot.context.properties.source; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.env.MockPropertySource; @@ -31,20 +31,20 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class UnboundElementsSourceFilterTests { +class UnboundElementsSourceFilterTests { private UnboundElementsSourceFilter filter; private ConfigurationPropertySource source; - @Before + @BeforeEach public void setUp() { this.filter = new UnboundElementsSourceFilter(); this.source = mock(ConfigurationPropertySource.class); } @Test - public void filterWhenSourceIsSystemPropertiesPropertySourceShouldReturnFalse() { + void filterWhenSourceIsSystemPropertiesPropertySourceShouldReturnFalse() { MockPropertySource propertySource = new MockPropertySource( StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); given(this.source.getUnderlyingSource()).willReturn(propertySource); @@ -52,7 +52,7 @@ public class UnboundElementsSourceFilterTests { } @Test - public void filterWhenSourceIsSystemEnvironmentPropertySourceShouldReturnFalse() { + void filterWhenSourceIsSystemEnvironmentPropertySourceShouldReturnFalse() { MockPropertySource propertySource = new MockPropertySource( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); given(this.source.getUnderlyingSource()).willReturn(propertySource); @@ -60,7 +60,7 @@ public class UnboundElementsSourceFilterTests { } @Test - public void filterWhenSourceIsNotSystemShouldReturnTrue() { + void filterWhenSourceIsNotSystemShouldReturnTrue() { MockPropertySource propertySource = new MockPropertySource("test"); given(this.source.getUnderlyingSource()).willReturn(propertySource); assertThat(this.filter.apply(this.source)).isTrue(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java index 2a97d68351f..40a7720a0b7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java @@ -16,14 +16,13 @@ package org.springframework.boot.convert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; -import org.springframework.format.support.FormattingConversionService; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -33,68 +32,55 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class ArrayToDelimitedStringConverterTests { +class ArrayToDelimitedStringConverterTests { - private final ConversionService conversionService; - - public ArrayToDelimitedStringConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertListToStringShouldConvert() { + @ConversionServiceTest + void convertListToStringShouldConvert(ConversionService conversionService) { String[] list = { "a", "b", "c" }; - String converted = this.conversionService.convert(list, String.class); + String converted = conversionService.convert(list, String.class); assertThat(converted).isEqualTo("a,b,c"); } - @Test - public void convertWhenHasDelimiterNoneShouldConvert() { + @ConversionServiceTest + void convertWhenHasDelimiterNoneShouldConvert(ConversionService conversionService) { Data data = new Data(); data.none = new String[] { "1", "2", "3" }; - String converted = (String) this.conversionService.convert(data.none, + String converted = (String) conversionService.convert(data.none, TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "none"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("123"); } - @Test - public void convertWhenHasDelimiterDashShouldConvert() { + @ConversionServiceTest + void convertWhenHasDelimiterDashShouldConvert(ConversionService conversionService) { Data data = new Data(); data.dash = new String[] { "1", "2", "3" }; - String converted = (String) this.conversionService.convert(data.dash, + String converted = (String) conversionService.convert(data.dash, TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "dash"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1-2-3"); } - @Test - public void convertShouldConvertElements() { - if (this.conversionService instanceof ApplicationConversionService) { - Data data = new Data(); - data.type = new int[] { 1, 2, 3 }; - String converted = (String) this.conversionService.convert(data.type, - TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), - TypeDescriptor.valueOf(String.class)); - assertThat(converted).isEqualTo("1.2.3"); - } - } - - @Test - public void convertShouldConvertNull() { + @ConversionServiceTest + void convertShouldConvertNull(ConversionService conversionService) { String[] list = null; - String converted = this.conversionService.convert(list, String.class); + String converted = conversionService.convert(list, String.class); assertThat(converted).isNull(); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(ArrayToDelimitedStringConverterTests::addConverter); + @Test + void convertShouldConvertElements() { + Data data = new Data(); + data.type = new int[] { 1, 2, 3 }; + String converted = (String) new ApplicationConversionService().convert(data.type, + TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), + TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("1.2.3"); } - private static void addConverter(FormattingConversionService service) { - service.addConverter(new ArrayToDelimitedStringConverter(service)); + static Stream conversionServices() { + return ConversionServiceArguments + .with((service) -> service.addConverter(new ArrayToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CharArrayFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CharArrayFormatterTests.java index a8feedf88bd..f323128d982 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CharArrayFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CharArrayFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,9 @@ package org.springframework.boot.convert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; + +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; @@ -30,32 +29,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class CharArrayFormatterTests { +class CharArrayFormatterTests { - private final ConversionService conversionService; - - public CharArrayFormatterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertFromCharArrayToStringShouldConvert() { + @ConversionServiceTest + void convertFromCharArrayToStringShouldConvert(ConversionService conversionService) { char[] source = { 'b', 'o', 'o', 't' }; - String converted = this.conversionService.convert(source, String.class); + String converted = conversionService.convert(source, String.class); assertThat(converted).isEqualTo("boot"); } - @Test - public void convertFromStringToCharArrayShouldConvert() { + @ConversionServiceTest + void convertFromStringToCharArrayShouldConvert(ConversionService conversionService) { String source = "boot"; - char[] converted = this.conversionService.convert(source, char[].class); + char[] converted = conversionService.convert(source, char[].class); assertThat(converted).containsExactly('b', 'o', 'o', 't'); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new CharArrayFormatter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new CharArrayFormatter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java index c0bdbecd6c2..e75f1faf9da 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java @@ -18,15 +18,13 @@ package org.springframework.boot.convert; import java.util.Arrays; import java.util.List; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; -import org.springframework.format.support.FormattingConversionService; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -36,68 +34,55 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class CollectionToDelimitedStringConverterTests { +class CollectionToDelimitedStringConverterTests { - private final ConversionService conversionService; - - public CollectionToDelimitedStringConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertListToStringShouldConvert() { + @ConversionServiceTest + void convertListToStringShouldConvert(ConversionService conversionService) { List list = Arrays.asList("a", "b", "c"); - String converted = this.conversionService.convert(list, String.class); + String converted = conversionService.convert(list, String.class); assertThat(converted).isEqualTo("a,b,c"); } - @Test - public void convertWhenHasDelimiterNoneShouldConvert() { + @ConversionServiceTest + void convertWhenHasDelimiterNoneShouldConvert(ConversionService conversionService) { Data data = new Data(); data.none = Arrays.asList("1", "2", "3"); - String converted = (String) this.conversionService.convert(data.none, + String converted = (String) conversionService.convert(data.none, TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "none"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("123"); } - @Test - public void convertWhenHasDelimiterDashShouldConvert() { + @ConversionServiceTest + void convertWhenHasDelimiterDashShouldConvert(ConversionService conversionService) { Data data = new Data(); data.dash = Arrays.asList("1", "2", "3"); - String converted = (String) this.conversionService.convert(data.dash, + String converted = (String) conversionService.convert(data.dash, TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "dash"), 0), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1-2-3"); } - @Test - public void convertShouldConvertElements() { - if (this.conversionService instanceof ApplicationConversionService) { - Data data = new Data(); - data.type = Arrays.asList(1, 2, 3); - String converted = (String) this.conversionService.convert(data.type, - TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), - TypeDescriptor.valueOf(String.class)); - assertThat(converted).isEqualTo("1.2.3"); - } - } - - @Test - public void convertShouldConvertNull() { + @ConversionServiceTest + void convertShouldConvertNull(ConversionService conversionService) { List list = null; - String converted = this.conversionService.convert(list, String.class); + String converted = conversionService.convert(list, String.class); assertThat(converted).isNull(); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(CollectionToDelimitedStringConverterTests::addConverter); + @Test + void convertShouldConvertElements() { + Data data = new Data(); + data.type = Arrays.asList(1, 2, 3); + String converted = (String) new ApplicationConversionService().convert(data.type, + TypeDescriptor.nested(ReflectionUtils.findField(Data.class, "type"), 0), + TypeDescriptor.valueOf(String.class)); + assertThat(converted).isEqualTo("1.2.3"); } - private static void addConverter(FormattingConversionService service) { - service.addConverter(new CollectionToDelimitedStringConverter(service)); + static Stream conversionServices() { + return ConversionServiceArguments + .with((service) -> service.addConverter(new CollectionToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java new file mode 100644 index 00000000000..a1ebb96ff80 --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java @@ -0,0 +1,99 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.convert; + +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; + +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.format.Formatter; +import org.springframework.format.support.FormattingConversionService; + +/** + * Factory for creating a {@link Stream stream} of {@link Arguments} for use in a + * {@link ParameterizedTest parameterized test}. + * + * @author Phillip Webb + * @author Andy Wilkinson + */ +final class ConversionServiceArguments { + + private ConversionServiceArguments() { + + } + + static Stream with(Formatter formatter) { + return with((conversionService) -> conversionService.addFormatter(formatter)); + } + + static Stream with(GenericConverter converter) { + return with((conversionService) -> conversionService.addConverter(converter)); + } + + static Stream with(Consumer initializer) { + FormattingConversionService withoutDefaults = new FormattingConversionService(); + initializer.accept(withoutDefaults); + return Stream.of( + Arguments.of(new NamedConversionService(withoutDefaults, "Without defaults conversion service")), + Arguments.of(new NamedConversionService(new ApplicationConversionService(), + "Application conversion service"))); + } + + private static class NamedConversionService implements ConversionService { + + private final ConversionService delegate; + + private final String name; + + NamedConversionService(ConversionService delegate, String name) { + this.delegate = delegate; + this.name = name; + } + + @Override + public boolean canConvert(Class sourceType, Class targetType) { + return this.delegate.canConvert(sourceType, targetType); + } + + @Override + public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) { + return this.delegate.canConvert(sourceType, targetType); + } + + @Override + public T convert(Object source, Class targetType) { + return this.delegate.convert(source, targetType); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + return this.delegate.convert(source, sourceType, targetType); + } + + @Override + public String toString() { + return this.name; + } + + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java deleted file mode 100644 index cf738e26229..00000000000 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceParameters.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.convert; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.function.Consumer; - -import org.junit.runners.Parameterized.Parameters; - -import org.springframework.core.convert.ConversionService; -import org.springframework.core.convert.converter.ConverterFactory; -import org.springframework.core.convert.converter.GenericConverter; -import org.springframework.format.Formatter; -import org.springframework.format.support.FormattingConversionService; - -/** - * Factory to create {@link ConversionService ConversionServices} for test - * {@link Parameters}. - * - * @author Phillip Webb - */ -public class ConversionServiceParameters implements Iterable { - - private final List parameters; - - public ConversionServiceParameters(Formatter formatter) { - this((Consumer) (conversionService) -> conversionService.addFormatter(formatter)); - } - - public ConversionServiceParameters(ConverterFactory converterFactory) { - this((Consumer) (conversionService) -> conversionService - .addConverterFactory(converterFactory)); - } - - public ConversionServiceParameters(GenericConverter converter) { - this((Consumer) (conversionService) -> conversionService.addConverter(converter)); - } - - public ConversionServiceParameters(Consumer initializer) { - FormattingConversionService withoutDefaults = new FormattingConversionService(); - initializer.accept(withoutDefaults); - List parameters = new ArrayList<>(); - parameters.add(new Object[] { "without defaults conversion service", withoutDefaults }); - parameters.add(new Object[] { "application conversion service", new ApplicationConversionService() }); - this.parameters = Collections.unmodifiableList(parameters); - } - - @Override - public Iterator iterator() { - return this.parameters.iterator(); - } - -} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceTest.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceTest.java new file mode 100644 index 00000000000..37ba16740fd --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.convert; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import org.springframework.core.convert.ConversionService; + +/** + * Specialized {@link ParameterizedTest parameterized test} for + * {@link ConversionService}-related testing. Test classes with methods annotated with + * {@link ParameterizedTest @ParameterizedTest} must have a {@code static} + * {@code conversionServices} method that is suitable for use as a {@link MethodSource + * method source}. + * + * @author Andy Wilkinson + */ +@ParameterizedTest +@MethodSource("conversionServices") +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@interface ConversionServiceTest { + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java index 0fc17ddbc54..0ccb3914cfe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java @@ -18,15 +18,13 @@ package org.springframework.boot.convert; import java.util.LinkedList; import java.util.List; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; -import org.springframework.format.support.FormattingConversionService; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -36,74 +34,59 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class DelimitedStringToArrayConverterTests { +class DelimitedStringToArrayConverterTests { - private final ConversionService conversionService; - - public DelimitedStringToArrayConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void canConvertFromStringToArrayShouldReturnTrue(ConversionService conversionService) { + assertThat(conversionService.canConvert(String.class, String[].class)).isTrue(); } - @Test - public void canConvertFromStringToArrayShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, String[].class)).isTrue(); - } - - @Test - public void matchesWhenTargetIsNotAnnotatedShouldReturnTrue() { + @ConversionServiceTest + void matchesWhenTargetIsNotAnnotatedShouldReturnTrue(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) - .isTrue(); + assertThat(new DelimitedStringToArrayConverter(conversionService).matches(sourceType, targetType)).isTrue(); } - @Test - public void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { - if (this.conversionService instanceof ApplicationConversionService) { - TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) - .isTrue(); - } - } - - @Test - public void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse() { + @ConversionServiceTest + void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); - assertThat(new DelimitedStringToArrayConverter(this.conversionService).matches(sourceType, targetType)) - .isFalse(); + assertThat(new DelimitedStringToArrayConverter(conversionService).matches(sourceType, targetType)).isFalse(); } - @Test - public void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { - if (this.conversionService instanceof ApplicationConversionService) { - TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - Integer[] converted = (Integer[]) this.conversionService.convert(" 1 | 2| 3 ", sourceType, targetType); - assertThat(converted).containsExactly(1, 2, 3); - } - } - - @Test - public void convertWhenHasDelimiterOfNoneShouldReturnWholeString() { + @ConversionServiceTest + void convertWhenHasDelimiterOfNoneShouldReturnWholeString(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); - String[] converted = (String[]) this.conversionService.convert("a,b,c", sourceType, targetType); + String[] converted = (String[]) conversionService.convert("a,b,c", sourceType, targetType); assertThat(converted).containsExactly("a,b,c"); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(DelimitedStringToArrayConverterTests::addConverter); + @Test + void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { + TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + assertThat( + new DelimitedStringToArrayConverter(new ApplicationConversionService()).matches(sourceType, targetType)) + .isTrue(); } - private static void addConverter(FormattingConversionService service) { - service.addConverter(new DelimitedStringToArrayConverter(service)); + @Test + void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { + TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + Integer[] converted = (Integer[]) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, + targetType); + assertThat(converted).containsExactly(1, 2, 3); + } + + static Stream conversionServices() { + return ConversionServiceArguments + .with((service) -> service.addConverter(new DelimitedStringToArrayConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java index 52ffb9d2a64..f445f2db63c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java @@ -19,15 +19,13 @@ package org.springframework.boot.convert; import java.util.Collection; import java.util.LinkedList; import java.util.List; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; -import org.springframework.format.support.FormattingConversionService; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -37,105 +35,90 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class DelimitedStringToCollectionConverterTests { +class DelimitedStringToCollectionConverterTests { - private final ConversionService conversionService; - - public DelimitedStringToCollectionConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void canConvertFromStringToCollectionShouldReturnTrue(ConversionService conversionService) { + assertThat(conversionService.canConvert(String.class, Collection.class)).isTrue(); } - @Test - public void canConvertFromStringToCollectionShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, Collection.class)).isTrue(); - } - - @Test - public void matchesWhenTargetIsNotAnnotatedShouldReturnTrue() { + @ConversionServiceTest + void matchesWhenTargetIsNotAnnotatedShouldReturnTrue(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) .isTrue(); } - @Test - public void matchesWhenHasAnnotationAndNoElementTypeShouldReturnTrue() { + @ConversionServiceTest + void matchesWhenHasAnnotationAndNoElementTypeShouldReturnTrue(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) .isTrue(); } - @Test - public void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { - if (this.conversionService instanceof ApplicationConversionService) { - TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) - .isTrue(); - } - } - - @Test - public void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse() { + @ConversionServiceTest + void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); - assertThat(new DelimitedStringToCollectionConverter(this.conversionService).matches(sourceType, targetType)) + assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) .isFalse(); } - @Test + @ConversionServiceTest @SuppressWarnings("unchecked") - public void convertWhenHasNoElementTypeShouldReturnTrimmedString() { + void convertWhenHasNoElementTypeShouldReturnTrimmedString(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); - Collection converted = (Collection) this.conversionService.convert(" a | b| c ", sourceType, + Collection converted = (Collection) conversionService.convert(" a | b| c ", sourceType, targetType); assertThat(converted).containsExactly("a", "b", "c"); } - @Test + @ConversionServiceTest @SuppressWarnings("unchecked") - public void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { - if (this.conversionService instanceof ApplicationConversionService) { - TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); - TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); - List converted = (List) this.conversionService.convert(" 1 | 2| 3 ", sourceType, - targetType); - assertThat(converted).containsExactly(1, 2, 3); - } - } - - @Test - @SuppressWarnings("unchecked") - public void convertWhenHasDelimiterOfNoneShouldReturnWholeString() { + void convertWhenHasDelimiterOfNoneShouldReturnWholeString(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "delimiterNone"), 0); - List converted = (List) this.conversionService.convert("a,b,c", sourceType, targetType); + List converted = (List) conversionService.convert("a,b,c", sourceType, targetType); assertThat(converted).containsExactly("a,b,c"); } @SuppressWarnings("unchecked") - @Test - public void convertWhenHasCollectionObjectTypeShouldUseCollectionObjectType() { + @ConversionServiceTest + void convertWhenHasCollectionObjectTypeShouldUseCollectionObjectType(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "specificType"), 0); - MyCustomList converted = (MyCustomList) this.conversionService.convert("a*b", sourceType, + MyCustomList converted = (MyCustomList) conversionService.convert("a*b", sourceType, targetType); assertThat(converted).containsExactly("a", "b"); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(DelimitedStringToCollectionConverterTests::addConverter); + @Test + void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { + TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + assertThat(new DelimitedStringToCollectionConverter(new ApplicationConversionService()).matches(sourceType, + targetType)).isTrue(); } - private static void addConverter(FormattingConversionService service) { - service.addConverter(new DelimitedStringToCollectionConverter(service)); + @Test + @SuppressWarnings("unchecked") + void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { + TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); + TypeDescriptor targetType = TypeDescriptor + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + List converted = (List) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, + targetType); + assertThat(converted).containsExactly(1, 2, 3); + } + + static Stream conversionServices() { + return ConversionServiceArguments + .with((service) -> service.addConverter(new DelimitedStringToCollectionConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java index 321d5837df1..f440f3b8673 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -29,16 +29,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class DurationStyleTests { +class DurationStyleTests { @Test - public void detectAndParseWhenValueIsNullShouldThrowException() { + void detectAndParseWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse(null)) .withMessageContaining("Value must not be null"); } @Test - public void detectAndParseWhenIso8601ShouldReturnDuration() { + void detectAndParseWhenIso8601ShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); assertThat(DurationStyle.detectAndParse("PT15M")).isEqualTo(Duration.parse("PT15M")); assertThat(DurationStyle.detectAndParse("+PT15M")).isEqualTo(Duration.parse("PT15M")); @@ -50,7 +50,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleNanosShouldReturnDuration() { + void detectAndParseWhenSimpleNanosShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10ns")).isEqualTo(Duration.ofNanos(10)); assertThat(DurationStyle.detectAndParse("10NS")).isEqualTo(Duration.ofNanos(10)); assertThat(DurationStyle.detectAndParse("+10ns")).isEqualTo(Duration.ofNanos(10)); @@ -58,7 +58,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleMicrosShouldReturnDuration() { + void detectAndParseWhenSimpleMicrosShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10us")).isEqualTo(Duration.ofNanos(10000)); assertThat(DurationStyle.detectAndParse("10US")).isEqualTo(Duration.ofNanos(10000)); assertThat(DurationStyle.detectAndParse("+10us")).isEqualTo(Duration.ofNanos(10000)); @@ -66,7 +66,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleMillisShouldReturnDuration() { + void detectAndParseWhenSimpleMillisShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10ms")).isEqualTo(Duration.ofMillis(10)); assertThat(DurationStyle.detectAndParse("10MS")).isEqualTo(Duration.ofMillis(10)); assertThat(DurationStyle.detectAndParse("+10ms")).isEqualTo(Duration.ofMillis(10)); @@ -74,7 +74,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleSecondsShouldReturnDuration() { + void detectAndParseWhenSimpleSecondsShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10s")).isEqualTo(Duration.ofSeconds(10)); assertThat(DurationStyle.detectAndParse("10S")).isEqualTo(Duration.ofSeconds(10)); assertThat(DurationStyle.detectAndParse("+10s")).isEqualTo(Duration.ofSeconds(10)); @@ -82,7 +82,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleMinutesShouldReturnDuration() { + void detectAndParseWhenSimpleMinutesShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10m")).isEqualTo(Duration.ofMinutes(10)); assertThat(DurationStyle.detectAndParse("10M")).isEqualTo(Duration.ofMinutes(10)); assertThat(DurationStyle.detectAndParse("+10m")).isEqualTo(Duration.ofMinutes(10)); @@ -90,7 +90,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleHoursShouldReturnDuration() { + void detectAndParseWhenSimpleHoursShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10h")).isEqualTo(Duration.ofHours(10)); assertThat(DurationStyle.detectAndParse("10H")).isEqualTo(Duration.ofHours(10)); assertThat(DurationStyle.detectAndParse("+10h")).isEqualTo(Duration.ofHours(10)); @@ -98,7 +98,7 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleDaysShouldReturnDuration() { + void detectAndParseWhenSimpleDaysShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10d")).isEqualTo(Duration.ofDays(10)); assertThat(DurationStyle.detectAndParse("10D")).isEqualTo(Duration.ofDays(10)); assertThat(DurationStyle.detectAndParse("+10d")).isEqualTo(Duration.ofDays(10)); @@ -106,27 +106,27 @@ public class DurationStyleTests { } @Test - public void detectAndParseWhenSimpleWithoutSuffixShouldReturnDuration() { + void detectAndParseWhenSimpleWithoutSuffixShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10")).isEqualTo(Duration.ofMillis(10)); assertThat(DurationStyle.detectAndParse("+10")).isEqualTo(Duration.ofMillis(10)); assertThat(DurationStyle.detectAndParse("-10")).isEqualTo(Duration.ofMillis(-10)); } @Test - public void detectAndParseWhenSimpleWithoutSuffixButWithChronoUnitShouldReturnDuration() { + void detectAndParseWhenSimpleWithoutSuffixButWithChronoUnitShouldReturnDuration() { assertThat(DurationStyle.detectAndParse("10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); assertThat(DurationStyle.detectAndParse("+10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); assertThat(DurationStyle.detectAndParse("-10", ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(-10)); } @Test - public void detectAndParseWhenBadFormatShouldThrowException() { + void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse("10foo")) .withMessageContaining("'10foo' is not a valid duration"); } @Test - public void detectWhenSimpleShouldReturnSimple() { + void detectWhenSimpleShouldReturnSimple() { assertThat(DurationStyle.detect("10")).isEqualTo(DurationStyle.SIMPLE); assertThat(DurationStyle.detect("+10")).isEqualTo(DurationStyle.SIMPLE); assertThat(DurationStyle.detect("-10")).isEqualTo(DurationStyle.SIMPLE); @@ -142,7 +142,7 @@ public class DurationStyleTests { } @Test - public void detectWhenIso8601ShouldReturnIso8601() { + void detectWhenIso8601ShouldReturnIso8601() { assertThat(DurationStyle.detect("PT20.345S")).isEqualTo(DurationStyle.ISO8601); assertThat(DurationStyle.detect("PT15M")).isEqualTo(DurationStyle.ISO8601); assertThat(DurationStyle.detect("+PT15M")).isEqualTo(DurationStyle.ISO8601); @@ -154,13 +154,13 @@ public class DurationStyleTests { } @Test - public void detectWhenUnknownShouldThrowException() { + void detectWhenUnknownShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detect("bad")) .withMessageContaining("'bad' is not a valid duration"); } @Test - public void parseIso8601ShouldParse() { + void parseIso8601ShouldParse() { assertThat(DurationStyle.ISO8601.parse("PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); assertThat(DurationStyle.ISO8601.parse("PT15M")).isEqualTo(Duration.parse("PT15M")); assertThat(DurationStyle.ISO8601.parse("+PT15M")).isEqualTo(Duration.parse("PT15M")); @@ -172,7 +172,7 @@ public class DurationStyleTests { } @Test - public void parseIso8601WithUnitShouldIgnoreUnit() { + void parseIso8601WithUnitShouldIgnoreUnit() { assertThat(DurationStyle.ISO8601.parse("PT20.345S", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT20.345S")); assertThat(DurationStyle.ISO8601.parse("PT15M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT15M")); assertThat(DurationStyle.ISO8601.parse("+PT15M", ChronoUnit.SECONDS)).isEqualTo(Duration.parse("PT15M")); @@ -184,54 +184,54 @@ public class DurationStyleTests { } @Test - public void parseIso8601WhenSimpleShouldThrowException() { + void parseIso8601WhenSimpleShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) .withMessageContaining("'10d' is not a valid ISO-8601 duration"); } @Test - public void parseSimpleShouldParse() { + void parseSimpleShouldParse() { assertThat(DurationStyle.SIMPLE.parse("10m")).isEqualTo(Duration.ofMinutes(10)); } @Test - public void parseSimpleWithUnitShouldUseUnitAsFallback() { + void parseSimpleWithUnitShouldUseUnitAsFallback() { assertThat(DurationStyle.SIMPLE.parse("10m", ChronoUnit.SECONDS)).isEqualTo(Duration.ofMinutes(10)); assertThat(DurationStyle.SIMPLE.parse("10", ChronoUnit.MINUTES)).isEqualTo(Duration.ofMinutes(10)); } @Test - public void parseSimpleWhenUnknownUnitShouldThrowException() { + void parseSimpleWhenUnknownUnitShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); } @Test - public void parseSimpleWhenIso8601ShouldThrowException() { + void parseSimpleWhenIso8601ShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) .withMessageContaining("'PT10H' is not a valid simple duration"); } @Test - public void printIso8601ShouldPrint() { + void printIso8601ShouldPrint() { Duration duration = Duration.parse("-PT-6H+3M"); assertThat(DurationStyle.ISO8601.print(duration)).isEqualTo("PT5H57M"); } @Test - public void printIso8601ShouldIgnoreUnit() { + void printIso8601ShouldIgnoreUnit() { Duration duration = Duration.parse("-PT-6H+3M"); assertThat(DurationStyle.ISO8601.print(duration, ChronoUnit.DAYS)).isEqualTo("PT5H57M"); } @Test - public void printSimpleWithoutUnitShouldPrintInMs() { + void printSimpleWithoutUnitShouldPrintInMs() { Duration duration = Duration.ofSeconds(1); assertThat(DurationStyle.SIMPLE.print(duration)).isEqualTo("1000ms"); } @Test - public void printSimpleWithUnitShouldPrintInUnit() { + void printSimpleWithUnitShouldPrintInUnit() { Duration duration = Duration.ofMillis(1000); assertThat(DurationStyle.SIMPLE.print(duration, ChronoUnit.SECONDS)).isEqualTo("1s"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java index 1022e83d68f..fe84a0c5f4e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToNumberConverterTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; @@ -34,38 +32,30 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class DurationToNumberConverterTests { +class DurationToNumberConverterTests { - private final ConversionService conversionService; - - public DurationToNumberConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertWithoutStyleShouldReturnMs() { - Long converted = this.conversionService.convert(Duration.ofSeconds(1), Long.class); + @ConversionServiceTest + void convertWithoutStyleShouldReturnMs(ConversionService conversionService) { + Long converted = conversionService.convert(Duration.ofSeconds(1), Long.class); assertThat(converted).isEqualTo(1000); } - @Test - public void convertWithFormatShouldUseIgnoreFormat() { - Integer converted = (Integer) this.conversionService.convert(Duration.ofSeconds(1), + @ConversionServiceTest + void convertWithFormatShouldUseIgnoreFormat(ConversionService conversionService) { + Integer converted = (Integer) conversionService.convert(Duration.ofSeconds(1), MockDurationTypeDescriptor.get(null, DurationStyle.ISO8601), TypeDescriptor.valueOf(Integer.class)); assertThat(converted).isEqualTo(1000); } - @Test - public void convertWithFormatAndUnitShouldUseFormatAndUnit() { - Byte converted = (Byte) this.conversionService.convert(Duration.ofSeconds(1), + @ConversionServiceTest + void convertWithFormatAndUnitShouldUseFormatAndUnit(ConversionService conversionService) { + Byte converted = (Byte) conversionService.convert(Duration.ofSeconds(1), MockDurationTypeDescriptor.get(ChronoUnit.SECONDS, null), TypeDescriptor.valueOf(Byte.class)); assertThat(converted).isEqualTo((byte) 1); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new DurationToNumberConverter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new DurationToNumberConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java index f3d9f40b740..19dd01effbe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationToStringConverterTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; @@ -34,39 +32,31 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class DurationToStringConverterTests { +class DurationToStringConverterTests { - private final ConversionService conversionService; - - public DurationToStringConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertWithoutStyleShouldReturnIso8601() { - String converted = this.conversionService.convert(Duration.ofSeconds(1), String.class); + @ConversionServiceTest + void convertWithoutStyleShouldReturnIso8601(ConversionService conversionService) { + String converted = conversionService.convert(Duration.ofSeconds(1), String.class); assertThat(converted).isEqualTo("PT1S"); } - @Test - public void convertWithFormatShouldUseFormatAndMs() { - String converted = (String) this.conversionService.convert(Duration.ofSeconds(1), + @ConversionServiceTest + void convertWithFormatShouldUseFormatAndMs(ConversionService conversionService) { + String converted = (String) conversionService.convert(Duration.ofSeconds(1), MockDurationTypeDescriptor.get(null, DurationStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1000ms"); } - @Test - public void convertWithFormatAndUnitShouldUseFormatAndUnit() { - String converted = (String) this.conversionService.convert(Duration.ofSeconds(1), + @ConversionServiceTest + void convertWithFormatAndUnitShouldUseFormatAndUnit(ConversionService conversionService) { + String converted = (String) conversionService.convert(Duration.ofSeconds(1), MockDurationTypeDescriptor.get(ChronoUnit.SECONDS, DurationStyle.SIMPLE), TypeDescriptor.valueOf(String.class)); assertThat(converted).isEqualTo("1s"); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new DurationToStringConverter()); + static Stream conversionServices() throws Exception { + return ConversionServiceArguments.with(new DurationToStringConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java index 0e0a9271d83..33b2820645c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java @@ -18,61 +18,47 @@ package org.springframework.boot.convert; import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.stream.Stream; -import org.junit.AssumptionViolatedException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.jupiter.api.Assumptions.assumingThat; /** * Tests for {@link InetAddressFormatter}. * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class InetAddressFormatterTests { +class InetAddressFormatterTests { - private final ConversionService conversionService; - - public InetAddressFormatterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void convertFromInetAddressToStringShouldConvert(ConversionService conversionService) throws UnknownHostException { + assumingThat(isResolvable("example.com"), () -> { + InetAddress address = InetAddress.getByName("example.com"); + String converted = conversionService.convert(address, String.class); + assertThat(converted).isEqualTo(address.getHostAddress()); + }); } - @Test - public void convertFromInetAddressToStringShouldConvert() throws UnknownHostException { - assumeResolves("example.com", true); - InetAddress address = InetAddress.getByName("example.com"); - String converted = this.conversionService.convert(address, String.class); - assertThat(converted).isEqualTo(address.getHostAddress()); + @ConversionServiceTest + void convertFromStringToInetAddressShouldConvert(ConversionService conversionService) { + assumingThat(isResolvable("example.com"), () -> { + InetAddress converted = conversionService.convert("example.com", InetAddress.class); + assertThat(converted.toString()).startsWith("example.com"); + }); } - @Test - public void convertFromStringToInetAddressShouldConvert() { - assumeResolves("example.com", true); - InetAddress converted = this.conversionService.convert("example.com", InetAddress.class); - assertThat(converted.toString()).startsWith("example.com"); - } - - @Test - public void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException() { + @ConversionServiceTest + void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException(ConversionService conversionService) { String missingDomain = "ireallydontexist.example.com"; - assumeResolves(missingDomain, false); - assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> this.conversionService.convert(missingDomain, InetAddress.class)); - } - - private void assumeResolves(String host, boolean expectedToResolve) { - boolean resolved = isResolvable(host); - if (resolved != expectedToResolve) { - throw new AssumptionViolatedException("Host " + host + " resolved " + resolved); - } + assumingThat(!isResolvable("ireallydontexist.example.com"), + () -> assertThatExceptionOfType(ConversionFailedException.class) + .isThrownBy(() -> conversionService.convert(missingDomain, InetAddress.class))); } private boolean isResolvable(String host) { @@ -85,9 +71,8 @@ public class InetAddressFormatterTests { } } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new InetAddressFormatter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new InetAddressFormatter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java index 9c2b4a2c044..c3048689269 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/IsoOffsetFormatterTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.convert; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; @@ -33,33 +31,25 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class IsoOffsetFormatterTests { +class IsoOffsetFormatterTests { - private final ConversionService conversionService; - - public IsoOffsetFormatterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; - } - - @Test - public void convertShouldConvertStringToIsoDate() { + @ConversionServiceTest + void convertShouldConvertStringToIsoDate(ConversionService conversionService) { OffsetDateTime now = OffsetDateTime.now(); - OffsetDateTime converted = this.conversionService.convert(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now), + OffsetDateTime converted = conversionService.convert(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now), OffsetDateTime.class); assertThat(converted).isEqualTo(now); } - @Test - public void convertShouldConvertIsoDateToString() { + @ConversionServiceTest + void convertShouldConvertIsoDateToString(ConversionService conversionService) { OffsetDateTime now = OffsetDateTime.now(); - String converted = this.conversionService.convert(now, String.class); + String converted = conversionService.convert(now, String.class); assertThat(converted).isNotNull().startsWith(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new IsoOffsetFormatter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new IsoOffsetFormatter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java index b9d4f406b19..15b3296efe8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java @@ -17,10 +17,9 @@ package org.springframework.boot.convert; import java.util.Collections; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.convert.ConversionService; @@ -37,35 +36,28 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -@RunWith(Parameterized.class) -public class NumberToDataSizeConverterTests { +class NumberToDataSizeConverterTests { - private final ConversionService conversionService; - - public NumberToDataSizeConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, 10)).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, +10)).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, -10)).isEqualTo(DataSize.ofBytes(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixShouldReturnDataSize() { - assertThat(convert(10)).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert(+10)).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert(-10)).isEqualTo(DataSize.ofBytes(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, 10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, +10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, -10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDataSize() { - assertThat(convert(10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert(+10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert(-10, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-10)); - } - - private DataSize convert(Integer source) { - return this.conversionService.convert(source, DataSize.class); + private DataSize convert(ConversionService conversionService, Integer source) { + return conversionService.convert(source, DataSize.class); } @SuppressWarnings({ "rawtypes", "unchecked" }) - private DataSize convert(Integer source, DataUnit defaultUnit) { + private DataSize convert(ConversionService conversionService, Integer source, DataUnit defaultUnit) { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DataSizeUnit unitAnnotation = AnnotationUtils @@ -73,12 +65,11 @@ public class NumberToDataSizeConverterTests { given(targetType.getAnnotation(DataSizeUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) DataSize.class); - return (DataSize) this.conversionService.convert(source, TypeDescriptor.forObject(source), targetType); + return (DataSize) conversionService.convert(source, TypeDescriptor.forObject(source), targetType); } - @Parameterized.Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new NumberToDataSizeConverter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new NumberToDataSizeConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java index 0b7c75522a8..d3b638ace83 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java @@ -19,11 +19,9 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Collections; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.convert.ConversionService; @@ -38,35 +36,28 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class NumberToDurationConverterTests { +class NumberToDurationConverterTests { - private final ConversionService conversionService; - - public NumberToDurationConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, 10)).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, +10)).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, -10)).isEqualTo(Duration.ofMillis(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixShouldReturnDuration() { - assertThat(convert(10)).isEqualTo(Duration.ofMillis(10)); - assertThat(convert(+10)).isEqualTo(Duration.ofMillis(10)); - assertThat(convert(-10)).isEqualTo(Duration.ofMillis(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, 10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, +10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, -10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDuration() { - assertThat(convert(10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert(+10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert(-10, ChronoUnit.SECONDS)).isEqualTo(Duration.ofSeconds(-10)); - } - - private Duration convert(Integer source) { - return this.conversionService.convert(source, Duration.class); + private Duration convert(ConversionService conversionService, Integer source) { + return conversionService.convert(source, Duration.class); } @SuppressWarnings({ "rawtypes", "unchecked" }) - private Duration convert(Integer source, ChronoUnit defaultUnit) { + private Duration convert(ConversionService conversionService, Integer source, ChronoUnit defaultUnit) { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DurationUnit unitAnnotation = AnnotationUtils @@ -74,12 +65,11 @@ public class NumberToDurationConverterTests { given(targetType.getAnnotation(DurationUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Duration.class); - return (Duration) this.conversionService.convert(source, TypeDescriptor.forObject(source), targetType); + return (Duration) conversionService.convert(source, TypeDescriptor.forObject(source), targetType); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new NumberToDurationConverter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new NumberToDurationConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java index a350ddadab9..0855db899d1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java @@ -16,10 +16,9 @@ package org.springframework.boot.convert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import java.util.stream.Stream; + +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; @@ -35,87 +34,79 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Stephane Nicoll */ -@RunWith(Parameterized.class) -public class StringToDataSizeConverterTests { +class StringToDataSizeConverterTests { - private final ConversionService conversionService; - - public StringToDataSizeConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void convertWhenSimpleBytesShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10B")).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, "+10B")).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, "-10B")).isEqualTo(DataSize.ofBytes(-10)); } - @Test - public void convertWhenSimpleBytesShouldReturnDataSize() { - assertThat(convert("10B")).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert("+10B")).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert("-10B")).isEqualTo(DataSize.ofBytes(-10)); + @ConversionServiceTest + void convertWhenSimpleKilobytesShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10KB")).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, "+10KB")).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, "-10KB")).isEqualTo(DataSize.ofKilobytes(-10)); } - @Test - public void convertWhenSimpleKilobytesShouldReturnDataSize() { - assertThat(convert("10KB")).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("+10KB")).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("-10KB")).isEqualTo(DataSize.ofKilobytes(-10)); + @ConversionServiceTest + void convertWhenSimpleMegabytesShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10MB")).isEqualTo(DataSize.ofMegabytes(10)); + assertThat(convert(conversionService, "+10MB")).isEqualTo(DataSize.ofMegabytes(10)); + assertThat(convert(conversionService, "-10MB")).isEqualTo(DataSize.ofMegabytes(-10)); } - @Test - public void convertWhenSimpleMegabytesShouldReturnDataSize() { - assertThat(convert("10MB")).isEqualTo(DataSize.ofMegabytes(10)); - assertThat(convert("+10MB")).isEqualTo(DataSize.ofMegabytes(10)); - assertThat(convert("-10MB")).isEqualTo(DataSize.ofMegabytes(-10)); + @ConversionServiceTest + void convertWhenSimpleGigabytesShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10GB")).isEqualTo(DataSize.ofGigabytes(10)); + assertThat(convert(conversionService, "+10GB")).isEqualTo(DataSize.ofGigabytes(10)); + assertThat(convert(conversionService, "-10GB")).isEqualTo(DataSize.ofGigabytes(-10)); } - @Test - public void convertWhenSimpleGigabytesShouldReturnDataSize() { - assertThat(convert("10GB")).isEqualTo(DataSize.ofGigabytes(10)); - assertThat(convert("+10GB")).isEqualTo(DataSize.ofGigabytes(10)); - assertThat(convert("-10GB")).isEqualTo(DataSize.ofGigabytes(-10)); + @ConversionServiceTest + void convertWhenSimpleTerabytesShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10TB")).isEqualTo(DataSize.ofTerabytes(10)); + assertThat(convert(conversionService, "+10TB")).isEqualTo(DataSize.ofTerabytes(10)); + assertThat(convert(conversionService, "-10TB")).isEqualTo(DataSize.ofTerabytes(-10)); } - @Test - public void convertWhenSimpleTerabytesShouldReturnDataSize() { - assertThat(convert("10TB")).isEqualTo(DataSize.ofTerabytes(10)); - assertThat(convert("+10TB")).isEqualTo(DataSize.ofTerabytes(10)); - assertThat(convert("-10TB")).isEqualTo(DataSize.ofTerabytes(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10")).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, "+10")).isEqualTo(DataSize.ofBytes(10)); + assertThat(convert(conversionService, "-10")).isEqualTo(DataSize.ofBytes(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixShouldReturnDataSize() { - assertThat(convert("10")).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert("+10")).isEqualTo(DataSize.ofBytes(10)); - assertThat(convert("-10")).isEqualTo(DataSize.ofBytes(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDataSize(ConversionService conversionService) { + assertThat(convert(conversionService, "10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, "+10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); + assertThat(convert(conversionService, "-10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDataSize() { - assertThat(convert("10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("+10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(10)); - assertThat(convert("-10", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-10)); - } - - @Test - public void convertWhenBadFormatShouldThrowException() { - assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert("10WB")) + @ConversionServiceTest + void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10WB")) .withMessageContaining("'10WB' is not a valid data size"); } - @Test - public void convertWhenEmptyShouldReturnNull() { - assertThat(convert("")).isNull(); + @ConversionServiceTest + void convertWhenEmptyShouldReturnNull(ConversionService conversionService) { + assertThat(convert(conversionService, "")).isNull(); } - private DataSize convert(String source) { - return this.conversionService.convert(source, DataSize.class); + private DataSize convert(ConversionService conversionService, String source) { + return conversionService.convert(source, DataSize.class); } - private DataSize convert(String source, DataUnit unit) { - return (DataSize) this.conversionService.convert(source, TypeDescriptor.forObject(source), + private DataSize convert(ConversionService conversionService, String source, DataUnit unit) { + return (DataSize) conversionService.convert(source, TypeDescriptor.forObject(source), MockDataSizeTypeDescriptor.get(unit)); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new StringToDataSizeConverter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new StringToDataSizeConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index 4dfb9aa6f2b..cc882e05a95 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java @@ -18,11 +18,9 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; @@ -36,126 +34,118 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class StringToDurationConverterTests { +class StringToDurationConverterTests { - private final ConversionService conversionService; - - public StringToDurationConverterTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void convertWhenIso8601ShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); + assertThat(convert(conversionService, "PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(convert(conversionService, "+PT15M")).isEqualTo(Duration.parse("PT15M")); + assertThat(convert(conversionService, "PT10H")).isEqualTo(Duration.parse("PT10H")); + assertThat(convert(conversionService, "P2D")).isEqualTo(Duration.parse("P2D")); + assertThat(convert(conversionService, "P2DT3H4M")).isEqualTo(Duration.parse("P2DT3H4M")); + assertThat(convert(conversionService, "-PT6H3M")).isEqualTo(Duration.parse("-PT6H3M")); + assertThat(convert(conversionService, "-PT-6H+3M")).isEqualTo(Duration.parse("-PT-6H+3M")); } - @Test - public void convertWhenIso8601ShouldReturnDuration() { - assertThat(convert("PT20.345S")).isEqualTo(Duration.parse("PT20.345S")); - assertThat(convert("PT15M")).isEqualTo(Duration.parse("PT15M")); - assertThat(convert("+PT15M")).isEqualTo(Duration.parse("PT15M")); - assertThat(convert("PT10H")).isEqualTo(Duration.parse("PT10H")); - assertThat(convert("P2D")).isEqualTo(Duration.parse("P2D")); - assertThat(convert("P2DT3H4M")).isEqualTo(Duration.parse("P2DT3H4M")); - assertThat(convert("-PT6H3M")).isEqualTo(Duration.parse("-PT6H3M")); - assertThat(convert("-PT-6H+3M")).isEqualTo(Duration.parse("-PT-6H+3M")); + @ConversionServiceTest + void convertWhenSimpleNanosShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10ns")).isEqualTo(Duration.ofNanos(10)); + assertThat(convert(conversionService, "10NS")).isEqualTo(Duration.ofNanos(10)); + assertThat(convert(conversionService, "+10ns")).isEqualTo(Duration.ofNanos(10)); + assertThat(convert(conversionService, "-10ns")).isEqualTo(Duration.ofNanos(-10)); } - @Test - public void convertWhenSimpleNanosShouldReturnDuration() { - assertThat(convert("10ns")).isEqualTo(Duration.ofNanos(10)); - assertThat(convert("10NS")).isEqualTo(Duration.ofNanos(10)); - assertThat(convert("+10ns")).isEqualTo(Duration.ofNanos(10)); - assertThat(convert("-10ns")).isEqualTo(Duration.ofNanos(-10)); + @ConversionServiceTest + void convertWhenSimpleMicrosShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10us")).isEqualTo(Duration.ofNanos(10000)); + assertThat(convert(conversionService, "10US")).isEqualTo(Duration.ofNanos(10000)); + assertThat(convert(conversionService, "+10us")).isEqualTo(Duration.ofNanos(10000)); + assertThat(convert(conversionService, "-10us")).isEqualTo(Duration.ofNanos(-10000)); } - @Test - public void convertWhenSimpleMicrosShouldReturnDuration() { - assertThat(convert("10us")).isEqualTo(Duration.ofNanos(10000)); - assertThat(convert("10US")).isEqualTo(Duration.ofNanos(10000)); - assertThat(convert("+10us")).isEqualTo(Duration.ofNanos(10000)); - assertThat(convert("-10us")).isEqualTo(Duration.ofNanos(-10000)); + @ConversionServiceTest + void convertWhenSimpleMillisShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10ms")).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, "10MS")).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, "+10ms")).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, "-10ms")).isEqualTo(Duration.ofMillis(-10)); } - @Test - public void convertWhenSimpleMillisShouldReturnDuration() { - assertThat(convert("10ms")).isEqualTo(Duration.ofMillis(10)); - assertThat(convert("10MS")).isEqualTo(Duration.ofMillis(10)); - assertThat(convert("+10ms")).isEqualTo(Duration.ofMillis(10)); - assertThat(convert("-10ms")).isEqualTo(Duration.ofMillis(-10)); + @ConversionServiceTest + void convertWhenSimpleSecondsShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10s")).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, "10S")).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, "+10s")).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, "-10s")).isEqualTo(Duration.ofSeconds(-10)); } - @Test - public void convertWhenSimpleSecondsShouldReturnDuration() { - assertThat(convert("10s")).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("10S")).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("+10s")).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("-10s")).isEqualTo(Duration.ofSeconds(-10)); + @ConversionServiceTest + void convertWhenSimpleMinutesShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10m")).isEqualTo(Duration.ofMinutes(10)); + assertThat(convert(conversionService, "10M")).isEqualTo(Duration.ofMinutes(10)); + assertThat(convert(conversionService, "+10m")).isEqualTo(Duration.ofMinutes(10)); + assertThat(convert(conversionService, "-10m")).isEqualTo(Duration.ofMinutes(-10)); } - @Test - public void convertWhenSimpleMinutesShouldReturnDuration() { - assertThat(convert("10m")).isEqualTo(Duration.ofMinutes(10)); - assertThat(convert("10M")).isEqualTo(Duration.ofMinutes(10)); - assertThat(convert("+10m")).isEqualTo(Duration.ofMinutes(10)); - assertThat(convert("-10m")).isEqualTo(Duration.ofMinutes(-10)); + @ConversionServiceTest + void convertWhenSimpleHoursShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10h")).isEqualTo(Duration.ofHours(10)); + assertThat(convert(conversionService, "10H")).isEqualTo(Duration.ofHours(10)); + assertThat(convert(conversionService, "+10h")).isEqualTo(Duration.ofHours(10)); + assertThat(convert(conversionService, "-10h")).isEqualTo(Duration.ofHours(-10)); } - @Test - public void convertWhenSimpleHoursShouldReturnDuration() { - assertThat(convert("10h")).isEqualTo(Duration.ofHours(10)); - assertThat(convert("10H")).isEqualTo(Duration.ofHours(10)); - assertThat(convert("+10h")).isEqualTo(Duration.ofHours(10)); - assertThat(convert("-10h")).isEqualTo(Duration.ofHours(-10)); + @ConversionServiceTest + void convertWhenSimpleDaysShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10d")).isEqualTo(Duration.ofDays(10)); + assertThat(convert(conversionService, "10D")).isEqualTo(Duration.ofDays(10)); + assertThat(convert(conversionService, "+10d")).isEqualTo(Duration.ofDays(10)); + assertThat(convert(conversionService, "-10d")).isEqualTo(Duration.ofDays(-10)); } - @Test - public void convertWhenSimpleDaysShouldReturnDuration() { - assertThat(convert("10d")).isEqualTo(Duration.ofDays(10)); - assertThat(convert("10D")).isEqualTo(Duration.ofDays(10)); - assertThat(convert("+10d")).isEqualTo(Duration.ofDays(10)); - assertThat(convert("-10d")).isEqualTo(Duration.ofDays(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10")).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, "+10")).isEqualTo(Duration.ofMillis(10)); + assertThat(convert(conversionService, "-10")).isEqualTo(Duration.ofMillis(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixShouldReturnDuration() { - assertThat(convert("10")).isEqualTo(Duration.ofMillis(10)); - assertThat(convert("+10")).isEqualTo(Duration.ofMillis(10)); - assertThat(convert("-10")).isEqualTo(Duration.ofMillis(-10)); + @ConversionServiceTest + void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDuration(ConversionService conversionService) { + assertThat(convert(conversionService, "10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, "+10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); + assertThat(convert(conversionService, "-10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(-10)); } - @Test - public void convertWhenSimpleWithoutSuffixButWithAnnotationShouldReturnDuration() { - assertThat(convert("10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("+10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(10)); - assertThat(convert("-10", ChronoUnit.SECONDS, null)).isEqualTo(Duration.ofSeconds(-10)); - } - - @Test - public void convertWhenBadFormatShouldThrowException() { - assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert("10foo")) + @ConversionServiceTest + void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10foo")) .withMessageContaining("'10foo' is not a valid duration"); } - @Test - public void convertWhenStyleMismatchShouldThrowException() { + @ConversionServiceTest + void convertWhenStyleMismatchShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> convert("10s", null, DurationStyle.ISO8601)); + .isThrownBy(() -> convert(conversionService, "10s", null, DurationStyle.ISO8601)); } - @Test - public void convertWhenEmptyShouldReturnNull() { - assertThat(convert("")).isNull(); + @ConversionServiceTest + void convertWhenEmptyShouldReturnNull(ConversionService conversionService) { + assertThat(convert(conversionService, "")).isNull(); } - private Duration convert(String source) { - return this.conversionService.convert(source, Duration.class); + private Duration convert(ConversionService conversionService, String source) { + return conversionService.convert(source, Duration.class); } - private Duration convert(String source, ChronoUnit unit, DurationStyle style) { - return (Duration) this.conversionService.convert(source, TypeDescriptor.forObject(source), + private Duration convert(ConversionService conversionService, String source, ChronoUnit unit, DurationStyle style) { + return (Duration) conversionService.convert(source, TypeDescriptor.forObject(source), MockDurationTypeDescriptor.get(unit, style)); } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new StringToDurationConverter()); + static Stream conversionServices() { + return ConversionServiceArguments.with(new StringToDurationConverter()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java index b194015af72..dbbe120c065 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToEnumIgnoringCaseConverterFactoryTests.java @@ -17,11 +17,9 @@ package org.springframework.boot.convert; import java.util.Locale; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.provider.Arguments; import org.springframework.core.convert.ConversionService; @@ -32,52 +30,43 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -@RunWith(Parameterized.class) -public class StringToEnumIgnoringCaseConverterFactoryTests { +class StringToEnumIgnoringCaseConverterFactoryTests { - private final ConversionService conversionService; - - public StringToEnumIgnoringCaseConverterFactoryTests(String name, ConversionService conversionService) { - this.conversionService = conversionService; + @ConversionServiceTest + void canConvertFromStringToEnumShouldReturnTrue(ConversionService conversionService) { + assertThat(conversionService.canConvert(String.class, TestEnum.class)).isTrue(); } - @Test - public void canConvertFromStringToEnumShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, TestEnum.class)).isTrue(); + @ConversionServiceTest + void canConvertFromStringToEnumSubclassShouldReturnTrue(ConversionService conversionService) { + assertThat(conversionService.canConvert(String.class, TestSubclassEnum.ONE.getClass())).isTrue(); } - @Test - public void canConvertFromStringToEnumSubclassShouldReturnTrue() { - assertThat(this.conversionService.canConvert(String.class, TestSubclassEnum.ONE.getClass())).isTrue(); + @ConversionServiceTest + void convertFromStringToEnumWhenExactMatchShouldConvertValue(ConversionService conversionService) { + assertThat(conversionService.convert("", TestEnum.class)).isNull(); + assertThat(conversionService.convert("ONE", TestEnum.class)).isEqualTo(TestEnum.ONE); + assertThat(conversionService.convert("TWO", TestEnum.class)).isEqualTo(TestEnum.TWO); + assertThat(conversionService.convert("THREE_AND_FOUR", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); } - @Test - public void convertFromStringToEnumWhenExactMatchShouldConvertValue() { - ConversionService service = this.conversionService; - assertThat(service.convert("", TestEnum.class)).isNull(); - assertThat(service.convert("ONE", TestEnum.class)).isEqualTo(TestEnum.ONE); - assertThat(service.convert("TWO", TestEnum.class)).isEqualTo(TestEnum.TWO); - assertThat(service.convert("THREE_AND_FOUR", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + @ConversionServiceTest + void convertFromStringToEnumWhenFuzzyMatchShouldConvertValue(ConversionService conversionService) { + assertThat(conversionService.convert("", TestEnum.class)).isNull(); + assertThat(conversionService.convert("one", TestEnum.class)).isEqualTo(TestEnum.ONE); + assertThat(conversionService.convert("tWo", TestEnum.class)).isEqualTo(TestEnum.TWO); + assertThat(conversionService.convert("three_and_four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(conversionService.convert("threeandfour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(conversionService.convert("three-and-four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); + assertThat(conversionService.convert("threeAndFour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); } - @Test - public void convertFromStringToEnumWhenFuzzyMatchShouldConvertValue() { - ConversionService service = this.conversionService; - assertThat(service.convert("", TestEnum.class)).isNull(); - assertThat(service.convert("one", TestEnum.class)).isEqualTo(TestEnum.ONE); - assertThat(service.convert("tWo", TestEnum.class)).isEqualTo(TestEnum.TWO); - assertThat(service.convert("three_and_four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("threeandfour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("three-and-four", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); - assertThat(service.convert("threeAndFour", TestEnum.class)).isEqualTo(TestEnum.THREE_AND_FOUR); - } - - @Test - public void convertFromStringToEnumWhenUsingNonEnglishLocaleShouldConvertValue() { + @ConversionServiceTest + void convertFromStringToEnumWhenUsingNonEnglishLocaleShouldConvertValue(ConversionService conversionService) { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("tr")); - LocaleSensitiveEnum result = this.conversionService.convert("accept-case-insensitive-properties", + LocaleSensitiveEnum result = conversionService.convert("accept-case-insensitive-properties", LocaleSensitiveEnum.class); assertThat(result).isEqualTo(LocaleSensitiveEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES); } @@ -86,9 +75,9 @@ public class StringToEnumIgnoringCaseConverterFactoryTests { } } - @Parameters(name = "{0}") - public static Iterable conversionServices() { - return new ConversionServiceParameters(new StringToEnumIgnoringCaseConverterFactory()); + static Stream conversionServices() { + return ConversionServiceArguments + .with((service) -> service.addConverterFactory(new StringToEnumIgnoringCaseConverterFactory())); } enum TestEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index fed625bb45d..c12afd932fa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -18,12 +18,13 @@ package org.springframework.boot.diagnostics; import javax.annotation.PostConstruct; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.server.PortInUseException; import org.springframework.context.annotation.Configuration; @@ -35,16 +36,14 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Andy Wilkinson */ -public class FailureAnalyzersIntegrationTests { - - @Rule - public OutputCapture outputCapture = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class FailureAnalyzersIntegrationTests { @Test - public void analysisIsPerformed() { + void analysisIsPerformed(CapturedOutput capturedOutput) { assertThatExceptionOfType(Exception.class).isThrownBy( () -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); - assertThat(this.outputCapture.toString()).contains("APPLICATION FAILED TO START"); + assertThat(capturedOutput).contains("APPLICATION FAILED TO START"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java index 370d15acdaa..42f2983e14a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java @@ -20,8 +20,8 @@ import java.io.IOException; import java.net.URL; import java.util.Enumeration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; @@ -41,45 +41,45 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Stephane Nicoll */ -public class FailureAnalyzersTests { +class FailureAnalyzersTests { private static AwareFailureAnalyzer failureAnalyzer; - @Before + @BeforeEach public void configureMock() { failureAnalyzer = mock(AwareFailureAnalyzer.class); } @Test - public void analyzersAreLoadedAndCalled() { + void analyzersAreLoadedAndCalled() { RuntimeException failure = new RuntimeException(); analyzeAndReport("basic.factories", failure); verify(failureAnalyzer, times(2)).analyze(failure); } @Test - public void beanFactoryIsInjectedIntoBeanFactoryAwareFailureAnalyzers() { + void beanFactoryIsInjectedIntoBeanFactoryAwareFailureAnalyzers() { RuntimeException failure = new RuntimeException(); analyzeAndReport("basic.factories", failure); verify(failureAnalyzer).setBeanFactory(any(BeanFactory.class)); } @Test - public void environmentIsInjectedIntoEnvironmentAwareFailureAnalyzers() { + void environmentIsInjectedIntoEnvironmentAwareFailureAnalyzers() { RuntimeException failure = new RuntimeException(); analyzeAndReport("basic.factories", failure); verify(failureAnalyzer).setEnvironment(any(Environment.class)); } @Test - public void analyzerThatFailsDuringInitializationDoesNotPreventOtherAnalyzersFromBeingCalled() { + void analyzerThatFailsDuringInitializationDoesNotPreventOtherAnalyzersFromBeingCalled() { RuntimeException failure = new RuntimeException(); analyzeAndReport("broken-initialization.factories", failure); verify(failureAnalyzer, times(1)).analyze(failure); } @Test - public void analyzerThatFailsDuringAnalysisDoesNotPreventOtherAnalyzersFromBeingCalled() { + void analyzerThatFailsDuringAnalysisDoesNotPreventOtherAnalyzersFromBeingCalled() { RuntimeException failure = new RuntimeException(); analyzeAndReport("broken-analysis.factories", failure); verify(failureAnalyzer, times(1)).analyze(failure); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index 30c9df85be6..88cb0705466 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -22,7 +22,7 @@ import java.io.StringReader; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.annotation.Autowired; @@ -38,19 +38,19 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link BeanCurrentlyInCreationFailureAnalyzer}. * * @author Andy Wilkinson */ -public class BeanCurrentlyInCreationFailureAnalyzerTests { +class BeanCurrentlyInCreationFailureAnalyzerTests { private final FailureAnalyzer analyzer = new BeanCurrentlyInCreationFailureAnalyzer(); @Test - public void cyclicBeanMethods() throws IOException { + void cyclicBeanMethods() throws IOException { FailureAnalysis analysis = performAnalysis(CyclicBeanMethodsConfiguration.class); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); @@ -67,7 +67,7 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } @Test - public void cycleWithAutowiredFields() throws IOException { + void cycleWithAutowiredFields() throws IOException { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); assertThat(analysis.getDescription()) .startsWith("The dependencies of some of the beans in the application context form a cycle:"); @@ -87,7 +87,7 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } @Test - public void cycleReferencedViaOtherBeans() throws IOException { + void cycleReferencedViaOtherBeans() throws IOException { FailureAnalysis analysis = performAnalysis(CycleReferencedViaOtherBeansConfiguration.class); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(12); @@ -110,7 +110,7 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } @Test - public void cycleWithAnUnknownStartIsNotAnalyzed() { + void cycleWithAnUnknownStartIsNotAnalyzed() { assertThat(this.analyzer.analyze(new BeanCurrentlyInCreationException("test"))).isNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java index c129a6e6394..fc2b5679aef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.BeanDefinitionOverrideException; import org.springframework.boot.diagnostics.FailureAnalysis; @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class BeanDefinitionOverrideFailureAnalyzerTests { +class BeanDefinitionOverrideFailureAnalyzerTests { @Test - public void analyzeBeanDefinitionOverrideException() { + void analyzeBeanDefinitionOverrideException() { FailureAnalysis analysis = performAnalysis(BeanOverrideConfiguration.class); String description = analysis.getDescription(); assertThat(description).contains("The bean 'testBean', defined in " + SecondConfiguration.class.getName() diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index 013a9d44e68..48cd63269a2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.diagnostics.FailureAnalyzer; @@ -29,19 +29,19 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for {@link BeanNotOfRequiredTypeFailureAnalyzer}. * * @author Andy Wilkinson */ -public class BeanNotOfRequiredTypeFailureAnalyzerTests { +class BeanNotOfRequiredTypeFailureAnalyzerTests { private final FailureAnalyzer analyzer = new BeanNotOfRequiredTypeFailureAnalyzer(); @Test - public void jdkProxyCausesInjectionFailure() { + void jdkProxyCausesInjectionFailure() { FailureAnalysis analysis = performAnalysis(JdkProxyConfiguration.class); assertThat(analysis.getDescription()).startsWith("The bean 'asyncBean'"); assertThat(analysis.getDescription()).contains("'" + AsyncBean.class.getName() + "'"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java index b35e1dc80a9..17f7cf92e47 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzerTests.java @@ -23,7 +23,7 @@ import java.util.Set; import javax.validation.constraints.Min; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -42,30 +42,30 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Andy Wilkinson * @author Madhura Bhave */ -public class BindFailureAnalyzerTests { +class BindFailureAnalyzerTests { @Test - public void analysisForUnboundElementsIsNull() { + void analysisForUnboundElementsIsNull() { FailureAnalysis analysis = performAnalysis(UnboundElementsFailureConfiguration.class, "test.foo.listValue[0]=hello", "test.foo.listValue[2]=world"); assertThat(analysis).isNull(); } @Test - public void analysisForValidationExceptionIsNull() { + void analysisForValidationExceptionIsNull() { FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class, "test.foo.value=1"); assertThat(analysis).isNull(); } @Test - public void bindExceptionDueToOtherFailure() { + void bindExceptionDueToOtherFailure() { FailureAnalysis analysis = performAnalysis(GenericFailureConfiguration.class, "test.foo.value=alpha"); assertThat(analysis.getDescription()).contains(failure("test.foo.value", "alpha", "\"test.foo.value\" from property source \"test\"", "failed to convert java.lang.String to int")); } @Test - public void bindExceptionForUnknownValueInEnumListsValidValuesInAction() { + void bindExceptionForUnknownValueInEnumListsValidValuesInAction() { FailureAnalysis analysis = performAnalysis(EnumFailureConfiguration.class, "test.foo.fruit=apple,strawberry"); for (Fruit fruit : Fruit.values()) { assertThat(analysis.getAction()).contains(fruit.name()); @@ -73,7 +73,7 @@ public class BindFailureAnalyzerTests { } @Test - public void bindExceptionWithNestedFailureShouldDisplayNestedMessage() { + void bindExceptionWithNestedFailureShouldDisplayNestedMessage() { FailureAnalysis analysis = performAnalysis(NestedFailureConfiguration.class, "test.foo.value=hello"); assertThat(analysis.getDescription()).contains(failure("test.foo.value", "hello", "\"test.foo.value\" from property source \"test\"", "This is a failure")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java index 8556e0034d2..84ab1b401d7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BindValidationFailureAnalyzerTests.java @@ -24,9 +24,9 @@ import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -49,20 +49,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class BindValidationFailureAnalyzerTests { +class BindValidationFailureAnalyzerTests { - @Before + @BeforeEach public void setup() { LocaleContextHolder.setLocale(Locale.US); } - @After + @AfterEach public void cleanup() { LocaleContextHolder.resetLocaleContext(); } @Test - public void bindExceptionWithFieldErrorsDueToValidationFailure() { + void bindExceptionWithFieldErrorsDueToValidationFailure() { FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class); assertThat(analysis.getDescription()).contains(failure("test.foo.foo", "null", "must not be null")); assertThat(analysis.getDescription()).contains(failure("test.foo.value", "0", "at least five")); @@ -70,19 +70,19 @@ public class BindValidationFailureAnalyzerTests { } @Test - public void bindExceptionWithOriginDueToValidationFailure() { + void bindExceptionWithOriginDueToValidationFailure() { FailureAnalysis analysis = performAnalysis(FieldValidationFailureConfiguration.class, "test.foo.value=4"); assertThat(analysis.getDescription()).contains("Origin: \"test.foo.value\" from property source \"test\""); } @Test - public void bindExceptionWithObjectErrorsDueToValidationFailure() { + void bindExceptionWithObjectErrorsDueToValidationFailure() { FailureAnalysis analysis = performAnalysis(ObjectValidationFailureConfiguration.class); assertThat(analysis.getDescription()).contains("Reason: This object could not be bound."); } @Test - public void otherBindExceptionShouldReturnAnalysis() { + void otherBindExceptionShouldReturnAnalysis() { BindException cause = new BindException(new FieldValidationFailureProperties(), "fieldValidationFailureProperties"); cause.addError(new FieldError("test", "value", "must not be null")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java index 7d132097628..e417045262e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertiesFailureAnalyzerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.InvalidConfigurationPropertiesException; @@ -30,12 +30,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class InvalidConfigurationPropertiesFailureAnalyzerTests { +class InvalidConfigurationPropertiesFailureAnalyzerTests { private final InvalidConfigurationPropertiesFailureAnalyzer analyzer = new InvalidConfigurationPropertiesFailureAnalyzer(); @Test - public void analysisForInvalidConfigurationOfConfigurationProperties() { + void analysisForInvalidConfigurationOfConfigurationProperties() { FailureAnalysis analysis = performAnalysis(); assertThat(analysis.getDescription()).isEqualTo(getDescription()); assertThat(analysis.getAction()).isEqualTo("Remove @Component from " + TestProperties.class.getName() diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java index e2ae6bc1dcf..1a97bac1fa6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -33,12 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class InvalidConfigurationPropertyNameFailureAnalyzerTests { +class InvalidConfigurationPropertyNameFailureAnalyzerTests { private InvalidConfigurationPropertyNameFailureAnalyzer analyzer = new InvalidConfigurationPropertyNameFailureAnalyzer(); @Test - public void analysisWhenRootCauseIsBeanCreationFailureShouldContainBeanName() { + void analysisWhenRootCauseIsBeanCreationFailureShouldContainBeanName() { BeanCreationException failure = createFailure(InvalidPrefixConfiguration.class); FailureAnalysis analysis = this.analyzer.analyze(failure); assertThat(analysis.getDescription()) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java index 96fa3828d0f..29b46485355 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.diagnostics.analyzer; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.source.InvalidConfigurationPropertyValueException; import org.springframework.boot.diagnostics.FailureAnalysis; @@ -35,12 +35,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class InvalidConfigurationPropertyValueFailureAnalyzerTests { +class InvalidConfigurationPropertyValueFailureAnalyzerTests { private final MockEnvironment environment = new MockEnvironment(); @Test - public void analysisWithNullEnvironment() { + void analysisWithNullEnvironment() { InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.property", "invalid", "This is not valid."); FailureAnalysis analysis = new InvalidConfigurationPropertyValueFailureAnalyzer().analyze(failure); @@ -48,7 +48,7 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { } @Test - public void analysisWithKnownProperty() { + void analysisWithKnownProperty() { MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source)); InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( @@ -61,7 +61,7 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { } @Test - public void analysisWithKnownPropertyAndNoReason() { + void analysisWithKnownPropertyAndNoReason() { MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source)); InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( @@ -73,7 +73,7 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { } @Test - public void analysisWithKnownPropertyAndOtherCandidates() { + void analysisWithKnownPropertyAndOtherCandidates() { MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid")); MapPropertySource additional = new MapPropertySource("additional", Collections.singletonMap("test.property", "valid")); @@ -93,7 +93,7 @@ public class InvalidConfigurationPropertyValueFailureAnalyzerTests { } @Test - public void analysisWithUnknownKey() { + void analysisWithUnknownKey() { InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException( "test.key.not.defined", "invalid", "This is not valid."); assertThat(performAnalysis(failure)).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index e44ec705995..aebbab4bbba 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.ObjectProvider; @@ -37,12 +37,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class NoUniqueBeanDefinitionFailureAnalyzerTests { +class NoUniqueBeanDefinitionFailureAnalyzerTests { private final NoUniqueBeanDefinitionFailureAnalyzer analyzer = new NoUniqueBeanDefinitionFailureAnalyzer(); @Test - public void failureAnalysisForFieldConsumer() { + void failureAnalysisForFieldConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(FieldConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith( "Field testBean in " + FieldConsumer.class.getName() + " required a single bean, but 6 were found:"); @@ -50,7 +50,7 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForMethodConsumer() { + void failureAnalysisForMethodConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(MethodConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of method consumer in " + MethodConsumer.class.getName() + " required a single bean, but 6 were found:"); @@ -58,7 +58,7 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForConstructorConsumer() { + void failureAnalysisForConstructorConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ConstructorConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + ConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); @@ -66,7 +66,7 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForObjectProviderMethodConsumer() { + void failureAnalysisForObjectProviderMethodConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderMethodConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith("Method consumer in " + ObjectProviderMethodConsumer.class.getName() + " required a single bean, but 6 were found:"); @@ -74,7 +74,7 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForXmlConsumer() { + void failureAnalysisForXmlConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(XmlConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith("Parameter 0 of constructor in " + TestBeanConsumer.class.getName() + " required a single bean, but 6 were found:"); @@ -82,7 +82,7 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } @Test - public void failureAnalysisForObjectProviderConstructorConsumer() { + void failureAnalysisForObjectProviderConstructorConsumer() { FailureAnalysis failureAnalysis = analyzeFailure(createFailure(ObjectProviderConstructorConsumer.class)); assertThat(failureAnalysis.getDescription()).startsWith("Constructor in " + ObjectProviderConstructorConsumer.class.getName() + " required a single bean, but 6 were found:"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java index 2e4c9a677b7..8eb3a2aaf89 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java @@ -21,9 +21,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -41,20 +41,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class UnboundConfigurationPropertyFailureAnalyzerTests { +class UnboundConfigurationPropertyFailureAnalyzerTests { - @Before + @BeforeEach public void setup() { LocaleContextHolder.setLocale(Locale.US); } - @After + @AfterEach public void cleanup() { LocaleContextHolder.resetLocaleContext(); } @Test - public void bindExceptionDueToUnboundElements() { + void bindExceptionDueToUnboundElements() { FailureAnalysis analysis = performAnalysis(UnboundElementsFailureConfiguration.class, "test.foo.listValue[0]=hello", "test.foo.listValue[2]=world"); assertThat(analysis.getDescription()).contains( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java index c6afbe9c25b..af862453b4c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedMapPropertySourceTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.env; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginTrackedValue; @@ -33,7 +33,7 @@ import static org.mockito.Mockito.mock; * @author Madhura Bhave * @author Phillip Webb */ -public class OriginTrackedMapPropertySourceTests { +class OriginTrackedMapPropertySourceTests { private Map map = new LinkedHashMap<>(); @@ -42,35 +42,35 @@ public class OriginTrackedMapPropertySourceTests { private Origin origin = mock(Origin.class); @Test - public void getPropertyWhenMissingShouldReturnNull() { + void getPropertyWhenMissingShouldReturnNull() { assertThat(this.source.getProperty("test")).isNull(); } @Test - public void getPropertyWhenNonTrackedShouldReturnValue() { + void getPropertyWhenNonTrackedShouldReturnValue() { this.map.put("test", "foo"); assertThat(this.source.getProperty("test")).isEqualTo("foo"); } @Test - public void getPropertyWhenTrackedShouldReturnValue() { + void getPropertyWhenTrackedShouldReturnValue() { this.map.put("test", OriginTrackedValue.of("foo", this.origin)); assertThat(this.source.getProperty("test")).isEqualTo("foo"); } @Test - public void getPropertyOriginWhenMissingShouldReturnNull() { + void getPropertyOriginWhenMissingShouldReturnNull() { assertThat(this.source.getOrigin("test")).isNull(); } @Test - public void getPropertyOriginWhenNonTrackedShouldReturnNull() { + void getPropertyOriginWhenNonTrackedShouldReturnNull() { this.map.put("test", "foo"); assertThat(this.source.getOrigin("test")).isNull(); } @Test - public void getPropertyOriginWhenTrackedShouldReturnOrigin() { + void getPropertyOriginWhenTrackedShouldReturnOrigin() { this.map.put("test", OriginTrackedValue.of("foo", this.origin)); assertThat(this.source.getOrigin("test")).isEqualTo(this.origin); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java index 2256ca25b0b..b93966a1594 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.env; import java.util.Map; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.OriginTrackedValue; import org.springframework.boot.origin.TextResourceOrigin; @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Madhura Bhave * @author Phillip Webb */ -public class OriginTrackedPropertiesLoaderTests { +class OriginTrackedPropertiesLoaderTests { private ClassPathResource resource; private Map properties; - @Before + @BeforeEach public void setUp() throws Exception { String path = "test-properties.properties"; this.resource = new ClassPathResource(path, getClass()); @@ -50,7 +50,7 @@ public class OriginTrackedPropertiesLoaderTests { } @Test - public void compareToJavaProperties() throws Exception { + void compareToJavaProperties() throws Exception { Properties java = PropertiesLoaderUtils.loadProperties(this.resource); Properties ours = new Properties(); new OriginTrackedPropertiesLoader(this.resource).load(false).forEach((k, v) -> ours.put(k, v.getValue())); @@ -58,35 +58,35 @@ public class OriginTrackedPropertiesLoaderTests { } @Test - public void getSimpleProperty() { + void getSimpleProperty() { OriginTrackedValue value = this.properties.get("test"); assertThat(getValue(value)).isEqualTo("properties"); assertThat(getLocation(value)).isEqualTo("11:6"); } @Test - public void getSimplePropertyWithColonSeparator() { + void getSimplePropertyWithColonSeparator() { OriginTrackedValue value = this.properties.get("test-colon-separator"); assertThat(getValue(value)).isEqualTo("my-property"); assertThat(getLocation(value)).isEqualTo("15:23"); } @Test - public void getPropertyWithSeparatorSurroundedBySpaces() { + void getPropertyWithSeparatorSurroundedBySpaces() { OriginTrackedValue value = this.properties.get("blah"); assertThat(getValue(value)).isEqualTo("hello world"); assertThat(getLocation(value)).isEqualTo("2:12"); } @Test - public void getUnicodeProperty() { + void getUnicodeProperty() { OriginTrackedValue value = this.properties.get("test-unicode"); assertThat(getValue(value)).isEqualTo("properties&test"); assertThat(getLocation(value)).isEqualTo("12:14"); } @Test - public void getMalformedUnicodeProperty() throws Exception { + void getMalformedUnicodeProperty() throws Exception { // gh-12716 ClassPathResource resource = new ClassPathResource("test-properties-malformed-unicode.properties", getClass()); assertThatIllegalStateException().isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) @@ -94,70 +94,70 @@ public class OriginTrackedPropertiesLoaderTests { } @Test - public void getEscapedProperty() { + void getEscapedProperty() { OriginTrackedValue value = this.properties.get("test=property"); assertThat(getValue(value)).isEqualTo("helloworld"); assertThat(getLocation(value)).isEqualTo("14:15"); } @Test - public void getPropertyWithTab() { + void getPropertyWithTab() { OriginTrackedValue value = this.properties.get("test-tab-property"); assertThat(getValue(value)).isEqualTo("foo\tbar"); assertThat(getLocation(value)).isEqualTo("16:19"); } @Test - public void getPropertyWithBang() { + void getPropertyWithBang() { OriginTrackedValue value = this.properties.get("test-bang-property"); assertThat(getValue(value)).isEqualTo("foo!"); assertThat(getLocation(value)).isEqualTo("34:20"); } @Test - public void getPropertyWithValueComment() { + void getPropertyWithValueComment() { OriginTrackedValue value = this.properties.get("test-property-value-comment"); assertThat(getValue(value)).isEqualTo("foo !bar #foo"); assertThat(getLocation(value)).isEqualTo("36:29"); } @Test - public void getPropertyWithMultilineImmediateBang() { + void getPropertyWithMultilineImmediateBang() { OriginTrackedValue value = this.properties.get("test-multiline-immediate-bang"); assertThat(getValue(value)).isEqualTo("!foo"); assertThat(getLocation(value)).isEqualTo("39:1"); } @Test - public void getPropertyWithCarriageReturn() { + void getPropertyWithCarriageReturn() { OriginTrackedValue value = this.properties.get("test-return-property"); assertThat(getValue(value)).isEqualTo("foo\rbar"); assertThat(getLocation(value)).isEqualTo("17:22"); } @Test - public void getPropertyWithNewLine() { + void getPropertyWithNewLine() { OriginTrackedValue value = this.properties.get("test-newline-property"); assertThat(getValue(value)).isEqualTo("foo\nbar"); assertThat(getLocation(value)).isEqualTo("18:23"); } @Test - public void getPropertyWithFormFeed() { + void getPropertyWithFormFeed() { OriginTrackedValue value = this.properties.get("test-form-feed-property"); assertThat(getValue(value)).isEqualTo("foo\fbar"); assertThat(getLocation(value)).isEqualTo("19:25"); } @Test - public void getPropertyWithWhiteSpace() { + void getPropertyWithWhiteSpace() { OriginTrackedValue value = this.properties.get("test-whitespace-property"); assertThat(getValue(value)).isEqualTo("foo bar"); assertThat(getLocation(value)).isEqualTo("20:32"); } @Test - public void getCommentedOutPropertyShouldBeNull() { + void getCommentedOutPropertyShouldBeNull() { assertThat(this.properties.get("commented-property")).isNull(); assertThat(this.properties.get("#commented-property")).isNull(); assertThat(this.properties.get("commented-two")).isNull(); @@ -165,63 +165,63 @@ public class OriginTrackedPropertiesLoaderTests { } @Test - public void getMultiline() { + void getMultiline() { OriginTrackedValue value = this.properties.get("test-multiline"); assertThat(getValue(value)).isEqualTo("ab\\c"); assertThat(getLocation(value)).isEqualTo("21:17"); } @Test - public void getImmediateMultiline() { + void getImmediateMultiline() { OriginTrackedValue value = this.properties.get("test-multiline-immediate"); assertThat(getValue(value)).isEqualTo("foo"); assertThat(getLocation(value)).isEqualTo("32:1"); } @Test - public void getPropertyWithWhitespaceAfterKey() { + void getPropertyWithWhitespaceAfterKey() { OriginTrackedValue value = this.properties.get("bar"); assertThat(getValue(value)).isEqualTo("foo=baz"); assertThat(getLocation(value)).isEqualTo("3:7"); } @Test - public void getPropertyWithSpaceSeparator() { + void getPropertyWithSpaceSeparator() { OriginTrackedValue value = this.properties.get("hello"); assertThat(getValue(value)).isEqualTo("world"); assertThat(getLocation(value)).isEqualTo("4:9"); } @Test - public void getPropertyWithBackslashEscaped() { + void getPropertyWithBackslashEscaped() { OriginTrackedValue value = this.properties.get("proper\\ty"); assertThat(getValue(value)).isEqualTo("test"); assertThat(getLocation(value)).isEqualTo("5:11"); } @Test - public void getPropertyWithEmptyValue() { + void getPropertyWithEmptyValue() { OriginTrackedValue value = this.properties.get("foo"); assertThat(getValue(value)).isEqualTo(""); assertThat(getLocation(value)).isEqualTo("7:0"); } @Test - public void getPropertyWithBackslashEscapedInValue() { + void getPropertyWithBackslashEscapedInValue() { OriginTrackedValue value = this.properties.get("bat"); assertThat(getValue(value)).isEqualTo("a\\"); assertThat(getLocation(value)).isEqualTo("7:7"); } @Test - public void getPropertyWithSeparatorInValue() { + void getPropertyWithSeparatorInValue() { OriginTrackedValue value = this.properties.get("bling"); assertThat(getValue(value)).isEqualTo("a=b"); assertThat(getLocation(value)).isEqualTo("8:9"); } @Test - public void getListProperty() { + void getListProperty() { OriginTrackedValue apple = this.properties.get("foods[0]"); assertThat(getValue(apple)).isEqualTo("Apple"); assertThat(getLocation(apple)).isEqualTo("24:9"); @@ -237,13 +237,13 @@ public class OriginTrackedPropertiesLoaderTests { } @Test - public void getPropertyWithISO88591Character() { + void getPropertyWithISO88591Character() { OriginTrackedValue value = this.properties.get("test-iso8859-1-chars"); assertThat(getValue(value)).isEqualTo("æ×ÈÅÞßáñÀÿ"); } @Test - public void getPropertyWithTrailingSpace() { + void getPropertyWithTrailingSpace() { OriginTrackedValue value = this.properties.get("test-with-trailing-space"); assertThat(getValue(value)).isEqualTo("trailing "); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java index ac536c964d7..f392fcbafad 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedYamlLoaderTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.env; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.OriginTrackedValue; import org.springframework.boot.origin.TextResourceOrigin; @@ -35,27 +35,27 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Madhura Bhave * @author Phillip Webb */ -public class OriginTrackedYamlLoaderTests { +class OriginTrackedYamlLoaderTests { private OriginTrackedYamlLoader loader; private List> result; - @Before + @BeforeEach public void setUp() { Resource resource = new ClassPathResource("test-yaml.yml", getClass()); this.loader = new OriginTrackedYamlLoader(resource); } @Test - public void processSimpleKey() { + void processSimpleKey() { OriginTrackedValue value = getValue("name"); assertThat(value.toString()).isEqualTo("Martin D'vloper"); assertThat(getLocation(value)).isEqualTo("3:7"); } @Test - public void processMap() { + void processMap() { OriginTrackedValue perl = getValue("languages.perl"); OriginTrackedValue python = getValue("languages.python"); OriginTrackedValue pascal = getValue("languages.pascal"); @@ -68,7 +68,7 @@ public class OriginTrackedYamlLoaderTests { } @Test - public void processCollection() { + void processCollection() { OriginTrackedValue apple = getValue("foods[0]"); OriginTrackedValue orange = getValue("foods[1]"); OriginTrackedValue strawberry = getValue("foods[2]"); @@ -84,14 +84,14 @@ public class OriginTrackedYamlLoaderTests { } @Test - public void processMultiline() { + void processMultiline() { OriginTrackedValue education = getValue("education"); assertThat(education.toString()).isEqualTo("4 GCSEs\n3 A-Levels\nBSc in the Internet of Things\n"); assertThat(getLocation(education)).isEqualTo("16:12"); } @Test - public void processListOfMaps() { + void processListOfMaps() { OriginTrackedValue name = getValue("example.foo[0].name"); OriginTrackedValue url = getValue("example.foo[0].url"); OriginTrackedValue bar1 = getValue("example.foo[0].bar[0].bar1"); @@ -107,7 +107,7 @@ public class OriginTrackedYamlLoaderTests { } @Test - public void processEmptyAndNullValues() { + void processEmptyAndNullValues() { OriginTrackedValue empty = getValue("empty"); OriginTrackedValue nullValue = getValue("null-value"); assertThat(empty.getValue()).isEqualTo(""); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java index f8b37780a78..0652fef69b3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.env; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.PropertySource; import org.springframework.core.io.ClassPathResource; @@ -31,17 +31,17 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class PropertiesPropertySourceLoaderTests { +class PropertiesPropertySourceLoaderTests { private PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader(); @Test - public void getFileExtensions() { + void getFileExtensions() { assertThat(this.loader.getFileExtensions()).isEqualTo(new String[] { "properties", "xml" }); } @Test - public void loadProperties() throws Exception { + void loadProperties() throws Exception { List> loaded = this.loader.load("test.properties", new ClassPathResource("test-properties.properties", getClass())); PropertySource source = loaded.get(0); @@ -49,7 +49,7 @@ public class PropertiesPropertySourceLoaderTests { } @Test - public void loadXml() throws Exception { + void loadXml() throws Exception { List> loaded = this.loader.load("test.xml", new ClassPathResource("test-xml.xml", getClass())); PropertySource source = loaded.get(0); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java index f5a958774c2..2623b9077b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.boot.env; import java.util.Random; import java.util.UUID; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -31,35 +31,35 @@ import static org.mockito.Mockito.spy; * @author Dave Syer * @author Matt Benson */ -public class RandomValuePropertySourceTests { +class RandomValuePropertySourceTests { private RandomValuePropertySource source = new RandomValuePropertySource(); @Test - public void notRandom() { + void notRandom() { assertThat(this.source.getProperty("foo")).isNull(); } @Test - public void string() { + void string() { assertThat(this.source.getProperty("random.string")).isNotNull(); } @Test - public void intValue() { + void intValue() { Integer value = (Integer) this.source.getProperty("random.int"); assertThat(value).isNotNull(); } @Test - public void uuidValue() { + void uuidValue() { String value = (String) this.source.getProperty("random.uuid"); assertThat(value).isNotNull(); assertThat(UUID.fromString(value)).isNotNull(); } @Test - public void intRange() { + void intRange() { Integer value = (Integer) this.source.getProperty("random.int[4,10]"); assertThat(value).isNotNull(); assertThat(value >= 4).isTrue(); @@ -67,31 +67,31 @@ public class RandomValuePropertySourceTests { } @Test - public void intMax() { + void intMax() { Integer value = (Integer) this.source.getProperty("random.int(10)"); assertThat(value).isNotNull().isLessThan(10); } @Test - public void longValue() { + void longValue() { Long value = (Long) this.source.getProperty("random.long"); assertThat(value).isNotNull(); } @Test - public void longRange() { + void longRange() { Long value = (Long) this.source.getProperty("random.long[4,10]"); assertThat(value).isNotNull().isBetween(4L, 10L); } @Test - public void longMax() { + void longMax() { Long value = (Long) this.source.getProperty("random.long(10)"); assertThat(value).isNotNull().isLessThan(10L); } @Test - public void longOverflow() { + void longOverflow() { RandomValuePropertySource source = spy(this.source); given(source.getSource()).willReturn(new Random() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index 91107ec7f89..791bcb3978c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.env; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.json.JsonParseException; import org.springframework.boot.origin.PropertySourceOrigin; @@ -36,14 +36,14 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Phillip Webb * @author Artsiom Yudovin */ -public class SpringApplicationJsonEnvironmentPostProcessorTests { +class SpringApplicationJsonEnvironmentPostProcessorTests { private SpringApplicationJsonEnvironmentPostProcessor processor = new SpringApplicationJsonEnvironmentPostProcessor(); private ConfigurableEnvironment environment = new StandardEnvironment(); @Test - public void error() { + void error() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); assertThatExceptionOfType(JsonParseException.class) @@ -52,14 +52,14 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void missing() { + void missing() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); this.processor.postProcessEnvironment(this.environment, null); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @Test - public void empty() { + void empty() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={}"); this.processor.postProcessEnvironment(this.environment, null); @@ -67,7 +67,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void periodSeparated() { + void periodSeparated() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}"); @@ -76,7 +76,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void envVar() { + void envVar() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":\"bar\"}"); @@ -85,7 +85,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void nested() { + void nested() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":{\"bar\":\"spam\",\"rab\":\"maps\"}}"); @@ -95,7 +95,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void prefixed() { + void prefixed() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo.bar\":\"spam\"}"); @@ -104,7 +104,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void list() { + void list() { assertThat(this.environment.resolvePlaceholders("${foo[1]:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[\"bar\",\"spam\"]}"); @@ -113,7 +113,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void listOfObject() { + void listOfObject() { assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[{\"bar\":\"spam\"}]}"); @@ -122,7 +122,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { } @Test - public void propertySourceShouldTrackOrigin() { + void propertySourceShouldTrackOrigin() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java index be580546a86..982340fdb7d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.env; import java.util.Collections; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor.OriginAwareSystemEnvironmentPropertySource; import org.springframework.boot.origin.SystemEnvironmentOrigin; @@ -36,17 +35,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { +class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { - private ConfigurableEnvironment environment; - - @Before - public void setUp() { - this.environment = new StandardEnvironment(); - } + private final ConfigurableEnvironment environment = new StandardEnvironment(); @Test - public void postProcessShouldReplaceSystemEnvironmentPropertySource() { + void postProcessShouldReplaceSystemEnvironmentPropertySource() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); postProcessor.postProcessEnvironment(this.environment, null); PropertySource replaced = this.environment.getPropertySources().get("systemEnvironment"); @@ -55,7 +49,7 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { @Test @SuppressWarnings("unchecked") - public void replacedPropertySourceShouldBeOriginAware() { + void replacedPropertySourceShouldBeOriginAware() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); PropertySource original = this.environment.getPropertySources().get("systemEnvironment"); postProcessor.postProcessEnvironment(this.environment, null); @@ -71,7 +65,7 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { } @Test - public void replacedPropertySourceWhenPropertyAbsentShouldReturnNullOrigin() { + void replacedPropertySourceWhenPropertyAbsentShouldReturnNullOrigin() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); postProcessor.postProcessEnvironment(this.environment, null); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment @@ -80,7 +74,7 @@ public class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { } @Test - public void replacedPropertySourceShouldResolveProperty() { + void replacedPropertySourceShouldResolveProperty() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); Map source = Collections.singletonMap("FOO_BAR_BAZ", "hello"); this.environment.getPropertySources().replace("systemEnvironment", diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index bcc5d109cf8..16d10379a49 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.env; import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.PropertySource; @@ -37,12 +37,12 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Andy Wilkinson */ -public class YamlPropertySourceLoaderTests { +class YamlPropertySourceLoaderTests { private YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Test - public void load() throws Exception { + void load() throws Exception { ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); PropertySource source = this.loader.load("resource", resource).get(0); assertThat(source).isNotNull(); @@ -50,7 +50,7 @@ public class YamlPropertySourceLoaderTests { } @Test - public void orderedItems() throws Exception { + void orderedItems() throws Exception { StringBuilder yaml = new StringBuilder(); List expected = new ArrayList<>(); for (char c = 'a'; c <= 'z'; c++) { @@ -65,7 +65,7 @@ public class YamlPropertySourceLoaderTests { } @Test - public void mergeItems() throws Exception { + void mergeItems() throws Exception { StringBuilder yaml = new StringBuilder(); yaml.append("foo:\n bar: spam\n"); yaml.append("---\n"); @@ -78,7 +78,7 @@ public class YamlPropertySourceLoaderTests { } @Test - public void timestampLikeItemsDoNotBecomeDates() throws Exception { + void timestampLikeItemsDoNotBecomeDates() throws Exception { ByteArrayResource resource = new ByteArrayResource("foo: 2015-01-28".getBytes()); PropertySource source = this.loader.load("resource", resource).get(0); assertThat(source).isNotNull(); @@ -86,7 +86,7 @@ public class YamlPropertySourceLoaderTests { } @Test - public void loadOriginAware() throws Exception { + void loadOriginAware() throws Exception { Resource resource = new ClassPathResource("test-yaml.yml", getClass()); List> loaded = this.loader.load("resource", resource); for (PropertySource source : loaded) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java index cb66aaaeaea..809d0e8eba0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java @@ -21,7 +21,7 @@ import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class BuildPropertiesTests { +class BuildPropertiesTests { @Test - public void basicInfo() { + void basicInfo() { Instant instant = Instant.now(); BuildProperties properties = new BuildProperties( createProperties("com.example", "demo", "0.0.1", DateTimeFormatter.ISO_INSTANT.format(instant))); @@ -45,7 +45,7 @@ public class BuildPropertiesTests { } @Test - public void noInfo() { + void noInfo() { BuildProperties properties = new BuildProperties(new Properties()); assertThat(properties.getGroup()).isNull(); assertThat(properties.getArtifact()).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java index da2c0c3db36..b00b8fb2699 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/GitPropertiesTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.info; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class GitPropertiesTests { +class GitPropertiesTests { @Test - public void basicInfo() { + void basicInfo() { GitProperties properties = new GitProperties( createProperties("master", "abcdefghijklmno", "abcdefg", "1457527123")); assertThat(properties.getBranch()).isEqualTo("master"); @@ -39,7 +39,7 @@ public class GitPropertiesTests { } @Test - public void noInfo() { + void noInfo() { GitProperties properties = new GitProperties(new Properties()); assertThat(properties.getBranch()).isNull(); assertThat(properties.getCommitId()).isNull(); @@ -48,7 +48,7 @@ public class GitPropertiesTests { } @Test - public void coerceEpochSecond() { + void coerceEpochSecond() { GitProperties properties = new GitProperties(createProperties("master", "abcdefg", null, "1457527123")); assertThat(properties.getCommitTime()).isNotNull(); assertThat(properties.get("commit.time")).isEqualTo("1457527123000"); @@ -56,7 +56,7 @@ public class GitPropertiesTests { } @Test - public void coerceDateString() { + void coerceDateString() { GitProperties properties = new GitProperties( createProperties("master", "abcdefg", null, "2016-03-04T14:36:33+0100")); assertThat(properties.getCommitTime()).isNotNull(); @@ -65,7 +65,7 @@ public class GitPropertiesTests { } @Test - public void coerceUnsupportedFormat() { + void coerceUnsupportedFormat() { GitProperties properties = new GitProperties( createProperties("master", "abcdefg", null, "2016-03-04 15:22:24")); assertThat(properties.getCommitTime()).isNull(); @@ -73,7 +73,7 @@ public class GitPropertiesTests { } @Test - public void shortCommitUsedIfPresent() { + void shortCommitUsedIfPresent() { GitProperties properties = new GitProperties( createProperties("master", "abcdefghijklmno", "abcdefgh", "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abcdefghijklmno"); @@ -81,14 +81,14 @@ public class GitPropertiesTests { } @Test - public void shortenCommitIdShorterThan7() { + void shortenCommitIdShorterThan7() { GitProperties properties = new GitProperties(createProperties("master", "abc", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abc"); assertThat(properties.getShortCommitId()).isEqualTo("abc"); } @Test - public void shortenCommitIdLongerThan7() { + void shortenCommitIdLongerThan7() { GitProperties properties = new GitProperties(createProperties("master", "abcdefghijklmno", null, "1457527123")); assertThat(properties.getCommitId()).isEqualTo("abcdefghijklmno"); assertThat(properties.getShortCommitId()).isEqualTo("abcdefg"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java index b9eb272c749..82d35115d8e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.info; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.PropertySource; @@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Stephane Nicoll */ -public class InfoPropertiesTests { +class InfoPropertiesTests { @Test - public void inputIsImmutable() { + void inputIsImmutable() { Properties p = new Properties(); p.put("foo", "bar"); InfoProperties infoProperties = new InfoProperties(p); @@ -43,7 +43,7 @@ public class InfoPropertiesTests { } @Test - public void iterator() { + void iterator() { Properties p = new Properties(); p.put("one", "first"); p.put("two", "second"); @@ -56,7 +56,7 @@ public class InfoPropertiesTests { } @Test - public void removeNotSupported() { + void removeNotSupported() { Properties p = new Properties(); p.put("foo", "bar"); InfoProperties infoProperties = new InfoProperties(p); @@ -64,7 +64,7 @@ public class InfoPropertiesTests { } @Test - public void toPropertySources() { + void toPropertySources() { Properties p = new Properties(); p.put("one", "first"); p.put("two", "second"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 635dd81f0b2..f642856e1df 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java @@ -24,8 +24,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -39,11 +39,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Vladimir Tsanev * @author Paul Aly */ -public class JsonComponentModuleTests { +class JsonComponentModuleTests { private AnnotationConfigApplicationContext context; - @After + @AfterEach public void closeContext() { if (this.context != null) { this.context.close(); @@ -51,21 +51,21 @@ public class JsonComponentModuleTests { } @Test - public void moduleShouldRegisterSerializers() throws Exception { + void moduleShouldRegisterSerializers() throws Exception { load(OnlySerializer.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertSerialize(module); } @Test - public void moduleShouldRegisterDeserializers() throws Exception { + void moduleShouldRegisterDeserializers() throws Exception { load(OnlyDeserializer.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertDeserialize(module); } @Test - public void moduleShouldRegisterInnerClasses() throws Exception { + void moduleShouldRegisterInnerClasses() throws Exception { load(NameAndAgeJsonComponent.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertSerialize(module); @@ -73,7 +73,7 @@ public class JsonComponentModuleTests { } @Test - public void moduleShouldAllowInnerAbstractClasses() throws Exception { + void moduleShouldAllowInnerAbstractClasses() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JsonComponentModule.class, ComponentWithInnerAbstractClass.class); JsonComponentModule module = context.getBean(JsonComponentModule.class); @@ -82,21 +82,21 @@ public class JsonComponentModuleTests { } @Test - public void moduleShouldRegisterKeySerializers() throws Exception { + void moduleShouldRegisterKeySerializers() throws Exception { load(OnlyKeySerializer.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertKeySerialize(module); } @Test - public void moduleShouldRegisterKeyDeserializers() throws Exception { + void moduleShouldRegisterKeyDeserializers() throws Exception { load(OnlyKeyDeserializer.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertKeyDeserialize(module); } @Test - public void moduleShouldRegisterInnerClassesForKeyHandlers() throws Exception { + void moduleShouldRegisterInnerClassesForKeyHandlers() throws Exception { load(NameAndAgeJsonKeyComponent.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertKeySerialize(module); @@ -104,7 +104,7 @@ public class JsonComponentModuleTests { } @Test - public void moduleShouldRegisterOnlyForSpecifiedClasses() throws Exception { + void moduleShouldRegisterOnlyForSpecifiedClasses() throws Exception { load(NameAndCareerJsonComponent.class); JsonComponentModule module = this.context.getBean(JsonComponentModule.class); assertSerialize(module, new NameAndCareer("spring", "developer"), "{\"name\":\"spring\"}"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index 3a94fb019f4..ba985064b08 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -27,7 +27,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.NullNode; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.jackson.NameAndAgeJsonComponent.Deserializer; @@ -42,12 +42,12 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class JsonObjectDeserializerTests { +class JsonObjectDeserializerTests { private TestJsonObjectDeserializer testDeserializer = new TestJsonObjectDeserializer<>(); @Test - public void deserializeObjectShouldReadJson() throws Exception { + void deserializeObjectShouldReadJson() throws Exception { Deserializer deserializer = new NameAndAgeJsonComponent.Deserializer(); SimpleModule module = new SimpleModule(); module.addDeserializer(NameAndAge.class, deserializer); @@ -59,20 +59,20 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenValueIsNullShouldReturnNull() { + void nullSafeValueWhenValueIsNullShouldReturnNull() { String value = this.testDeserializer.testNullSafeValue(null, String.class); assertThat(value).isNull(); } @Test - public void nullSafeValueWhenClassIsNullShouldThrowException() { + void nullSafeValueWhenClassIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) .withMessageContaining("Type must not be null"); } @Test - public void nullSafeValueWhenClassIsStringShouldReturnString() { + void nullSafeValueWhenClassIsStringShouldReturnString() { JsonNode node = mock(JsonNode.class); given(node.textValue()).willReturn("abc"); String value = this.testDeserializer.testNullSafeValue(node, String.class); @@ -80,7 +80,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsBooleanShouldReturnBoolean() { + void nullSafeValueWhenClassIsBooleanShouldReturnBoolean() { JsonNode node = mock(JsonNode.class); given(node.booleanValue()).willReturn(true); Boolean value = this.testDeserializer.testNullSafeValue(node, Boolean.class); @@ -88,7 +88,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsLongShouldReturnLong() { + void nullSafeValueWhenClassIsLongShouldReturnLong() { JsonNode node = mock(JsonNode.class); given(node.longValue()).willReturn(10L); Long value = this.testDeserializer.testNullSafeValue(node, Long.class); @@ -96,7 +96,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsIntegerShouldReturnInteger() { + void nullSafeValueWhenClassIsIntegerShouldReturnInteger() { JsonNode node = mock(JsonNode.class); given(node.intValue()).willReturn(10); Integer value = this.testDeserializer.testNullSafeValue(node, Integer.class); @@ -104,7 +104,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsShortShouldReturnShort() { + void nullSafeValueWhenClassIsShortShouldReturnShort() { JsonNode node = mock(JsonNode.class); given(node.shortValue()).willReturn((short) 10); Short value = this.testDeserializer.testNullSafeValue(node, Short.class); @@ -112,7 +112,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsDoubleShouldReturnDouble() { + void nullSafeValueWhenClassIsDoubleShouldReturnDouble() { JsonNode node = mock(JsonNode.class); given(node.doubleValue()).willReturn(1.1D); Double value = this.testDeserializer.testNullSafeValue(node, Double.class); @@ -120,7 +120,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsFloatShouldReturnFloat() { + void nullSafeValueWhenClassIsFloatShouldReturnFloat() { JsonNode node = mock(JsonNode.class); given(node.floatValue()).willReturn(1.1F); Float value = this.testDeserializer.testNullSafeValue(node, Float.class); @@ -128,7 +128,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsBigDecimalShouldReturnBigDecimal() { + void nullSafeValueWhenClassIsBigDecimalShouldReturnBigDecimal() { JsonNode node = mock(JsonNode.class); given(node.decimalValue()).willReturn(BigDecimal.TEN); BigDecimal value = this.testDeserializer.testNullSafeValue(node, BigDecimal.class); @@ -136,7 +136,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsBigIntegerShouldReturnBigInteger() { + void nullSafeValueWhenClassIsBigIntegerShouldReturnBigInteger() { JsonNode node = mock(JsonNode.class); given(node.bigIntegerValue()).willReturn(BigInteger.TEN); BigInteger value = this.testDeserializer.testNullSafeValue(node, BigInteger.class); @@ -144,7 +144,7 @@ public class JsonObjectDeserializerTests { } @Test - public void nullSafeValueWhenClassIsUnknownShouldThrowException() { + void nullSafeValueWhenClassIsUnknownShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) .withMessageContaining("Unsupported value type java.io.InputStream"); @@ -152,13 +152,13 @@ public class JsonObjectDeserializerTests { } @Test - public void getRequiredNodeWhenTreeIsNullShouldThrowException() { + void getRequiredNodeWhenTreeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) .withMessageContaining("Tree must not be null"); } @Test - public void getRequiredNodeWhenNodeIsNullShouldThrowException() { + void getRequiredNodeWhenNodeIsNullShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(null); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) @@ -166,7 +166,7 @@ public class JsonObjectDeserializerTests { } @Test - public void getRequiredNodeWhenNodeIsNullNodeShouldThrowException() { + void getRequiredNodeWhenNodeIsNullNodeShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(NullNode.instance); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) @@ -174,7 +174,7 @@ public class JsonObjectDeserializerTests { } @Test - public void getRequiredNodeWhenNodeIsFoundShouldReturnNode() { + void getRequiredNodeWhenNodeIsFoundShouldReturnNode() { JsonNode node = mock(JsonNode.class); JsonNode tree = node; given(tree.get("test")).willReturn(node); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectSerializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectSerializerTests.java index 49c2dfdd14e..25eb5327da1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectSerializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.jackson; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.jackson.NameAndAgeJsonComponent.Serializer; @@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class JsonObjectSerializerTests { +class JsonObjectSerializerTests { @Test - public void serializeObjectShouldWriteJson() throws Exception { + void serializeObjectShouldWriteJson() throws Exception { Serializer serializer = new NameAndAgeJsonComponent.Serializer(); SimpleModule module = new SimpleModule(); module.addSerializer(NameAndAge.class, serializer); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java index 510c60b9fcc..b125e70d095 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java @@ -26,8 +26,8 @@ import javax.sql.DataSource; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -36,11 +36,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class DataSourceBuilderTests { +class DataSourceBuilderTests { private DataSource dataSource; - @After + @AfterEach public void shutdownDataSource() throws IOException { if (this.dataSource instanceof Closeable) { ((Closeable) this.dataSource).close(); @@ -48,20 +48,20 @@ public class DataSourceBuilderTests { } @Test - public void defaultToHikari() { + void defaultToHikari() { this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").build(); assertThat(this.dataSource).isInstanceOf(HikariDataSource.class); } @Test - public void defaultToTomcatIfHikariIsNotAvailable() { + void defaultToTomcatIfHikariIsNotAvailable() { this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") .build(); assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test - public void defaultToCommonsDbcp2AsLastResort() { + void defaultToCommonsDbcp2AsLastResort() { this.dataSource = DataSourceBuilder .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) .url("jdbc:h2:test").build(); @@ -69,7 +69,7 @@ public class DataSourceBuilderTests { } @Test - public void specificTypeOfDataSource() { + void specificTypeOfDataSource() { HikariDataSource hikariDataSource = DataSourceBuilder.create().type(HikariDataSource.class).build(); assertThat(hikariDataSource).isInstanceOf(HikariDataSource.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java index 737840893a4..75abb0b4f96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java @@ -22,7 +22,7 @@ import javax.sql.DataSource; import com.zaxxer.hikari.HikariDataSource; import org.apache.tomcat.jdbc.pool.DataSourceProxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.jdbc.datasource.DelegatingDataSource; @@ -38,57 +38,57 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * * @author Stephane Nicoll */ -public class DataSourceUnwrapperTests { +class DataSourceUnwrapperTests { @Test - public void unwrapWithTarget() { + void unwrapWithTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapWithWrongTarget() { + void unwrapWithWrongTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, SingleConnectionDataSource.class)).isNull(); } @Test - public void unwrapWithDelegate() { + void unwrapWithDelegate() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInDelegate(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapWithProxy() { + void unwrapWithProxy() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapWithProxyAndDelegate() { + void unwrapWithProxyAndDelegate() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapWithSeveralLevelOfWrapping() { + void unwrapWithSeveralLevelOfWrapping() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(wrapInDelegate(wrapInProxy(wrapInDelegate(dataSource))))); assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapDataSourceProxy() { + void unwrapDataSourceProxy() { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInDelegate(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)).isSameAs(dataSource); } @Test - public void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget() throws SQLException { + void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget() throws SQLException { DataSource dataSource = mock(DataSource.class); DataSource actual = DataSourceUnwrapper.unwrap(dataSource, HikariDataSource.class); assertThat(actual).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java index c6b1afb75e5..e49befd13f1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java @@ -23,13 +23,15 @@ import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; import javax.sql.XADataSource; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.asm.ClassReader; @@ -40,43 +42,17 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class DatabaseDriverClassNameTests { +class DatabaseDriverClassNameTests { private static final Set EXCLUDED_DRIVERS = Collections.unmodifiableSet( EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.ORACLE, DatabaseDriver.DB2, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, DatabaseDriver.HANA, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); - private final String className; - - private final Class requiredType; - - @Parameters(name = "{0} {2}") - public static List parameters() { - DatabaseDriver[] databaseDrivers = DatabaseDriver.values(); - List parameters = new ArrayList<>(); - for (DatabaseDriver databaseDriver : databaseDrivers) { - if (EXCLUDED_DRIVERS.contains(databaseDriver)) { - continue; - } - parameters.add(new Object[] { databaseDriver, databaseDriver.getDriverClassName(), Driver.class }); - if (databaseDriver.getXaDataSourceClassName() != null) { - parameters.add( - new Object[] { databaseDriver, databaseDriver.getXaDataSourceClassName(), XADataSource.class }); - } - } - return parameters; - } - - public DatabaseDriverClassNameTests(DatabaseDriver driver, String className, Class requiredType) { - this.className = className; - this.requiredType = requiredType; - } - - @Test - public void databaseClassIsOfRequiredType() throws Exception { - assertThat(getInterfaceNames(this.className.replace('.', '/'))) - .contains(this.requiredType.getName().replace('.', '/')); + @ParameterizedTest(name = "{0} {2}") + @MethodSource + void databaseClassIsOfRequiredType(DatabaseDriver driver, String className, Class requiredType) + throws Exception { + assertThat(getInterfaceNames(className.replace('.', '/'))).contains(requiredType.getName().replace('.', '/')); } private List getInterfaceNames(String className) throws IOException { @@ -90,4 +66,23 @@ public class DatabaseDriverClassNameTests { return interfaceNames; } + static Stream databaseClassIsOfRequiredType() { + return Stream.concat(argumentsForType(Driver.class, DatabaseDriver::getDriverClassName), + argumentsForType(XADataSource.class, + (databaseDriver) -> databaseDriver.getXaDataSourceClassName() != null, + DatabaseDriver::getXaDataSourceClassName)); + } + + private static Stream argumentsForType(Class clazz, + Function classNameExtractor) { + return argumentsForType(clazz, (databaseDriver) -> true, classNameExtractor); + } + + private static Stream argumentsForType(Class clazz, Predicate predicate, + Function classNameExtractor) { + return Stream.of(DatabaseDriver.values()).filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) + .filter(predicate) + .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), clazz)); + } + } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index 4d14659f49e..ce870dfb013 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.jdbc; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -28,40 +28,40 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Maciej Walkowiak * @author Stephane Nicoll */ -public class DatabaseDriverTests { +class DatabaseDriverTests { @Test - public void classNameForKnownDatabase() { + void classNameForKnownDatabase() { String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isEqualTo("org.postgresql.Driver"); } @Test - public void nullClassNameForUnknownDatabase() { + void nullClassNameForUnknownDatabase() { String driverClassName = DatabaseDriver.fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); assertThat(driverClassName).isNull(); } @Test - public void unknownOnNullJdbcUrl() { + void unknownOnNullJdbcUrl() { DatabaseDriver actual = DatabaseDriver.fromJdbcUrl(null); assertThat(actual).isEqualTo(DatabaseDriver.UNKNOWN); } @Test - public void failureOnMalformedJdbcUrl() { + void failureOnMalformedJdbcUrl() { assertThatIllegalArgumentException().isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) .withMessageContaining("URL must start with"); } @Test - public void unknownOnNullProductName() { + void unknownOnNullProductName() { DatabaseDriver actual = DatabaseDriver.fromProductName(null); assertThat(actual).isEqualTo(DatabaseDriver.UNKNOWN); } @Test - public void databaseProductNameLookups() { + void databaseProductNameLookups() { assertThat(DatabaseDriver.fromProductName("newone")).isEqualTo(DatabaseDriver.UNKNOWN); assertThat(DatabaseDriver.fromProductName("Apache Derby")).isEqualTo(DatabaseDriver.DERBY); assertThat(DatabaseDriver.fromProductName("H2")).isEqualTo(DatabaseDriver.H2); @@ -85,7 +85,7 @@ public class DatabaseDriverTests { } @Test - public void databaseJdbcUrlLookups() { + void databaseJdbcUrlLookups() { assertThat(DatabaseDriver.fromJdbcUrl("jdbc:newone://localhost")).isEqualTo(DatabaseDriver.UNKNOWN); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:derby:sample")).isEqualTo(DatabaseDriver.DERBY); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:h2:~/sample")).isEqualTo(DatabaseDriver.H2); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java index 4ca78d32766..bf7511c549c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.jdbc; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -26,33 +26,33 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Stephane Nicoll */ -public class EmbeddedDatabaseConnectionTests { +class EmbeddedDatabaseConnectionTests { @Test - public void h2CustomDatabaseName() { + void h2CustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb")) .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test - public void derbyCustomDatabaseName() { + void derbyCustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.DERBY.getUrl("myderbydb")) .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); } @Test - public void hsqlCustomDatabaseName() { + void hsqlCustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")).isEqualTo("jdbc:hsqldb:mem:myhsql"); } @Test - public void getUrlWithNullDatabaseName() { + void getUrlWithNullDatabaseName() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(null)) .withMessageContaining("DatabaseName must not be empty"); } @Test - public void getUrlWithEmptyDatabaseName() { + void getUrlWithEmptyDatabaseName() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(" ")) .withMessageContaining("DatabaseName must not be empty"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index f88490ec281..5f43bf056b4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.jdbc.metadata; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.jdbc.core.ConnectionCallback; @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @param the data source pool metadata type * @author Stephane Nicoll */ -public abstract class AbstractDataSourcePoolMetadataTests> { +abstract class AbstractDataSourcePoolMetadataTests> { /** * Return a data source metadata instance with a min size of 0 and max size of 2. @@ -39,17 +39,17 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> null); @@ -58,7 +58,7 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> { assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(1)); @@ -68,7 +68,7 @@ public abstract class AbstractDataSourcePoolMetadataTests) (connection) -> { jdbcTemplate.execute((ConnectionCallback) (connection1) -> { @@ -81,10 +81,10 @@ public abstract class AbstractDataSourcePoolMetadataTests initializeBuilder() { return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java index 7f47549a7f3..5f4c911d1ff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java @@ -17,8 +17,7 @@ package org.springframework.boot.jdbc.metadata; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,15 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class CommonsDbcp2DataSourcePoolMetadataTests +class CommonsDbcp2DataSourcePoolMetadataTests extends AbstractDataSourcePoolMetadataTests { - private CommonsDbcp2DataSourcePoolMetadata dataSourceMetadata; - - @Before - public void setup() { - this.dataSourceMetadata = createDataSourceMetadata(0, 2); - } + private final CommonsDbcp2DataSourcePoolMetadata dataSourceMetadata = createDataSourceMetadata(0, 2); @Override protected CommonsDbcp2DataSourcePoolMetadata getDataSourceMetadata() { @@ -43,7 +37,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests } @Test - public void getPoolUsageWithNoCurrent() { + void getPoolUsageWithNoCurrent() { CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata(createDataSource()) { @Override public Integer getActive() { @@ -54,7 +48,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests } @Test - public void getPoolUsageWithNoMax() { + void getPoolUsageWithNoMax() { CommonsDbcp2DataSourcePoolMetadata dsm = new CommonsDbcp2DataSourcePoolMetadata(createDataSource()) { @Override public Integer getMax() { @@ -65,7 +59,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests } @Test - public void getPoolUsageWithUnlimitedPool() { + void getPoolUsageWithUnlimitedPool() { DataSourcePoolMetadata unlimitedDataSource = createDataSourceMetadata(0, -1); assertThat(unlimitedDataSource.getUsage()).isEqualTo(Float.valueOf(-1F)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java index 7762f6314e5..984ba43e00e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CompositeDataSourcePoolMetadataProviderTests.java @@ -20,8 +20,8 @@ import java.util.Arrays; import javax.sql.DataSource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -33,7 +33,7 @@ import static org.mockito.BDDMockito.given; * * @author Stephane Nicoll */ -public class CompositeDataSourcePoolMetadataProviderTests { +class CompositeDataSourcePoolMetadataProviderTests { @Mock private DataSourcePoolMetadataProvider firstProvider; @@ -56,7 +56,7 @@ public class CompositeDataSourcePoolMetadataProviderTests { @Mock private DataSource unknownDataSource; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); given(this.firstProvider.getDataSourcePoolMetadata(this.firstDataSource)).willReturn(this.first); @@ -64,7 +64,7 @@ public class CompositeDataSourcePoolMetadataProviderTests { } @Test - public void createWithProviders() { + void createWithProviders() { CompositeDataSourcePoolMetadataProvider provider = new CompositeDataSourcePoolMetadataProvider( Arrays.asList(this.firstProvider, this.secondProvider)); assertThat(provider.getDataSourcePoolMetadata(this.firstDataSource)).isSameAs(this.first); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java index e7ced968322..70d91b248d4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/HikariDataSourcePoolMetadataTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.jdbc.metadata; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Before; import static org.assertj.core.api.Assertions.assertThat; @@ -29,12 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat; public class HikariDataSourcePoolMetadataTests extends AbstractDataSourcePoolMetadataTests { - private HikariDataSourcePoolMetadata dataSourceMetadata; - - @Before - public void setup() { - this.dataSourceMetadata = new HikariDataSourcePoolMetadata(createDataSource(0, 2)); - } + private final HikariDataSourcePoolMetadata dataSourceMetadata = new HikariDataSourcePoolMetadata( + createDataSource(0, 2)); @Override protected HikariDataSourcePoolMetadata getDataSourceMetadata() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java index 91c5fcf57dc..ca642b639fa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.jdbc.metadata; import org.apache.tomcat.jdbc.pool.DataSource; -import org.junit.Before; import static org.assertj.core.api.Assertions.assertThat; @@ -29,12 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat; public class TomcatDataSourcePoolMetadataTests extends AbstractDataSourcePoolMetadataTests { - private TomcatDataSourcePoolMetadata dataSourceMetadata; - - @Before - public void setup() { - this.dataSourceMetadata = new TomcatDataSourcePoolMetadata(createDataSource(0, 2)); - } + private final TomcatDataSourcePoolMetadata dataSourceMetadata = new TomcatDataSourcePoolMetadata( + createDataSource(0, 2)); @Override protected TomcatDataSourcePoolMetadata getDataSourceMetadata() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index fa6d9d0d47d..a5822a35202 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.json; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -31,14 +31,14 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Jean de Klerk * @author Stephane Nicoll */ -public abstract class AbstractJsonParserTests { +abstract class AbstractJsonParserTests { private final JsonParser parser = getParser(); protected abstract JsonParser getParser(); @Test - public void simpleMap() { + void simpleMap() { Map map = this.parser.parseMap("{\"foo\":\"bar\",\"spam\":1}"); assertThat(map).hasSize(2); assertThat(map.get("foo")).isEqualTo("bar"); @@ -46,7 +46,7 @@ public abstract class AbstractJsonParserTests { } @Test - public void doubleValue() { + void doubleValue() { Map map = this.parser.parseMap("{\"foo\":\"bar\",\"spam\":1.23}"); assertThat(map).hasSize(2); assertThat(map.get("foo")).isEqualTo("bar"); @@ -54,41 +54,41 @@ public abstract class AbstractJsonParserTests { } @Test - public void stringContainingNumber() { + void stringContainingNumber() { Map map = this.parser.parseMap("{\"foo\":\"123\"}"); assertThat(map).hasSize(1); assertThat(map.get("foo")).isEqualTo("123"); } @Test - public void stringContainingComma() { + void stringContainingComma() { Map map = this.parser.parseMap("{\"foo\":\"bar1,bar2\"}"); assertThat(map).hasSize(1); assertThat(map.get("foo")).isEqualTo("bar1,bar2"); } @Test - public void emptyMap() { + void emptyMap() { Map map = this.parser.parseMap("{}"); assertThat(map).isEmpty(); } @Test - public void simpleList() { + void simpleList() { List list = this.parser.parseList("[\"foo\",\"bar\",1]"); assertThat(list).hasSize(3); assertThat(list.get(1)).isEqualTo("bar"); } @Test - public void emptyList() { + void emptyList() { List list = this.parser.parseList("[]"); assertThat(list).isEmpty(); } @SuppressWarnings("unchecked") @Test - public void listOfMaps() { + void listOfMaps() { List list = this.parser.parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); assertThat(list).hasSize(2); assertThat(((Map) list.get(1))).hasSize(2); @@ -96,7 +96,7 @@ public abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test - public void mapOfLists() { + void mapOfLists() { Map map = this.parser .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); assertThat(map).hasSize(1); @@ -104,61 +104,61 @@ public abstract class AbstractJsonParserTests { } @Test - public void mapWithNullThrowsARuntimeException() { + void mapWithNullThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap(null)); } @Test - public void listWithNullThrowsARuntimeException() { + void listWithNullThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList(null)); } @Test - public void mapWithEmptyStringThrowsARuntimeException() { + void mapWithEmptyStringThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("")); } @Test - public void listWithEmptyStringThrowsARuntimeException() { + void listWithEmptyStringThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("")); } @Test - public void mapWithListThrowsARuntimeException() { + void mapWithListThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("[]")); } @Test - public void listWithMapThrowsARuntimeException() { + void listWithMapThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("{}")); } @Test - public void listWithLeadingWhitespace() { + void listWithLeadingWhitespace() { List list = this.parser.parseList("\n\t[\"foo\"]"); assertThat(list).hasSize(1); assertThat(list.get(0)).isEqualTo("foo"); } @Test - public void mapWithLeadingWhitespace() { + void mapWithLeadingWhitespace() { Map map = this.parser.parseMap("\n\t{\"foo\":\"bar\"}"); assertThat(map).hasSize(1); assertThat(map.get("foo")).isEqualTo("bar"); } @Test - public void mapWithLeadingWhitespaceListThrowsARuntimeException() { + void mapWithLeadingWhitespaceListThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseMap("\n\t[]")); } @Test - public void listWithLeadingWhitespaceMapThrowsARuntimeException() { + void listWithLeadingWhitespaceMapThrowsARuntimeException() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.parser.parseList("\n\t{}")); } @Test - public void escapeDoubleQuote() { + void escapeDoubleQuote() { String input = "{\"foo\": \"\\\"bar\\\"\"}"; Map map = this.parser.parseMap(input); assertThat(map.get("foo")).isEqualTo("\"bar\""); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonJsonParserTests.java index 60dfa8cc28b..ebc21fb1df8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonJsonParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import java.io.IOException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -33,7 +33,7 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Stephane Nicoll */ -public class JacksonJsonParserTests extends AbstractJsonParserTests { +class JacksonJsonParserTests extends AbstractJsonParserTests { @Override protected JsonParser getParser() { @@ -41,7 +41,7 @@ public class JacksonJsonParserTests extends AbstractJsonParserTests { } @Test - public void instanceWithSpecificObjectMapper() throws IOException { + void instanceWithSpecificObjectMapper() throws IOException { ObjectMapper objectMapper = spy(new ObjectMapper()); new JacksonJsonParser(objectMapper).parseMap("{}"); verify(objectMapper).readValue(eq("{}"), any(TypeReference.class)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java index 2ddaf56f1c9..4b0190839aa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.jta.atomikos; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; @@ -28,10 +28,10 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class AtomikosConnectionFactoryBeanTests { +class AtomikosConnectionFactoryBeanTests { @Test - public void beanMethods() throws Exception { + void beanMethods() throws Exception { MockAtomikosConnectionFactoryBean bean = spy(new MockAtomikosConnectionFactoryBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java index 0888f11619f..ec8d9e4ac6e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.jta.atomikos; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; @@ -28,10 +28,10 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class AtomikosDataSourceBeanTests { +class AtomikosDataSourceBeanTests { @Test - public void beanMethods() throws Exception { + void beanMethods() throws Exception { MockAtomikosDataSourceBean bean = spy(new MockAtomikosDataSourceBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java index 68b735f6513..f37ec497ea1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java @@ -24,7 +24,7 @@ import javax.sql.DataSource; import com.atomikos.icatch.jta.UserTransactionManager; import com.atomikos.jms.extra.MessageDrivenContainer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -39,12 +39,12 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class AtomikosDependsOnBeanFactoryPostProcessorTests { +class AtomikosDependsOnBeanFactoryPostProcessorTests { private AnnotationConfigApplicationContext context; @Test - public void setsDependsOn() { + void setsDependsOn() { this.context = new AnnotationConfigApplicationContext(Config.class); assertDependsOn("dataSource"); assertDependsOn("connectionFactory"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java index 2e29fe17c75..18af4715856 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java @@ -20,7 +20,7 @@ import java.time.Duration; import java.util.Properties; import org.assertj.core.data.MapEntry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; @@ -34,12 +34,12 @@ import static org.assertj.core.api.Assertions.entry; * @author Phillip Webb * @author Stephane Nicoll */ -public class AtomikosPropertiesTests { +class AtomikosPropertiesTests { private AtomikosProperties properties = new AtomikosProperties(); @Test - public void testProperties() { + void testProperties() { this.properties.setService("service"); this.properties.setMaxTimeout(Duration.ofMillis(1)); this.properties.setDefaultJtaTimeout(Duration.ofMillis(2)); @@ -80,7 +80,7 @@ public class AtomikosPropertiesTests { } @Test - public void testDefaultProperties() { + void testDefaultProperties() { Properties defaultSettings = loadDefaultSettings(); Properties properties = this.properties.asProperties(); assertThat(properties).contains(defaultOf(defaultSettings, "com.atomikos.icatch.max_timeout", diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java index db9f2b50228..5cdd58b9cdb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.jta.atomikos; import javax.jms.ConnectionFactory; import javax.jms.XAConnectionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class AtomikosXAConnectionFactoryWrapperTests { +class AtomikosXAConnectionFactoryWrapperTests { @Test - public void wrap() { + void wrap() { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); AtomikosXAConnectionFactoryWrapper wrapper = new AtomikosXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java index e1373022d7e..6355c73c00a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.jta.atomikos; import javax.sql.DataSource; import javax.sql.XADataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class AtomikosXADataSourceWrapperTests { +class AtomikosXADataSourceWrapperTests { @Test - public void wrap() throws Exception { + void wrap() throws Exception { XADataSource dataSource = mock(XADataSource.class); AtomikosXADataSourceWrapper wrapper = new AtomikosXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessorTests.java index be4fbb5488b..faf92525c78 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessorTests.java @@ -20,7 +20,7 @@ import javax.jms.ConnectionFactory; import javax.sql.DataSource; import bitronix.tm.BitronixTransactionManager; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -36,12 +36,12 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class BitronixDependentBeanFactoryPostProcessorTests { +class BitronixDependentBeanFactoryPostProcessorTests { private AnnotationConfigApplicationContext context; @Test - public void setsDependsOn() { + void setsDependsOn() { DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory()); this.context = new AnnotationConfigApplicationContext(beanFactory); this.context.register(Config.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java index 11a3de361b2..21da1d52670 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.jta.bitronix; import javax.jms.ConnectionFactory; import javax.jms.XAConnectionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class BitronixXAConnectionFactoryWrapperTests { +class BitronixXAConnectionFactoryWrapperTests { @Test - public void wrap() { + void wrap() { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); BitronixXAConnectionFactoryWrapper wrapper = new BitronixXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java index c0866b5e94d..b7eb2e60111 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.jta.bitronix; import javax.sql.DataSource; import javax.sql.XADataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -29,10 +29,10 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class BitronixXADataSourceWrapperTests { +class BitronixXADataSourceWrapperTests { @Test - public void wrap() throws Exception { + void wrap() throws Exception { XADataSource dataSource = mock(XADataSource.class); BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java index 3705af8b067..cd3a9f19117 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.jta.bitronix; import javax.jms.XAConnectionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -29,7 +29,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class PoolingConnectionFactoryBeanTests { +class PoolingConnectionFactoryBeanTests { @SuppressWarnings("serial") private PoolingConnectionFactoryBean bean = new PoolingConnectionFactoryBean() { @@ -40,7 +40,7 @@ public class PoolingConnectionFactoryBeanTests { }; @Test - public void sensibleDefaults() { + void sensibleDefaults() { assertThat(this.bean.getMaxPoolSize()).isEqualTo(10); assertThat(this.bean.getTestConnections()).isTrue(); assertThat(this.bean.getAutomaticEnlistingEnabled()).isTrue(); @@ -48,14 +48,14 @@ public class PoolingConnectionFactoryBeanTests { } @Test - public void setsUniqueNameIfNull() throws Exception { + void setsUniqueNameIfNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.afterPropertiesSet(); assertThat(this.bean.getUniqueName()).isEqualTo("beanName"); } @Test - public void doesNotSetUniqueNameIfNotNull() throws Exception { + void doesNotSetUniqueNameIfNotNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.setUniqueName("un"); this.bean.afterPropertiesSet(); @@ -63,7 +63,7 @@ public class PoolingConnectionFactoryBeanTests { } @Test - public void setConnectionFactory() throws Exception { + void setConnectionFactory() throws Exception { XAConnectionFactory factory = mock(XAConnectionFactory.class); this.bean.setConnectionFactory(factory); this.bean.setBeanName("beanName"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java index 750bc52cf5c..f2d671c5e73 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import javax.sql.XAConnection; import javax.sql.XADataSource; import bitronix.tm.TransactionManagerServices; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -34,26 +34,26 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class PoolingDataSourceBeanTests { +class PoolingDataSourceBeanTests { private PoolingDataSourceBean bean = new PoolingDataSourceBean(); @Test - public void sensibleDefaults() { + void sensibleDefaults() { assertThat(this.bean.getMaxPoolSize()).isEqualTo(10); assertThat(this.bean.getAutomaticEnlistingEnabled()).isTrue(); assertThat(this.bean.isEnableJdbc4ConnectionTest()).isTrue(); } @Test - public void setsUniqueNameIfNull() throws Exception { + void setsUniqueNameIfNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.afterPropertiesSet(); assertThat(this.bean.getUniqueName()).isEqualTo("beanName"); } @Test - public void doesNotSetUniqueNameIfNotNull() throws Exception { + void doesNotSetUniqueNameIfNotNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.setUniqueName("un"); this.bean.afterPropertiesSet(); @@ -61,7 +61,7 @@ public class PoolingDataSourceBeanTests { } @Test - public void setDataSource() throws Exception { + void setDataSource() throws Exception { XADataSource dataSource = mock(XADataSource.class); XAConnection xaConnection = mock(XAConnection.class); Connection connection = mock(Connection.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java index 021097b9fb6..6f862fa15d0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java @@ -25,8 +25,8 @@ import java.util.List; import liquibase.servicelocator.CustomResolverServiceLocator; import liquibase.servicelocator.DefaultPackageScanClassResolver; import liquibase.servicelocator.ServiceLocator; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -43,11 +43,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class LiquibaseServiceLocatorApplicationListenerTests { +class LiquibaseServiceLocatorApplicationListenerTests { private ConfigurableApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -55,7 +55,7 @@ public class LiquibaseServiceLocatorApplicationListenerTests { } @Test - public void replacesServiceLocator() throws IllegalAccessException { + void replacesServiceLocator() throws IllegalAccessException { SpringApplication application = new SpringApplication(Conf.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); @@ -64,7 +64,7 @@ public class LiquibaseServiceLocatorApplicationListenerTests { } @Test - public void replaceServiceLocatorBacksOffIfNotPresent() throws IllegalAccessException { + void replaceServiceLocatorBacksOffIfNotPresent() throws IllegalAccessException { SpringApplication application = new SpringApplication(Conf.class); application.setWebApplicationType(WebApplicationType.NONE); DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java index 7166b6f88e9..79efeababdc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java @@ -20,7 +20,7 @@ import java.util.Set; import liquibase.logging.Logger; import org.apache.commons.logging.LogFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class SpringPackageScanClassResolverTests { +class SpringPackageScanClassResolverTests { @Test - public void testScan() { + void testScan() { SpringPackageScanClassResolver resolver = new SpringPackageScanClassResolver(LogFactory.getLog(getClass())); resolver.addClassLoader(getClass().getClassLoader()); Set> implementations = resolver.findImplementations(Logger.class, "liquibase.logging.core"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java index c895807cffb..079617ab78f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.logging; import java.util.List; import org.apache.commons.logging.Log; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; @@ -34,7 +34,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class DeferredLogTests { +class DeferredLogTests { private DeferredLog deferredLog = new DeferredLog(); @@ -45,121 +45,121 @@ public class DeferredLogTests { private Log log = mock(Log.class); @Test - public void isTraceEnabled() { + void isTraceEnabled() { assertThat(this.deferredLog.isTraceEnabled()).isTrue(); } @Test - public void isDebugEnabled() { + void isDebugEnabled() { assertThat(this.deferredLog.isDebugEnabled()).isTrue(); } @Test - public void isInfoEnabled() { + void isInfoEnabled() { assertThat(this.deferredLog.isInfoEnabled()).isTrue(); } @Test - public void isWarnEnabled() { + void isWarnEnabled() { assertThat(this.deferredLog.isWarnEnabled()).isTrue(); } @Test - public void isErrorEnabled() { + void isErrorEnabled() { assertThat(this.deferredLog.isErrorEnabled()).isTrue(); } @Test - public void isFatalEnabled() { + void isFatalEnabled() { assertThat(this.deferredLog.isFatalEnabled()).isTrue(); } @Test - public void trace() { + void trace() { this.deferredLog.trace(this.message); this.deferredLog.replayTo(this.log); verify(this.log).trace(this.message, null); } @Test - public void traceWithThrowable() { + void traceWithThrowable() { this.deferredLog.trace(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).trace(this.message, this.throwable); } @Test - public void debug() { + void debug() { this.deferredLog.debug(this.message); this.deferredLog.replayTo(this.log); verify(this.log).debug(this.message, null); } @Test - public void debugWithThrowable() { + void debugWithThrowable() { this.deferredLog.debug(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).debug(this.message, this.throwable); } @Test - public void info() { + void info() { this.deferredLog.info(this.message); this.deferredLog.replayTo(this.log); verify(this.log).info(this.message, null); } @Test - public void infoWithThrowable() { + void infoWithThrowable() { this.deferredLog.info(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).info(this.message, this.throwable); } @Test - public void warn() { + void warn() { this.deferredLog.warn(this.message); this.deferredLog.replayTo(this.log); verify(this.log).warn(this.message, null); } @Test - public void warnWithThrowable() { + void warnWithThrowable() { this.deferredLog.warn(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).warn(this.message, this.throwable); } @Test - public void error() { + void error() { this.deferredLog.error(this.message); this.deferredLog.replayTo(this.log); verify(this.log).error(this.message, null); } @Test - public void errorWithThrowable() { + void errorWithThrowable() { this.deferredLog.error(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).error(this.message, this.throwable); } @Test - public void fatal() { + void fatal() { this.deferredLog.fatal(this.message); this.deferredLog.replayTo(this.log); verify(this.log).fatal(this.message, null); } @Test - public void fatalWithThrowable() { + void fatalWithThrowable() { this.deferredLog.fatal(this.message, this.throwable); this.deferredLog.replayTo(this.log); verify(this.log).fatal(this.message, this.throwable); } @Test - public void clearsOnReplayTo() { + void clearsOnReplayTo() { this.deferredLog.info("1"); this.deferredLog.fatal("2"); Log log2 = mock(Log.class); @@ -173,7 +173,7 @@ public class DeferredLogTests { @SuppressWarnings("unchecked") @Test - public void switchTo() { + void switchTo() { List lines = (List) ReflectionTestUtils.getField(this.deferredLog, "lines"); assertThat(lines).isEmpty(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index 4fa12bdce5a..0ec5b5d4fc5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -22,7 +22,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; @@ -37,24 +37,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class LogFileTests { +class LogFileTests { @Test - public void noProperties() { + void noProperties() { PropertyResolver resolver = getPropertyResolver(Collections.emptyMap()); LogFile logFile = LogFile.get(resolver); assertThat(logFile).isNull(); } @Test - public void loggingFile() { + void loggingFile() { PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file.name", "log.file")); testLoggingFile(resolver); } @Test @Deprecated - public void loggingFileWithDeprecatedProperties() { + void loggingFileWithDeprecatedProperties() { PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file", "log.file")); testLoggingFile(resolver); } @@ -69,14 +69,14 @@ public class LogFileTests { } @Test - public void loggingPath() { + void loggingPath() { PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.file.path", "logpath")); testLoggingPath(resolver); } @Test @Deprecated - public void loggingPathWithDeprecatedProperties() { + void loggingPathWithDeprecatedProperties() { PropertyResolver resolver = getPropertyResolver(Collections.singletonMap("logging.path", "logpath")); testLoggingPath(resolver); } @@ -92,7 +92,7 @@ public class LogFileTests { } @Test - public void loggingFileAndPath() { + void loggingFileAndPath() { Map properties = new LinkedHashMap<>(); properties.put("logging.file.name", "log.file"); properties.put("logging.file.path", "logpath"); @@ -102,7 +102,7 @@ public class LogFileTests { @Test @Deprecated - public void loggingFileAndPathWithDeprecatedProperties() { + void loggingFileAndPathWithDeprecatedProperties() { Map properties = new LinkedHashMap<>(); properties.put("logging.file", "log.file"); properties.put("logging.path", "logpath"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java index af2b09cb2c1..2e8ae57b3ca 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggerConfigurationComparatorTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.logging; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,54 +25,54 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Ben Hale */ -public class LoggerConfigurationComparatorTests { +class LoggerConfigurationComparatorTests { private final LoggerConfigurationComparator comparator = new LoggerConfigurationComparator("ROOT"); @Test - public void rootLoggerFirst() { + void rootLoggerFirst() { LoggerConfiguration first = new LoggerConfiguration("ROOT", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("alpha", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isLessThan(0); } @Test - public void rootLoggerSecond() { + void rootLoggerSecond() { LoggerConfiguration first = new LoggerConfiguration("alpha", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("ROOT", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isGreaterThan(0); } @Test - public void rootLoggerFirstEmpty() { + void rootLoggerFirstEmpty() { LoggerConfiguration first = new LoggerConfiguration("ROOT", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isLessThan(0); } @Test - public void rootLoggerSecondEmpty() { + void rootLoggerSecondEmpty() { LoggerConfiguration first = new LoggerConfiguration("", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("ROOT", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isGreaterThan(0); } @Test - public void lexicalFirst() { + void lexicalFirst() { LoggerConfiguration first = new LoggerConfiguration("alpha", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("bravo", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isLessThan(0); } @Test - public void lexicalSecond() { + void lexicalSecond() { LoggerConfiguration first = new LoggerConfiguration("bravo", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("alpha", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isGreaterThan(0); } @Test - public void lexicalEqual() { + void lexicalEqual() { LoggerConfiguration first = new LoggerConfiguration("alpha", null, LogLevel.OFF); LoggerConfiguration second = new LoggerConfiguration("alpha", null, LogLevel.OFF); assertThat(this.comparator.compare(first, second)).isEqualTo(0); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java index 36a16d042f3..f27da5e8d8d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java @@ -20,9 +20,9 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; @@ -36,48 +36,48 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class LoggingSystemPropertiesTests { +class LoggingSystemPropertiesTests { private Set systemPropertyNames; - @Before + @BeforeEach public void captureSystemPropertyNames() { this.systemPropertyNames = new HashSet<>(System.getProperties().keySet()); } - @After + @AfterEach public void restoreSystemProperties() { System.getProperties().keySet().retainAll(this.systemPropertyNames); } @Test - public void pidIsSet() { + void pidIsSet() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(System.getProperty(LoggingSystemProperties.PID_KEY)).isNotNull(); } @Test - public void consoleLogPatternIsSet() { + void consoleLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) .apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console pattern"); } @Test - public void fileLogPatternIsSet() { + void fileLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) .apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file pattern"); } @Test - public void consoleLogPatternCanReferencePid() { + void consoleLogPatternCanReferencePid() { new LoggingSystemProperties(environment("logging.pattern.console", "${PID:unknown}")).apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).matches("[0-9]+"); } @Test - public void fileLogPatternCanReferencePid() { + void fileLogPatternCanReferencePid() { new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")).apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).matches("[0-9]+"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java index f6d81368cb7..e202dc00af0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.logging; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.logging.LoggingSystem.NoOpLoggingSystem; @@ -29,28 +29,28 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Andy Wilkinson */ -public class LoggingSystemTests { +class LoggingSystemTests { - @After + @AfterEach public void clearSystemProperty() { System.clearProperty(LoggingSystem.SYSTEM_PROPERTY); } @Test - public void loggingSystemCanBeDisabled() { + void loggingSystemCanBeDisabled() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, LoggingSystem.NONE); LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader()); assertThat(loggingSystem).isInstanceOf(NoOpLoggingSystem.class); } @Test - public void getLoggerConfigurationIsUnsupported() { + void getLoggerConfigurationIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); } @Test - public void listLoggerConfigurationsIsUnsupported() { + void listLoggerConfigurationsIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> new StubLoggingSystem().getLoggerConfigurations()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index 0ec3bf21a0b..a9cea892271 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -34,7 +34,7 @@ import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.OutputCaptureRule; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; @@ -55,7 +55,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem(getClass().getClassLoader()); @Rule - public OutputCapture output = new OutputCapture(); + public OutputCaptureRule output = new OutputCaptureRule(); private Logger logger; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java index a4d24cfe87e..99bf8477f84 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ package org.springframework.boot.logging.log4j2; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.AbstractLogEvent; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiOutput; @@ -32,24 +32,24 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Vladimir Tsanev */ -public class ColorConverterTests { +class ColorConverterTests { private final String in = "in"; private TestLogEvent event; - @BeforeClass - public static void setupAnsi() { + @BeforeAll + static void setupAnsi() { AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); } - @AfterClass - public static void resetAnsi() { + @AfterAll + static void resetAnsi() { AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT); } - @Before - public void setUp() { + @BeforeEach + void setUp() { this.event = new TestLogEvent(); } @@ -58,56 +58,56 @@ public class ColorConverterTests { } @Test - public void faint() { + void faint() { StringBuilder output = new StringBuilder(); newConverter("faint").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[2min\033[0;39m"); } @Test - public void red() { + void red() { StringBuilder output = new StringBuilder(); newConverter("red").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[31min\033[0;39m"); } @Test - public void green() { + void green() { StringBuilder output = new StringBuilder(); newConverter("green").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[32min\033[0;39m"); } @Test - public void yellow() { + void yellow() { StringBuilder output = new StringBuilder(); newConverter("yellow").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[33min\033[0;39m"); } @Test - public void blue() { + void blue() { StringBuilder output = new StringBuilder(); newConverter("blue").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[34min\033[0;39m"); } @Test - public void magenta() { + void magenta() { StringBuilder output = new StringBuilder(); newConverter("magenta").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[35min\033[0;39m"); } @Test - public void cyan() { + void cyan() { StringBuilder output = new StringBuilder(); newConverter("cyan").format(this.event, output); assertThat(output.toString()).isEqualTo("\033[36min\033[0;39m"); } @Test - public void highlightFatal() { + void highlightFatal() { this.event.setLevel(Level.FATAL); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); @@ -115,7 +115,7 @@ public class ColorConverterTests { } @Test - public void highlightError() { + void highlightError() { this.event.setLevel(Level.ERROR); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); @@ -123,7 +123,7 @@ public class ColorConverterTests { } @Test - public void highlightWarn() { + void highlightWarn() { this.event.setLevel(Level.WARN); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); @@ -131,7 +131,7 @@ public class ColorConverterTests { } @Test - public void highlightDebug() { + void highlightDebug() { this.event.setLevel(Level.DEBUG); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); @@ -139,7 +139,7 @@ public class ColorConverterTests { } @Test - public void highlightTrace() { + void highlightTrace() { this.event.setLevel(Level.TRACE); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java index f96aa2aab4b..50c29bb3c05 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java @@ -20,7 +20,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vladimir Tsanev * @author Phillip Webb */ -public class ExtendedWhitespaceThrowablePatternConverterTests { +class ExtendedWhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = ExtendedWhitespaceThrowablePatternConverter .newInstance(new DefaultConfiguration(), new String[] {}); @Test - public void noStackTrace() { + void noStackTrace() { LogEvent event = Log4jLogEvent.newBuilder().build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); @@ -44,7 +44,7 @@ public class ExtendedWhitespaceThrowablePatternConverterTests { } @Test - public void withStackTrace() { + void withStackTrace() { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index 43b95b77e50..df6d0866180 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -42,7 +42,7 @@ import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; import org.springframework.boot.testsupport.assertj.Matched; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.OutputCaptureRule; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -66,7 +66,7 @@ import static org.mockito.Mockito.verify; public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Rule - public OutputCapture output = new OutputCapture(); + public OutputCaptureRule output = new OutputCaptureRule(); private final TestLog4J2LoggingSystem loggingSystem = new TestLog4J2LoggingSystem(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java index ccb496f83f3..3b5e650b562 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootConfigurationFactoryTests.java @@ -21,7 +21,7 @@ import java.io.IOException; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class SpringBootConfigurationFactoryTests { +class SpringBootConfigurationFactoryTests { @Test - public void producesConfigurationWithShutdownHookDisabled() throws IOException { + void producesConfigurationWithShutdownHookDisabled() throws IOException { ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(new byte[0])); assertThat(new SpringBootConfigurationFactory().getConfiguration(new LoggerContext(""), source) .isShutdownHookEnabled()).isFalse(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index d2a3ba961a2..e91ec4e2d67 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -20,7 +20,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,13 +29,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Vladimir Tsanev */ -public class WhitespaceThrowablePatternConverterTests { +class WhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = WhitespaceThrowablePatternConverter .newInstance(new DefaultConfiguration(), new String[] {}); @Test - public void noStackTrace() { + void noStackTrace() { LogEvent event = Log4jLogEvent.newBuilder().build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); @@ -43,7 +43,7 @@ public class WhitespaceThrowablePatternConverterTests { } @Test - public void withStackTrace() { + void withStackTrace() { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java index 8f40d0e780e..38025c432fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,9 @@ import java.util.Collections; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.LoggingEvent; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.boot.ansi.AnsiOutput; @@ -34,102 +33,96 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ColorConverterTests { +class ColorConverterTests { - private ColorConverter converter; + private final ColorConverter converter = new ColorConverter(); - private LoggingEvent event; + private final LoggingEvent event = new LoggingEvent(); private final String in = "in"; - @BeforeClass + @BeforeAll public static void setupAnsi() { AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); } - @AfterClass + @AfterAll public static void resetAnsi() { AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT); } - @Before - public void setup() { - this.converter = new ColorConverter(); - this.event = new LoggingEvent(); - } - @Test - public void faint() { + void faint() { this.converter.setOptionList(Collections.singletonList("faint")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[2min\033[0;39m"); } @Test - public void red() { + void red() { this.converter.setOptionList(Collections.singletonList("red")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[31min\033[0;39m"); } @Test - public void green() { + void green() { this.converter.setOptionList(Collections.singletonList("green")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[32min\033[0;39m"); } @Test - public void yellow() { + void yellow() { this.converter.setOptionList(Collections.singletonList("yellow")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[33min\033[0;39m"); } @Test - public void blue() { + void blue() { this.converter.setOptionList(Collections.singletonList("blue")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[34min\033[0;39m"); } @Test - public void magenta() { + void magenta() { this.converter.setOptionList(Collections.singletonList("magenta")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[35min\033[0;39m"); } @Test - public void cyan() { + void cyan() { this.converter.setOptionList(Collections.singletonList("cyan")); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[36min\033[0;39m"); } @Test - public void highlightError() { + void highlightError() { this.event.setLevel(Level.ERROR); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[31min\033[0;39m"); } @Test - public void highlightWarn() { + void highlightWarn() { this.event.setLevel(Level.WARN); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[33min\033[0;39m"); } @Test - public void highlightDebug() { + void highlightDebug() { this.event.setLevel(Level.DEBUG); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[32min\033[0;39m"); } @Test - public void highlightTrace() { + void highlightTrace() { this.event.setLevel(Level.TRACE); String out = this.converter.transform(this.event, this.in); assertThat(out).isEqualTo("\033[32min\033[0;39m"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java index 3d6fda57000..417dd9b1ace 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.logging.logback; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -28,20 +28,20 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Chanwit Kaewkasi */ -public class ExtendedWhitespaceThrowableProxyConverterTests { +class ExtendedWhitespaceThrowableProxyConverterTests { private final ExtendedWhitespaceThrowableProxyConverter converter = new ExtendedWhitespaceThrowableProxyConverter(); private final LoggingEvent event = new LoggingEvent(); @Test - public void noStackTrace() { + void noStackTrace() { String s = this.converter.convert(this.event); assertThat(s).isEmpty(); } @Test - public void withStackTrace() { + void withStackTrace() { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); assertThat(s).startsWith(System.lineSeparator()).endsWith(System.lineSeparator()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java index 2e9d7a53acf..f8b3d081224 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationTests.java @@ -27,7 +27,7 @@ import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.joran.spi.JoranException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class LogbackConfigurationTests { +class LogbackConfigurationTests { @Test - public void consolePatternCanBeOverridden() throws JoranException { + void consolePatternCanBeOverridden() throws JoranException { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); @@ -52,7 +52,7 @@ public class LogbackConfigurationTests { } @Test - public void filePatternCanBeOverridden() throws JoranException { + void filePatternCanBeOverridden() throws JoranException { JoranConfigurator configurator = new JoranConfigurator(); LoggerContext context = new LoggerContext(); configurator.setContext(context); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index be304b287f4..7b732cbf01a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -48,9 +48,9 @@ import org.springframework.boot.logging.LoggingInitializationContext; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; import org.springframework.boot.testsupport.assertj.Matched; -import org.springframework.boot.testsupport.rule.OutputCapture; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.system.OutputCaptureRule; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; @@ -80,7 +80,7 @@ import static org.mockito.Mockito.verify; public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Rule - public OutputCapture output = new OutputCapture(); + public OutputCaptureRule output = new OutputCaptureRule(); private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(getClass().getClassLoader()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java index bf22347db6e..fdae7c55f58 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java @@ -20,23 +20,22 @@ import ch.qos.logback.classic.BasicConfigurator; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.StaticLoggerBinder; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.boot.logging.LoggingInitializationContext; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.context.support.TestPropertySourceUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; /** * Tests for {@link SpringBootJoranConfigurator}. @@ -45,10 +44,8 @@ import static org.hamcrest.Matchers.not; * @author Eddú Meléndez * @author Stephane Nicoll */ -public class SpringBootJoranConfiguratorTests { - - @Rule - public OutputCapture out = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class SpringBootJoranConfiguratorTests { private MockEnvironment environment; @@ -60,8 +57,11 @@ public class SpringBootJoranConfiguratorTests { private Logger logger; - @Before - public void setup() { + private CapturedOutput capturedOutput; + + @BeforeEach + public void setup(CapturedOutput capturedOutput) { + this.capturedOutput = capturedOutput; this.environment = new MockEnvironment(); this.initializationContext = new LoggingInitializationContext(this.environment); this.configurator = new SpringBootJoranConfigurator(this.initializationContext); @@ -70,96 +70,96 @@ public class SpringBootJoranConfiguratorTests { this.logger = this.context.getLogger(getClass()); } - @After + @AfterEach public void reset() { this.context.stop(); new BasicConfigurator().configure((LoggerContext) LoggerFactory.getILoggerFactory()); } @Test - public void profileActive() throws Exception { + void profileActive() throws Exception { this.environment.setActiveProfiles("production"); initialize("production-profile.xml"); this.logger.trace("Hello"); - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } @Test - public void multipleNamesFirstProfileActive() throws Exception { + void multipleNamesFirstProfileActive() throws Exception { this.environment.setActiveProfiles("production"); initialize("multi-profile-names.xml"); this.logger.trace("Hello"); - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } @Test - public void multipleNamesSecondProfileActive() throws Exception { + void multipleNamesSecondProfileActive() throws Exception { this.environment.setActiveProfiles("test"); initialize("multi-profile-names.xml"); this.logger.trace("Hello"); - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } @Test - public void profileNotActive() throws Exception { + void profileNotActive() throws Exception { initialize("production-profile.xml"); this.logger.trace("Hello"); - this.out.expect(not(containsString("Hello"))); + assertThat(this.capturedOutput).doesNotContain("Hello"); } @Test - public void profileExpressionMatchFirst() throws Exception { + void profileExpressionMatchFirst() throws Exception { this.environment.setActiveProfiles("production"); initialize("profile-expression.xml"); this.logger.trace("Hello"); - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } @Test - public void profileExpressionMatchSecond() throws Exception { + void profileExpressionMatchSecond() throws Exception { this.environment.setActiveProfiles("test"); initialize("profile-expression.xml"); this.logger.trace("Hello"); - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } @Test - public void profileExpressionNoMatch() throws Exception { + void profileExpressionNoMatch() throws Exception { this.environment.setActiveProfiles("development"); initialize("profile-expression.xml"); this.logger.trace("Hello"); - this.out.expect(not(containsString("Hello"))); + assertThat(this.capturedOutput).doesNotContain("Hello"); } @Test - public void profileNestedActiveActive() throws Exception { + void profileNestedActiveActive() throws Exception { doTestNestedProfile(true, "outer", "inner"); } @Test - public void profileNestedActiveNotActive() throws Exception { + void profileNestedActiveNotActive() throws Exception { doTestNestedProfile(false, "outer"); } @Test - public void profileNestedNotActiveActive() throws Exception { + void profileNestedNotActiveActive() throws Exception { doTestNestedProfile(false, "inner"); } @Test - public void profileNestedNotActiveNotActive() throws Exception { + void profileNestedNotActiveNotActive() throws Exception { doTestNestedProfile(false); } @Test - public void springProperty() throws Exception { + void springProperty() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.example-property=test"); initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } @Test - public void relaxedSpringProperty() throws Exception { + void relaxedSpringProperty() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "my.EXAMPLE_PROPERTY=test"); ConfigurationPropertySources.attach(this.environment); initialize("property.xml"); @@ -167,25 +167,25 @@ public class SpringBootJoranConfiguratorTests { } @Test - public void springPropertyNoValue() throws Exception { + void springPropertyNoValue() throws Exception { initialize("property.xml"); assertThat(this.context.getProperty("SIMPLE")).isNull(); } @Test - public void relaxedSpringPropertyNoValue() throws Exception { + void relaxedSpringPropertyNoValue() throws Exception { initialize("property.xml"); assertThat(this.context.getProperty("MINE")).isNull(); } @Test - public void springPropertyWithDefaultValue() throws Exception { + void springPropertyWithDefaultValue() throws Exception { initialize("property-default-value.xml"); assertThat(this.context.getProperty("SIMPLE")).isEqualTo("foo"); } @Test - public void relaxedSpringPropertyWithDefaultValue() throws Exception { + void relaxedSpringPropertyWithDefaultValue() throws Exception { initialize("property-default-value.xml"); assertThat(this.context.getProperty("MINE")).isEqualTo("bar"); } @@ -195,10 +195,10 @@ public class SpringBootJoranConfiguratorTests { initialize("nested.xml"); this.logger.trace("Hello"); if (expected) { - this.out.expect(containsString("Hello")); + assertThat(this.capturedOutput).contains("Hello"); } else { - this.out.expect(not(containsString("Hello"))); + assertThat(this.capturedOutput).doesNotContain("Hello"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java index b5551bf7649..1702caa48cd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java @@ -24,8 +24,8 @@ import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.xml.sax.Attributes; @@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class SpringProfileActionTests { +class SpringProfileActionTests { private final Environment environment = mock(Environment.class); @@ -54,13 +54,13 @@ public class SpringProfileActionTests { private final Attributes attributes = mock(Attributes.class); - @Before + @BeforeEach public void setUp() { this.action.setContext(this.context); } @Test - public void environmentIsQueriedWithProfileFromNameAttribute() throws ActionException { + void environmentIsQueriedWithProfileFromNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev"); this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); @@ -74,7 +74,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() throws ActionException { + void environmentIsQueriedWithMultipleProfilesFromCommaSeparatedNameAttribute() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("dev,qa"); this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); @@ -88,7 +88,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() throws ActionException { + void environmentIsQueriedWithResolvedValueWhenNameAttributeUsesAPlaceholder() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile}"); this.context.putProperty("profile", "dev"); this.action.begin(this.interpretationContext, null, this.attributes); @@ -103,7 +103,7 @@ public class SpringProfileActionTests { } @Test - public void environmentIsQueriedWithResolvedValuesFromCommaSeparatedNameNameAttributeWithPlaceholders() + void environmentIsQueriedWithResolvedValuesFromCommaSeparatedNameNameAttributeWithPlaceholders() throws ActionException { given(this.attributes.getValue(Action.NAME_ATTRIBUTE)).willReturn("${profile1},${profile2}"); this.context.putProperty("profile1", "dev"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java index 6634896fa7f..f7277af5531 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.logging.logback; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -28,20 +28,20 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Chanwit Kaewkasi */ -public class WhitespaceThrowableProxyConverterTests { +class WhitespaceThrowableProxyConverterTests { private final WhitespaceThrowableProxyConverter converter = new WhitespaceThrowableProxyConverter(); private final LoggingEvent event = new LoggingEvent(); @Test - public void noStackTrace() { + void noStackTrace() { String s = this.converter.convert(this.event); assertThat(s).isEqualTo(""); } @Test - public void withStackTrace() { + void withStackTrace() { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); assertThat(s).startsWith(System.lineSeparator()).endsWith(System.lineSeparator()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginLookupTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginLookupTests.java index 0d416602cc0..3491eeb6fb6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginLookupTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginLookupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.origin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -28,22 +28,22 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OriginLookupTests { +class OriginLookupTests { @Test - public void getOriginWhenSourceIsNullShouldReturnNull() { + void getOriginWhenSourceIsNullShouldReturnNull() { assertThat(OriginLookup.getOrigin(null, "foo")).isNull(); } @Test - public void getOriginWhenSourceIsNotLookupShouldReturnLookupOrigin() { + void getOriginWhenSourceIsNotLookupShouldReturnLookupOrigin() { Object source = new Object(); assertThat(OriginLookup.getOrigin(source, "foo")).isNull(); } @Test @SuppressWarnings("unchecked") - public void getOriginWhenSourceIsLookupShouldReturnLookupOrigin() { + void getOriginWhenSourceIsLookupShouldReturnLookupOrigin() { OriginLookup source = mock(OriginLookup.class); Origin origin = MockOrigin.of("bar"); given(source.getOrigin("foo")).willReturn(origin); @@ -52,7 +52,7 @@ public class OriginLookupTests { @Test @SuppressWarnings("unchecked") - public void getOriginWhenSourceLookupThrowsAndErrorShouldReturnNull() { + void getOriginWhenSourceLookupThrowsAndErrorShouldReturnNull() { OriginLookup source = mock(OriginLookup.class); willThrow(RuntimeException.class).given(source).getOrigin("foo"); assertThat(OriginLookup.getOrigin(source, "foo")).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java index a5e7bade4db..71c548b468a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.origin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -27,27 +27,27 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OriginTests { +class OriginTests { @Test - public void fromWhenSourceIsNullShouldReturnNull() { + void fromWhenSourceIsNullShouldReturnNull() { assertThat(Origin.from(null)).isNull(); } @Test - public void fromWhenSourceIsRegularObjectShouldReturnNull() { + void fromWhenSourceIsRegularObjectShouldReturnNull() { Object source = new Object(); assertThat(Origin.from(source)).isNull(); } @Test - public void fromWhenSourceIsOriginShouldReturnSource() { + void fromWhenSourceIsOriginShouldReturnSource() { Origin origin = mock(Origin.class); assertThat(Origin.from(origin)).isEqualTo(origin); } @Test - public void fromWhenSourceIsOriginProviderShouldReturnProvidedOrigin() { + void fromWhenSourceIsOriginProviderShouldReturnProvidedOrigin() { Origin origin = mock(Origin.class); OriginProvider originProvider = mock(OriginProvider.class); given(originProvider.getOrigin()).willReturn(origin); @@ -55,14 +55,14 @@ public class OriginTests { } @Test - public void fromWhenSourceIsThrowableShouldUseCause() { + void fromWhenSourceIsThrowableShouldUseCause() { Origin origin = mock(Origin.class); Exception exception = new RuntimeException(new TestException(origin, null)); assertThat(Origin.from(exception)).isEqualTo(origin); } @Test - public void fromWhenSourceIsThrowableAndOriginProviderThatReturnsNullShouldUseCause() { + void fromWhenSourceIsThrowableAndOriginProviderThatReturnsNullShouldUseCause() { Origin origin = mock(Origin.class); Exception exception = new TestException(null, new TestException(origin, null)); assertThat(Origin.from(exception)).isEqualTo(origin); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java index 2013259bef5..d500948e69a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedValueTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.origin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -26,29 +26,29 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class OriginTrackedValueTests { +class OriginTrackedValueTests { @Test - public void getValueShouldReturnValue() { + void getValueShouldReturnValue() { Object value = new Object(); assertThat(OriginTrackedValue.of(value).getValue()).isEqualTo(value); } @Test - public void getOriginShouldReturnOrigin() { + void getOriginShouldReturnOrigin() { Object value = new Object(); Origin origin = mock(Origin.class); assertThat(OriginTrackedValue.of(value, origin).getOrigin()).isEqualTo(origin); } @Test - public void toStringShouldReturnValueToString() { + void toStringShouldReturnValueToString() { Object value = new Object(); assertThat(OriginTrackedValue.of(value).toString()).isEqualTo(value.toString()); } @Test - public void hashCodeAndEqualsShouldIgnoreOrigin() { + void hashCodeAndEqualsShouldIgnoreOrigin() { Object value1 = new Object(); OriginTrackedValue tracked1 = OriginTrackedValue.of(value1); OriginTrackedValue tracked2 = OriginTrackedValue.of(value1, mock(Origin.class)); @@ -58,13 +58,13 @@ public class OriginTrackedValueTests { } @Test - public void ofWhenValueIsNullShouldReturnNull() { + void ofWhenValueIsNullShouldReturnNull() { assertThat(OriginTrackedValue.of(null)).isNull(); assertThat(OriginTrackedValue.of(null, mock(Origin.class))).isNull(); } @Test - public void ofWhenValueIsCharSequenceShouldReturnCharSequence() { + void ofWhenValueIsCharSequenceShouldReturnCharSequence() { String value = "foo"; OriginTrackedValue tracked = OriginTrackedValue.of(value); assertThat(tracked).isInstanceOf(CharSequence.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java index 60a94a5c469..9f1a8ee6313 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.origin; import java.util.HashMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; @@ -34,43 +34,43 @@ import static org.mockito.Mockito.withSettings; * * @author Phillip Webb */ -public class PropertySourceOriginTests { +class PropertySourceOriginTests { @Test - public void createWhenPropertySourceIsNullShouldThrowException() { + void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(null, "name")) .withMessageContaining("PropertySource must not be null"); } @Test - public void createWhenPropertyNameIsNullShouldThrowException() { + void createWhenPropertyNameIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) .withMessageContaining("PropertyName must not be empty"); } @Test - public void createWhenPropertyNameIsEmptyShouldThrowException() { + void createWhenPropertyNameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), "")) .withMessageContaining("PropertyName must not be empty"); } @Test - public void getPropertySourceShouldReturnPropertySource() { + void getPropertySourceShouldReturnPropertySource() { MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>()); PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo"); assertThat(origin.getPropertySource()).isEqualTo(propertySource); } @Test - public void getPropertyNameShouldReturnPropertyName() { + void getPropertyNameShouldReturnPropertyName() { MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>()); PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo"); assertThat(origin.getPropertyName()).isEqualTo("foo"); } @Test - public void toStringShouldShowDetails() { + void toStringShouldShowDetails() { MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>()); PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo"); assertThat(origin.toString()).isEqualTo("\"foo\" from property source \"test\""); @@ -78,7 +78,7 @@ public class PropertySourceOriginTests { @Test @SuppressWarnings("unchecked") - public void getWhenPropertySourceSupportsOriginLookupShouldReturnOrigin() { + void getWhenPropertySourceSupportsOriginLookupShouldReturnOrigin() { Origin origin = mock(Origin.class); PropertySource propertySource = mock(PropertySource.class, withSettings().extraInterfaces(OriginLookup.class)); @@ -88,14 +88,14 @@ public class PropertySourceOriginTests { } @Test - public void getWhenPropertySourceSupportsOriginLookupButNoOriginShouldWrap() { + void getWhenPropertySourceSupportsOriginLookupButNoOriginShouldWrap() { PropertySource propertySource = mock(PropertySource.class, withSettings().extraInterfaces(OriginLookup.class)); assertThat(PropertySourceOrigin.get(propertySource, "foo")).isInstanceOf(PropertySourceOrigin.class); } @Test - public void getWhenPropertySourceIsNotOriginAwareShouldWrap() { + void getWhenPropertySourceIsNotOriginAwareShouldWrap() { MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>()); PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo"); assertThat(origin.getPropertySource()).isEqualTo(propertySource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java index c6b162e150f..5743863ceb0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.origin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -26,26 +26,26 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Madhura Bhave */ -public class SystemEnvironmentOriginTests { +class SystemEnvironmentOriginTests { @Test - public void createWhenPropertyIsNullShouldThrowException() { + void createWhenPropertyIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new SystemEnvironmentOrigin(null)); } @Test - public void createWhenPropertyNameIsEmptyShouldThrowException() { + void createWhenPropertyNameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new SystemEnvironmentOrigin("")); } @Test - public void getPropertyShouldReturnProperty() { + void getPropertyShouldReturnProperty() { SystemEnvironmentOrigin origin = new SystemEnvironmentOrigin("FOO_BAR"); assertThat(origin.getProperty()).isEqualTo("FOO_BAR"); } @Test - public void toStringShouldReturnStringWithDetails() { + void toStringShouldReturnStringWithDetails() { SystemEnvironmentOrigin origin = new SystemEnvironmentOrigin("FOO_BAR"); assertThat(origin.toString()).isEqualTo("System Environment Property \"FOO_BAR\""); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java index 199442aa09c..7292bd2ae50 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/TextResourceOriginTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.origin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.origin.TextResourceOrigin.Location; import org.springframework.core.io.ClassPathResource; @@ -28,29 +28,29 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class TextResourceOriginTests { +class TextResourceOriginTests { @Test - public void createWithNullResourceShouldSetNullResource() { + void createWithNullResourceShouldSetNullResource() { TextResourceOrigin origin = new TextResourceOrigin(null, null); assertThat(origin.getResource()).isNull(); } @Test - public void createWithNullLocationShouldSetNullLocation() { + void createWithNullLocationShouldSetNullLocation() { TextResourceOrigin origin = new TextResourceOrigin(null, null); assertThat(origin.getLocation()).isNull(); } @Test - public void getResourceShouldReturnResource() { + void getResourceShouldReturnResource() { ClassPathResource resource = new ClassPathResource("foo.txt"); TextResourceOrigin origin = new TextResourceOrigin(resource, null); assertThat(origin.getResource()).isEqualTo(resource); } @Test - public void getLocationShouldReturnLocation() { + void getLocationShouldReturnLocation() { Location location = new Location(1, 2); TextResourceOrigin origin = new TextResourceOrigin(null, location); assertThat(origin.getLocation()).isEqualTo(location); @@ -58,25 +58,25 @@ public class TextResourceOriginTests { } @Test - public void getLocationLineShouldReturnLine() { + void getLocationLineShouldReturnLine() { Location location = new Location(1, 2); assertThat(location.getLine()).isEqualTo(1); } @Test - public void getLocationColumnShouldReturnColumn() { + void getLocationColumnShouldReturnColumn() { Location location = new Location(1, 2); assertThat(location.getColumn()).isEqualTo(2); } @Test - public void locationToStringShouldReturnNiceString() { + void locationToStringShouldReturnNiceString() { Location location = new Location(1, 2); assertThat(location.toString()).isEqualTo("2:3"); } @Test - public void toStringShouldReturnNiceString() { + void toStringShouldReturnNiceString() { ClassPathResource resource = new ClassPathResource("foo.txt"); Location location = new Location(1, 2); TextResourceOrigin origin = new TextResourceOrigin(resource, location); @@ -84,21 +84,21 @@ public class TextResourceOriginTests { } @Test - public void toStringWhenResourceIsNullShouldReturnNiceString() { + void toStringWhenResourceIsNullShouldReturnNiceString() { Location location = new Location(1, 2); TextResourceOrigin origin = new TextResourceOrigin(null, location); assertThat(origin.toString()).isEqualTo("unknown resource [?]:2:3"); } @Test - public void toStringWhenLocationIsNullShouldReturnNiceString() { + void toStringWhenLocationIsNullShouldReturnNiceString() { ClassPathResource resource = new ClassPathResource("foo.txt"); TextResourceOrigin origin = new TextResourceOrigin(resource, null); assertThat(origin.toString()).isEqualTo("class path resource [foo.txt]"); } @Test - public void locationEqualsAndHashCodeShouldUseLineAndColumn() { + void locationEqualsAndHashCodeShouldUseLineAndColumn() { Location location1 = new Location(1, 2); Location location2 = new Location(1, 2); Location location3 = new Location(2, 2); @@ -111,7 +111,7 @@ public class TextResourceOriginTests { } @Test - public void equalsAndHashCodeShouldResourceAndLocation() { + void equalsAndHashCodeShouldResourceAndLocation() { TextResourceOrigin origin1 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(1, 2)); TextResourceOrigin origin2 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(1, 2)); TextResourceOrigin origin3 = new TextResourceOrigin(new ClassPathResource("foo.txt"), new Location(2, 2)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java index 7b4c78a0828..e35e7c7613d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/orm/jpa/hibernate/SpringPhysicalNamingStrategyTests.java @@ -24,8 +24,8 @@ import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.mapping.PersistentClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -35,13 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Madhura Bhave */ -public class SpringPhysicalNamingStrategyTests { +class SpringPhysicalNamingStrategyTests { private Metadata metadata; private MetadataSources metadataSources; - @Before + @BeforeEach public void setup() { this.metadataSources = new MetadataSources(createServiceRegistry()); this.metadataSources.addAnnotatedClass(TelephoneNumber.class); @@ -54,13 +54,13 @@ public class SpringPhysicalNamingStrategyTests { } @Test - public void tableNameShouldBeLowercaseUnderscore() { + void tableNameShouldBeLowercaseUnderscore() { PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); assertThat(binding.getTable().getQuotedName()).isEqualTo("telephone_number"); } @Test - public void tableNameShouldNotBeLowerCaseIfCaseSensitive() { + void tableNameShouldNotBeLowerCaseIfCaseSensitive() { this.metadata = this.metadataSources.getMetadataBuilder() .applyPhysicalNamingStrategy(new TestSpringPhysicalNamingStrategy()).build(); PersistentClass binding = this.metadata.getEntityBinding(TelephoneNumber.class.getName()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java index 6faaa0539c5..b194364e9a7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java @@ -30,15 +30,13 @@ import io.rsocket.SocketAcceptor; import io.rsocket.transport.netty.client.WebsocketClientTransport; import io.rsocket.util.DefaultPayload; import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import reactor.core.publisher.Mono; import org.springframework.boot.rsocket.server.RSocketServer; import org.springframework.boot.rsocket.server.ServerRSocketFactoryCustomizer; -import org.springframework.boot.testsupport.rule.OutputCapture; import org.springframework.core.codec.CharSequenceEncoder; import org.springframework.core.codec.StringDecoder; import org.springframework.core.io.buffer.NettyDataBufferFactory; @@ -57,10 +55,7 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class NettyRSocketServerFactoryTests { - - @Rule - public OutputCapture output = new OutputCapture(); +class NettyRSocketServerFactoryTests { private NettyRSocketServer rSocketServer; @@ -68,7 +63,7 @@ public class NettyRSocketServerFactoryTests { private static final Duration TIMEOUT = Duration.ofSeconds(3); - @After + @AfterEach public void tearDown() { if (this.rSocketServer != null) { try { @@ -88,7 +83,7 @@ public class NettyRSocketServerFactoryTests { } @Test - public void specificPort() { + void specificPort() { NettyRSocketServerFactory factory = getFactory(); int specificPort = SocketUtils.findAvailableTcpPort(41000); factory.setPort(specificPort); @@ -103,7 +98,7 @@ public class NettyRSocketServerFactoryTests { } @Test - public void websocketTransport() { + void websocketTransport() { NettyRSocketServerFactory factory = getFactory(); factory.setTransport(RSocketServer.TRANSPORT.WEBSOCKET); this.rSocketServer = factory.create(new EchoRequestResponseAcceptor()); @@ -115,7 +110,7 @@ public class NettyRSocketServerFactoryTests { } @Test - public void serverCustomizers() { + void serverCustomizers() { NettyRSocketServerFactory factory = getFactory(); ServerRSocketFactoryCustomizer[] customizers = new ServerRSocketFactoryCustomizer[2]; for (int i = 0; i < customizers.length; i++) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index 0a84182202a..a4f9cdc0e87 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.security.reactive; import java.util.function.Supplier; -import org.junit.Test; +import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -44,17 +44,17 @@ import static org.mockito.Mockito.mock; * * @author Madhura Bhave */ -public class ApplicationContextServerWebExchangeMatcherTests { +class ApplicationContextServerWebExchangeMatcherTests { @Test - public void createWhenContextClassIsNullShouldThrowException() { + void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) .withMessageContaining("Context class must not be null"); } @Test - public void matchesWhenContextClassIsApplicationContextShouldProvideContext() { + void matchesWhenContextClassIsApplicationContextShouldProvideContext() { ServerWebExchange exchange = createExchange(); StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ApplicationContext.class) @@ -62,7 +62,7 @@ public class ApplicationContextServerWebExchangeMatcherTests { } @Test - public void matchesWhenContextClassIsExistingBeanShouldProvideBean() { + void matchesWhenContextClassIsExistingBeanShouldProvideBean() { ServerWebExchange exchange = createExchange(); StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); @@ -71,7 +71,7 @@ public class ApplicationContextServerWebExchangeMatcherTests { } @Test - public void matchesWhenContextClassIsMissingBeanShouldProvideException() { + void matchesWhenContextClassIsMissingBeanShouldProvideException() { ServerWebExchange exchange = createExchange(); Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) .callMatchesAndReturnProvidedContext(exchange); @@ -79,7 +79,7 @@ public class ApplicationContextServerWebExchangeMatcherTests { } @Test - public void matchesWhenContextIsNull() { + void matchesWhenContextIsNull() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); assertThatIllegalStateException() .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java index bbb63f06665..c513f1ad408 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java @@ -20,7 +20,7 @@ import java.util.function.Supplier; import javax.servlet.http.HttpServletRequest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; @@ -38,23 +38,23 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * * @author Phillip Webb */ -public class ApplicationContextRequestMatcherTests { +class ApplicationContextRequestMatcherTests { @Test - public void createWhenContextClassIsNullShouldThrowException() { + void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) .withMessageContaining("Context class must not be null"); } @Test - public void matchesWhenContextClassIsApplicationContextShouldProvideContext() { + void matchesWhenContextClassIsApplicationContextShouldProvideContext() { StaticWebApplicationContext context = createWebApplicationContext(); assertThat(new TestApplicationContextRequestMatcher<>(ApplicationContext.class) .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context); } @Test - public void matchesWhenContextClassIsExistingBeanShouldProvideBean() { + void matchesWhenContextClassIsExistingBeanShouldProvideBean() { StaticWebApplicationContext context = createWebApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextRequestMatcher<>(ExistingBean.class) @@ -62,7 +62,7 @@ public class ApplicationContextRequestMatcherTests { } @Test - public void matchesWhenContextClassIsBeanThatDoesNotExistShouldSupplyException() { + void matchesWhenContextClassIsBeanThatDoesNotExistShouldSupplyException() { StaticWebApplicationContext context = createWebApplicationContext(); Supplier supplier = new TestApplicationContextRequestMatcher<>(ExistingBean.class) .callMatchesAndReturnProvidedContext(context); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java index 1d2c9b6ce64..5f0b7262f4d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java @@ -18,9 +18,8 @@ package org.springframework.boot.system; import java.io.File; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -31,48 +30,48 @@ import static org.assertj.core.api.Assertions.contentOf; * * @author Phillip Webb */ -public class ApplicationPidTests { +class ApplicationPidTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void toStringWithPid() { + void toStringWithPid() { assertThat(new ApplicationPid("123").toString()).isEqualTo("123"); } @Test - public void toStringWithoutPid() { + void toStringWithoutPid() { assertThat(new ApplicationPid(null).toString()).isEqualTo("???"); } @Test - public void throwIllegalStateWritingMissingPid() { + void throwIllegalStateWritingMissingPid() { ApplicationPid pid = new ApplicationPid(null); - assertThatIllegalStateException().isThrownBy(() -> pid.write(this.temporaryFolder.newFile())) + assertThatIllegalStateException().isThrownBy(() -> pid.write(new File(this.tempDir, "pid"))) .withMessageContaining("No PID available"); } @Test - public void writePid() throws Exception { + void writePid() throws Exception { ApplicationPid pid = new ApplicationPid("123"); - File file = this.temporaryFolder.newFile(); + File file = new File(this.tempDir, "pid"); pid.write(file); assertThat(contentOf(file)).isEqualTo("123"); } @Test - public void writeNewPid() throws Exception { + void writeNewPid() throws Exception { // gh-10784 ApplicationPid pid = new ApplicationPid("123"); - File file = this.temporaryFolder.newFile(); + File file = new File(this.tempDir, "pid"); file.delete(); pid.write(file); assertThat(contentOf(file)).isEqualTo("123"); } @Test - public void getPidFromJvm() { + void getPidFromJvm() { assertThat(new ApplicationPid().toString()).isNotEmpty(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java index 9ed9523636f..ec924357260 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.boot.system; import java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class ApplicationTempTests { +class ApplicationTempTests { @Test - public void generatesConsistentTemp() { + void generatesConsistentTemp() { ApplicationTemp t1 = new ApplicationTemp(); ApplicationTemp t2 = new ApplicationTemp(); assertThat(t1.getDir()).isNotNull(); @@ -38,7 +38,7 @@ public class ApplicationTempTests { } @Test - public void differentBasedOnUserDir() { + void differentBasedOnUserDir() { String userDir = System.getProperty("user.dir"); try { File t1 = new ApplicationTemp().getDir(); @@ -52,7 +52,7 @@ public class ApplicationTempTests { } @Test - public void getSubDir() { + void getSubDir() { ApplicationTemp temp = new ApplicationTemp(); assertThat(temp.getDir("abc")).isEqualTo(new File(temp.getDir(), "abc")); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/JavaVersionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/JavaVersionTests.java index 99de2e3de09..e9ee256328b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/JavaVersionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/JavaVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.system; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -25,55 +25,55 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class JavaVersionTests { +class JavaVersionTests { @Test - public void getJavaVersionShouldBeAvailable() { + void getJavaVersionShouldBeAvailable() { assertThat(JavaVersion.getJavaVersion()).isNotNull(); } @Test - public void compareToWhenComparingSmallerToGreaterShouldBeLessThanZero() { + void compareToWhenComparingSmallerToGreaterShouldBeLessThanZero() { assertThat(JavaVersion.EIGHT.compareTo(JavaVersion.NINE)).isLessThan(0); } @Test - public void compareToWhenComparingGreaterToSmallerShouldBeGreaterThanZero() { + void compareToWhenComparingGreaterToSmallerShouldBeGreaterThanZero() { assertThat(JavaVersion.NINE.compareTo(JavaVersion.EIGHT)).isGreaterThan(0); } @Test - public void compareToWhenComparingSameShouldBeZero() { + void compareToWhenComparingSameShouldBeZero() { assertThat(JavaVersion.EIGHT.compareTo(JavaVersion.EIGHT)).isEqualTo(0); } @Test - public void isEqualOrNewerThanWhenComparingSameShouldBeTrue() { + void isEqualOrNewerThanWhenComparingSameShouldBeTrue() { assertThat(JavaVersion.EIGHT.isEqualOrNewerThan(JavaVersion.EIGHT)).isTrue(); } @Test - public void isEqualOrNewerThanWhenSmallerToGreaterShouldBeFalse() { + void isEqualOrNewerThanWhenSmallerToGreaterShouldBeFalse() { assertThat(JavaVersion.EIGHT.isEqualOrNewerThan(JavaVersion.NINE)).isFalse(); } @Test - public void isEqualOrNewerThanWhenGreaterToSmallerShouldBeTrue() { + void isEqualOrNewerThanWhenGreaterToSmallerShouldBeTrue() { assertThat(JavaVersion.NINE.isEqualOrNewerThan(JavaVersion.EIGHT)).isTrue(); } @Test - public void isOlderThanThanWhenComparingSameShouldBeFalse() { + void isOlderThanThanWhenComparingSameShouldBeFalse() { assertThat(JavaVersion.EIGHT.isOlderThan(JavaVersion.EIGHT)).isFalse(); } @Test - public void isOlderThanWhenSmallerToGreaterShouldBeTrue() { + void isOlderThanWhenSmallerToGreaterShouldBeTrue() { assertThat(JavaVersion.EIGHT.isOlderThan(JavaVersion.NINE)).isTrue(); } @Test - public void isOlderThanWhenGreaterToSmallerShouldBeFalse() { + void isOlderThanWhenGreaterToSmallerShouldBeFalse() { assertThat(JavaVersion.NINE.isOlderThan(JavaVersion.EIGHT)).isFalse(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java index daaed9117c7..4b19060c3ff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java @@ -20,7 +20,7 @@ import java.time.Duration; import java.util.Collections; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.task.TaskDecorator; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -39,12 +39,12 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Stephane Nicoll * @author Filip Hrisafov */ -public class TaskExecutorBuilderTests { +class TaskExecutorBuilderTests { private TaskExecutorBuilder builder = new TaskExecutorBuilder(); @Test - public void poolSettingsShouldApply() { + void poolSettingsShouldApply() { ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8) .allowCoreThreadTimeOut(true).keepAlive(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("queueCapacity", 10); @@ -55,52 +55,52 @@ public class TaskExecutorBuilderTests { } @Test - public void awaitTerminationShouldApply() { + void awaitTerminationShouldApply() { ThreadPoolTaskExecutor executor = this.builder.awaitTermination(true).build(); assertThat(executor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); } @Test - public void awaitTerminationPeriodShouldApply() { + void awaitTerminationPeriodShouldApply() { ThreadPoolTaskExecutor executor = this.builder.awaitTerminationPeriod(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 60); } @Test - public void threadNamePrefixShouldApply() { + void threadNamePrefixShouldApply() { ThreadPoolTaskExecutor executor = this.builder.threadNamePrefix("test-").build(); assertThat(executor.getThreadNamePrefix()).isEqualTo("test-"); } @Test - public void taskDecoratorShouldApply() { + void taskDecoratorShouldApply() { TaskDecorator taskDecorator = mock(TaskDecorator.class); ThreadPoolTaskExecutor executor = this.builder.taskDecorator(taskDecorator).build(); assertThat(ReflectionTestUtils.getField(executor, "taskDecorator")).isSameAs(taskDecorator); } @Test - public void customizersWhenCustomizersAreNullShouldThrowException() { + void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((TaskExecutorCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { + void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersShouldApply() { + void customizersShouldApply() { TaskExecutorCustomizer customizer = mock(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = this.builder.customizers(customizer).build(); verify(customizer).customize(executor); } @Test - public void customizersShouldBeAppliedLast() { + void customizersShouldBeAppliedLast() { TaskDecorator taskDecorator = mock(TaskDecorator.class); ThreadPoolTaskExecutor executor = spy(new ThreadPoolTaskExecutor()); this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8).allowCoreThreadTimeOut(true) @@ -120,7 +120,7 @@ public class TaskExecutorBuilderTests { } @Test - public void customizersShouldReplaceExisting() { + void customizersShouldReplaceExisting() { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) @@ -130,21 +130,21 @@ public class TaskExecutorBuilderTests { } @Test - public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersShouldAddToExisting() { + void additionalCustomizersShouldAddToExisting() { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1).additionalCustomizers(customizer2) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java index 940ae3d0549..03827f6274a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java @@ -20,7 +20,7 @@ import java.time.Duration; import java.util.Collections; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; @@ -36,57 +36,57 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Stephane Nicoll */ -public class TaskSchedulerBuilderTests { +class TaskSchedulerBuilderTests { private TaskSchedulerBuilder builder = new TaskSchedulerBuilder(); @Test - public void poolSettingsShouldApply() { + void poolSettingsShouldApply() { ThreadPoolTaskScheduler scheduler = this.builder.poolSize(4).build(); assertThat(scheduler.getPoolSize()).isEqualTo(4); } @Test - public void awaitTerminationShouldApply() { + void awaitTerminationShouldApply() { ThreadPoolTaskScheduler executor = this.builder.awaitTermination(true).build(); assertThat(executor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); } @Test - public void awaitTerminationPeriodShouldApply() { + void awaitTerminationPeriodShouldApply() { ThreadPoolTaskScheduler executor = this.builder.awaitTerminationPeriod(Duration.ofMinutes(1)).build(); assertThat(executor).hasFieldOrPropertyWithValue("awaitTerminationSeconds", 60); } @Test - public void threadNamePrefixShouldApply() { + void threadNamePrefixShouldApply() { ThreadPoolTaskScheduler scheduler = this.builder.threadNamePrefix("test-").build(); assertThat(scheduler.getThreadNamePrefix()).isEqualTo("test-"); } @Test - public void customizersWhenCustomizersAreNullShouldThrowException() { + void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { + void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersShouldApply() { + void customizersShouldApply() { TaskSchedulerCustomizer customizer = mock(TaskSchedulerCustomizer.class); ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer).build(); verify(customizer).customize(scheduler); } @Test - public void customizersShouldBeAppliedLast() { + void customizersShouldBeAppliedLast() { ThreadPoolTaskScheduler scheduler = spy(new ThreadPoolTaskScheduler()); this.builder.poolSize(4).threadNamePrefix("test-").additionalCustomizers((taskScheduler) -> { verify(taskScheduler).setPoolSize(4); @@ -96,7 +96,7 @@ public class TaskSchedulerBuilderTests { } @Test - public void customizersShouldReplaceExisting() { + void customizersShouldReplaceExisting() { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) @@ -106,21 +106,21 @@ public class TaskSchedulerBuilderTests { } @Test - public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersShouldAddToExisting() { + void additionalCustomizersShouldAddToExisting() { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1).additionalCustomizers(customizer2) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java index 57b09313a06..0720e346fe0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.boot.type.classreading; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.Resource; import org.springframework.core.type.classreading.MetadataReader; @@ -34,10 +34,10 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ConcurrentReferenceCachingMetadataReaderFactoryTests { +class ConcurrentReferenceCachingMetadataReaderFactoryTests { @Test - public void getMetadataReaderUsesCache() throws Exception { + void getMetadataReaderUsesCache() throws Exception { TestConcurrentReferenceCachingMetadataReaderFactory factory = spy( new TestConcurrentReferenceCachingMetadataReaderFactory()); MetadataReader metadataReader1 = factory.getMetadataReader(getClass().getName()); @@ -47,7 +47,7 @@ public class ConcurrentReferenceCachingMetadataReaderFactoryTests { } @Test - public void clearResetsCache() throws Exception { + void clearResetsCache() throws Exception { TestConcurrentReferenceCachingMetadataReaderFactory factory = spy( new TestConcurrentReferenceCachingMetadataReaderFactory()); MetadataReader metadataReader1 = factory.getMetadataReader(getClass().getName()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index 0c874cb0719..d1350e29739 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java @@ -22,14 +22,14 @@ import java.util.List; import java.util.stream.Stream; import org.apache.commons.logging.Log; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.util.LambdaSafe.Filter; import org.springframework.boot.util.LambdaSafe.InvocationResult; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.BDDMockito.given; @@ -42,22 +42,22 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Phillip Webb */ -public class LambdaSafeTests { +class LambdaSafeTests { @Test - public void callbackWhenCallbackTypeIsNullShouldThrowException() { + void callbackWhenCallbackTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) .withMessageContaining("CallbackType must not be null"); } @Test - public void callbackWhenCallbackInstanceIsNullShouldThrowException() { + void callbackWhenCallbackInstanceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) .withMessageContaining("CallbackInstance must not be null"); } @Test - public void callbackInvokeWhenNoGenericShouldInvokeCallback() { + void callbackInvokeWhenNoGenericShouldInvokeCallback() { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; LambdaSafe.callback(NonGenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); @@ -66,7 +66,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeWhenHasGenericShouldInvokeCallback() { + void callbackInvokeWhenHasGenericShouldInvokeCallback() { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); @@ -75,7 +75,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { + void callbackInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); @@ -84,7 +84,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { + void callbackInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); @@ -93,7 +93,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeWhenLambdaMismatchShouldSwallowException() { + void callbackInvokeWhenLambdaMismatchShouldSwallowException() { GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).invoke((c) -> c.handle(argument)); @@ -101,7 +101,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { + void callbackInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callback(GenericMultiArgCallback.class, callbackInstance, argument) @@ -109,7 +109,7 @@ public class LambdaSafeTests { } @Test - public void callbackInvokeAndWhenNoGenericShouldReturnResult() { + void callbackInvokeAndWhenNoGenericShouldReturnResult() { NonGenericFactory callbackInstance = mock(NonGenericFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); @@ -121,7 +121,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenHasGenericShouldReturnResult() { + void callbackInvokeAndWhenHasGenericShouldReturnResult() { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); @@ -133,7 +133,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenReturnNullShouldReturnResult() { + void callbackInvokeAndWhenReturnNullShouldReturnResult() { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); @@ -145,7 +145,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenHasResolvableGenericMatchShouldReturnResult() { + void callbackInvokeAndWhenHasResolvableGenericMatchShouldReturnResult() { StringBuilderFactory callbackInstance = mock(StringBuilderFactory.class); StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); @@ -158,7 +158,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { + void callbackInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) @@ -169,7 +169,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenLambdaMismatchShouldSwallowException() { + void callbackInvokeAndWhenLambdaMismatchShouldSwallowException() { GenericFactory callbackInstance = (s) -> { fail("Should not get here"); return 123; @@ -182,7 +182,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackInvokeAndWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { + void callbackInvokeAndWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { GenericMultiArgFactory callbackInstance = (n, s, b) -> { fail("Should not get here"); return 123; @@ -194,7 +194,7 @@ public class LambdaSafeTests { } @Test - public void callbacksInvokeWhenNoGenericShouldInvokeCallbacks() { + void callbacksInvokeWhenNoGenericShouldInvokeCallbacks() { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; LambdaSafe.callbacks(NonGenericCallback.class, Collections.singleton(callbackInstance), argument) @@ -204,7 +204,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenHasGenericShouldInvokeCallback() { + void callbacksInvokeWhenHasGenericShouldInvokeCallback() { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) @@ -214,7 +214,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { + void callbacksInvokeWhenHasResolvableGenericMatchShouldInvokeCallback() { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) @@ -224,7 +224,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { + void callbacksInvokeWhenHasResolvableGenericNonMatchShouldNotInvokeCallback() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) @@ -234,7 +234,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenLambdaMismatchShouldSwallowException() { + void callbacksInvokeWhenLambdaMismatchShouldSwallowException() { GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) @@ -243,7 +243,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { + void callbacksInvokeWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericMultiArgCallback.class, Collections.singleton(callbackInstance), argument) @@ -251,7 +251,7 @@ public class LambdaSafeTests { } @Test - public void callbacksInvokeAndWhenNoGenericShouldReturnResult() { + void callbacksInvokeAndWhenNoGenericShouldReturnResult() { NonGenericFactory callbackInstance = mock(NonGenericFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); @@ -263,7 +263,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenHasGenericShouldReturnResult() { + void callbacksInvokeAndWhenHasGenericShouldReturnResult() { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); @@ -275,7 +275,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenReturnNullShouldReturnResult() { + void callbacksInvokeAndWhenReturnNullShouldReturnResult() { StringFactory callbackInstance = mock(StringFactory.class); String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); @@ -287,7 +287,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenHasResolvableGenericMatchShouldReturnResult() { + void callbacksInvokeAndWhenHasResolvableGenericMatchShouldReturnResult() { StringBuilderFactory callbackInstance = mock(StringBuilderFactory.class); StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); @@ -299,7 +299,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { + void callbacksInvokeAndWhenHasResolvableGenericNonMatchShouldReturnNoResult() { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; Stream result = LambdaSafe @@ -310,7 +310,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenLambdaMismatchShouldSwallowException() { + void callbacksInvokeAndWhenLambdaMismatchShouldSwallowException() { GenericFactory callbackInstance = (s) -> { fail("Should not get here"); return 123; @@ -324,7 +324,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeAndWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { + void callbacksInvokeAndWhenLambdaMismatchOnDifferentArgumentShouldSwallowException() { GenericMultiArgFactory callbackInstance = (n, s, b) -> { fail("Should not get here"); return 123; @@ -338,7 +338,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbacksInvokeWhenMultipleShouldInvokeSuitable() { + void callbacksInvokeWhenMultipleShouldInvokeSuitable() { List> callbackInstances = new ArrayList<>(); GenericFactory callback1 = (s) -> 1; GenericFactory callback2 = (s) -> 2; @@ -360,7 +360,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackWithFilterShouldUseFilter() { + void callbackWithFilterShouldUseFilter() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withFilter(Filter.allowAll()) @@ -370,7 +370,7 @@ public class LambdaSafeTests { @Test @SuppressWarnings("unchecked") - public void callbackWithLoggerShouldUseLogger() { + void callbackWithLoggerShouldUseLogger() { Log logger = mock(Log.class); given(logger.isDebugEnabled()).willReturn(true); GenericCallback callbackInstance = (s) -> fail("Should not get here"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java index e7fc64bfe70..9ca7cf0b62f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.boot.validation; import javax.validation.MessageInterpolator; import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -28,10 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class MessageInterpolatorFactoryTests { +class MessageInterpolatorFactoryTests { @Test - public void getObjectShouldReturnResourceBundleMessageInterpolator() { + void getObjectShouldReturnResourceBundleMessageInterpolator() { MessageInterpolator interpolator = new MessageInterpolatorFactory().getObject(); assertThat(interpolator).isInstanceOf(ResourceBundleMessageInterpolator.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java index 01cc0203755..cf8951052e8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/BasicAuthenticationClientHttpRequestFactoryTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.web.client; import java.io.IOException; import java.net.URI; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; * * @author Dmytro Nosan */ -public class BasicAuthenticationClientHttpRequestFactoryTests { +class BasicAuthenticationClientHttpRequestFactoryTests { private final HttpHeaders headers = new HttpHeaders(); @@ -45,7 +45,7 @@ public class BasicAuthenticationClientHttpRequestFactoryTests { private ClientHttpRequestFactory requestFactory; - @Before + @BeforeEach public void setUp() throws IOException { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); ClientHttpRequest request = mock(ClientHttpRequest.class); @@ -55,13 +55,13 @@ public class BasicAuthenticationClientHttpRequestFactoryTests { } @Test - public void shouldAddAuthorizationHeader() throws IOException { + void shouldAddAuthorizationHeader() throws IOException { ClientHttpRequest request = createRequest(); assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly("Basic c3ByaW5nOmJvb3Q="); } @Test - public void shouldNotAddAuthorizationHeaderAuthorizationAlreadySet() throws IOException { + void shouldNotAddAuthorizationHeaderAuthorizationAlreadySet() throws IOException { this.headers.setBasicAuth("boot", "spring"); ClientHttpRequest request = createRequest(); assertThat(request.getHeaders().get(HttpHeaders.AUTHORIZATION)).doesNotContain("Basic c3ByaW5nOmJvb3Q="); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 1f6827266f1..c8158b233da 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -23,8 +23,8 @@ import java.util.Set; import java.util.function.Supplier; import org.apache.http.client.config.RequestConfig; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -66,7 +66,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * @author Dmytro Nosan * @author Kevin Strijbos */ -public class RestTemplateBuilderTests { +class RestTemplateBuilderTests { private RestTemplateBuilder builder = new RestTemplateBuilder(); @@ -76,39 +76,39 @@ public class RestTemplateBuilderTests { @Mock private ClientHttpRequestInterceptor interceptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void createWhenCustomizersAreNullShouldThrowException() { + void createWhenCustomizersAreNullShouldThrowException() { RestTemplateCustomizer[] customizers = null; assertThatIllegalArgumentException().isThrownBy(() -> new RestTemplateBuilder(customizers)) .withMessageContaining("Customizers must not be null"); } @Test - public void createWithCustomizersShouldApplyCustomizers() { + void createWithCustomizersShouldApplyCustomizers() { RestTemplateCustomizer customizer = mock(RestTemplateCustomizer.class); RestTemplate template = new RestTemplateBuilder(customizer).build(); verify(customizer).customize(template); } @Test - public void buildShouldDetectRequestFactory() { + void buildShouldDetectRequestFactory() { RestTemplate restTemplate = this.builder.build(); assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test - public void detectRequestFactoryWhenFalseShouldDisableDetection() { + void detectRequestFactoryWhenFalseShouldDisableDetection() { RestTemplate restTemplate = this.builder.detectRequestFactory(false).build(); assertThat(restTemplate.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test - public void rootUriShouldApply() { + void rootUriShouldApply() { RestTemplate restTemplate = this.builder.rootUri("https://example.com").build(); MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(); server.expect(requestTo("https://example.com/hello")).andRespond(withSuccess()); @@ -117,7 +117,7 @@ public class RestTemplateBuilderTests { } @Test - public void rootUriShouldApplyAfterUriTemplateHandler() { + void rootUriShouldApplyAfterUriTemplateHandler() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).rootUri("https://example.com") .build(); @@ -128,48 +128,48 @@ public class RestTemplateBuilderTests { } @Test - public void messageConvertersWhenConvertersAreNullShouldThrowException() { + void messageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) .withMessageContaining("MessageConverters must not be null"); } @Test - public void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { + void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.messageConverters((Set>) null)) .withMessageContaining("MessageConverters must not be null"); } @Test - public void messageConvertersShouldApply() { + void messageConvertersShouldApply() { RestTemplate template = this.builder.messageConverters(this.messageConverter).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test - public void messageConvertersShouldReplaceExisting() { + void messageConvertersShouldReplaceExisting() { RestTemplate template = this.builder.messageConverters(new ResourceHttpMessageConverter()) .messageConverters(Collections.singleton(this.messageConverter)).build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test - public void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { + void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) .withMessageContaining("MessageConverters must not be null"); } @Test - public void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { + void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) .withMessageContaining("MessageConverters must not be null"); } @Test - public void additionalMessageConvertersShouldAddToExisting() { + void additionalMessageConvertersShouldAddToExisting() { HttpMessageConverter resourceConverter = new ResourceHttpMessageConverter(); RestTemplate template = this.builder.messageConverters(resourceConverter) .additionalMessageConverters(this.messageConverter).build(); @@ -177,128 +177,128 @@ public class RestTemplateBuilderTests { } @Test - public void defaultMessageConvertersShouldSetDefaultList() { + void defaultMessageConvertersShouldSetDefaultList() { RestTemplate template = new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())); this.builder.defaultMessageConverters().configure(template); assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test - public void defaultMessageConvertersShouldClearExisting() { + void defaultMessageConvertersShouldClearExisting() { RestTemplate template = new RestTemplate(Collections.singletonList(new StringHttpMessageConverter())); this.builder.additionalMessageConverters(this.messageConverter).defaultMessageConverters().configure(template); assertThat(template.getMessageConverters()).hasSameSizeAs(new RestTemplate().getMessageConverters()); } @Test - public void interceptorsWhenInterceptorsAreNullShouldThrowException() { + void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) .withMessageContaining("interceptors must not be null"); } @Test - public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { + void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.interceptors((Set) null)) .withMessageContaining("interceptors must not be null"); } @Test - public void interceptorsShouldApply() { + void interceptorsShouldApply() { RestTemplate template = this.builder.interceptors(this.interceptor).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test - public void interceptorsShouldReplaceExisting() { + void interceptorsShouldReplaceExisting() { RestTemplate template = this.builder.interceptors(mock(ClientHttpRequestInterceptor.class)) .interceptors(Collections.singleton(this.interceptor)).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test - public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { + void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) .withMessageContaining("interceptors must not be null"); } @Test - public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { + void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) .withMessageContaining("interceptors must not be null"); } @Test - public void additionalInterceptorsShouldAddToExisting() { + void additionalInterceptorsShouldAddToExisting() { ClientHttpRequestInterceptor interceptor = mock(ClientHttpRequestInterceptor.class); RestTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor).build(); assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @Test - public void requestFactoryClassWhenFactoryIsNullShouldThrowException() { + void requestFactoryClassWhenFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.requestFactory((Class) null)) .withMessageContaining("RequestFactory must not be null"); } @Test - public void requestFactoryClassShouldApply() { + void requestFactoryClassShouldApply() { RestTemplate template = this.builder.requestFactory(SimpleClientHttpRequestFactory.class).build(); assertThat(template.getRequestFactory()).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test - public void requestFactoryPackagePrivateClassShouldApply() { + void requestFactoryPackagePrivateClassShouldApply() { RestTemplate template = this.builder.requestFactory(TestClientHttpRequestFactory.class).build(); assertThat(template.getRequestFactory()).isInstanceOf(TestClientHttpRequestFactory.class); } @Test - public void requestFactoryWhenSupplierIsNullShouldThrowException() { + void requestFactoryWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) .withMessageContaining("RequestFactory Supplier must not be null"); } @Test - public void requestFactoryShouldApply() { + void requestFactoryShouldApply() { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); RestTemplate template = this.builder.requestFactory(() -> requestFactory).build(); assertThat(template.getRequestFactory()).isSameAs(requestFactory); } @Test - public void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { + void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.uriTemplateHandler(null)) .withMessageContaining("UriTemplateHandler must not be null"); } @Test - public void uriTemplateHandlerShouldApply() { + void uriTemplateHandlerShouldApply() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).build(); assertThat(template.getUriTemplateHandler()).isSameAs(uriTemplateHandler); } @Test - public void errorHandlerWhenHandlerIsNullShouldThrowException() { + void errorHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.errorHandler(null)) .withMessageContaining("ErrorHandler must not be null"); } @Test - public void errorHandlerShouldApply() { + void errorHandlerShouldApply() { ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); RestTemplate template = this.builder.errorHandler(errorHandler).build(); assertThat(template.getErrorHandler()).isSameAs(errorHandler); } @Test - public void basicAuthenticationShouldApply() { + void basicAuthenticationShouldApply() { RestTemplate template = this.builder.basicAuthentication("spring", "boot", StandardCharsets.UTF_8).build(); ClientHttpRequestFactory requestFactory = template.getRequestFactory(); Object authentication = ReflectionTestUtils.getField(requestFactory, "authentication"); @@ -307,27 +307,27 @@ public class RestTemplateBuilderTests { } @Test - public void customizersWhenCustomizersAreNullShouldThrowException() { + void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((RestTemplateCustomizer[]) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test - public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { + void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((Set) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test - public void customizersShouldApply() { + void customizersShouldApply() { RestTemplateCustomizer customizer = mock(RestTemplateCustomizer.class); RestTemplate template = this.builder.customizers(customizer).build(); verify(customizer).customize(template); } @Test - public void customizersShouldBeAppliedLast() { + void customizersShouldBeAppliedLast() { RestTemplate template = spy(new RestTemplate()); this.builder.additionalCustomizers( (restTemplate) -> verify(restTemplate).setRequestFactory(any(ClientHttpRequestFactory.class))); @@ -335,7 +335,7 @@ public class RestTemplateBuilderTests { } @Test - public void customizersShouldReplaceExisting() { + void customizersShouldReplaceExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); RestTemplate template = this.builder.customizers(customizer1).customizers(Collections.singleton(customizer2)) @@ -345,21 +345,21 @@ public class RestTemplateBuilderTests { } @Test - public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test - public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test - public void additionalCustomizersShouldAddToExisting() { + void additionalCustomizersShouldAddToExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); RestTemplate template = this.builder.customizers(customizer1).additionalCustomizers(customizer2).build(); @@ -369,7 +369,7 @@ public class RestTemplateBuilderTests { } @Test - public void customizerShouldBeAppliedAtTheEnd() { + void customizerShouldBeAppliedAtTheEnd() { ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); this.builder.interceptors(this.interceptor).messageConverters(this.messageConverter) @@ -389,40 +389,40 @@ public class RestTemplateBuilderTests { } @Test - public void buildShouldReturnRestTemplate() { + void buildShouldReturnRestTemplate() { RestTemplate template = this.builder.build(); assertThat(template.getClass()).isEqualTo(RestTemplate.class); } @Test - public void buildClassShouldReturnClassInstance() { + void buildClassShouldReturnClassInstance() { RestTemplateSubclass template = this.builder.build(RestTemplateSubclass.class); assertThat(template.getClass()).isEqualTo(RestTemplateSubclass.class); } @Test - public void configureShouldApply() { + void configureShouldApply() { RestTemplate template = new RestTemplate(); this.builder.configure(template); assertThat(template.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test - public void connectTimeoutCanBeNullToUseDefault() { + void connectTimeoutCanBeNullToUseDefault() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(null).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", -1); } @Test - public void readTimeoutCanBeNullToUseDefault() { + void readTimeoutCanBeNullToUseDefault() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setReadTimeout(null).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", -1); } @Test - public void connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { + void connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder .requestFactory(HttpComponentsClientHttpRequestFactory.class).setConnectTimeout(Duration.ofMillis(1234)) .build().getRequestFactory(); @@ -431,7 +431,7 @@ public class RestTemplateBuilderTests { } @Test - public void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { + void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder .requestFactory(HttpComponentsClientHttpRequestFactory.class).setReadTimeout(Duration.ofMillis(1234)) .build().getRequestFactory(); @@ -440,7 +440,7 @@ public class RestTemplateBuilderTests { } @Test - public void bufferRequestBodyCanBeConfiguredOnHttpComponentsRequestFactory() { + void bufferRequestBodyCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder .requestFactory(HttpComponentsClientHttpRequestFactory.class).setBufferRequestBody(false).build() .getRequestFactory(); @@ -454,21 +454,21 @@ public class RestTemplateBuilderTests { } @Test - public void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { + void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 1234); } @Test - public void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { + void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 1234); } @Test - public void bufferRequestBodyCanBeConfiguredOnSimpleRequestFactory() { + void bufferRequestBodyCanBeConfiguredOnSimpleRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setBufferRequestBody(false).build().getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("bufferRequestBody", false); @@ -480,7 +480,7 @@ public class RestTemplateBuilderTests { } @Test - public void connectTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { + void connectTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setConnectTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat( @@ -489,7 +489,7 @@ public class RestTemplateBuilderTests { } @Test - public void readTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { + void readTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setReadTimeout(Duration.ofMillis(1234)).build().getRequestFactory(); assertThat(ReflectionTestUtils.getField(ReflectionTestUtils.getField(requestFactory, "client"), "readTimeout")) @@ -497,7 +497,7 @@ public class RestTemplateBuilderTests { } @Test - public void bufferRequestBodyCanNotBeConfiguredOnOkHttp3RequestFactory() { + void bufferRequestBodyCanNotBeConfiguredOnOkHttp3RequestFactory() { assertThatIllegalStateException() .isThrownBy(() -> this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setBufferRequestBody(false).build().getRequestFactory()) @@ -505,7 +505,7 @@ public class RestTemplateBuilderTests { } @Test - public void connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { + void connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setConnectTimeout(Duration.ofMillis(1234)).build(); @@ -513,7 +513,7 @@ public class RestTemplateBuilderTests { } @Test - public void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { + void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setReadTimeout(Duration.ofMillis(1234)).build(); @@ -521,7 +521,7 @@ public class RestTemplateBuilderTests { } @Test - public void bufferRequestBodyCanBeConfiguredOnAWrappedRequestFactory() { + void bufferRequestBodyCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .setBufferRequestBody(false).build(); @@ -534,7 +534,7 @@ public class RestTemplateBuilderTests { } @Test - public void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { + void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); RestTemplate template = this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) .build(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index 52d92fc6e6b..8ee52a3f6c5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -21,8 +21,8 @@ import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -41,7 +41,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class RootUriTemplateHandlerTests { +class RootUriTemplateHandlerTests { private URI uri; @@ -50,7 +50,7 @@ public class RootUriTemplateHandlerTests { public UriTemplateHandler handler; - @Before + @BeforeEach @SuppressWarnings("unchecked") public void setup() throws URISyntaxException { MockitoAnnotations.initMocks(this); @@ -61,19 +61,19 @@ public class RootUriTemplateHandlerTests { } @Test - public void createWithNullRootUriShouldThrowException() { + void createWithNullRootUriShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler((String) null)) .withMessageContaining("RootUri must not be null"); } @Test - public void createWithNullHandlerShouldThrowException() { + void createWithNullHandlerShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler("https://example.com", null)) .withMessageContaining("Handler must not be null"); } @Test - public void expandMapVariablesShouldPrefixRoot() { + void expandMapVariablesShouldPrefixRoot() { HashMap uriVariables = new HashMap<>(); URI expanded = this.handler.expand("/hello", uriVariables); verify(this.delegate).expand("https://example.com/hello", uriVariables); @@ -81,7 +81,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void expandMapVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { + void expandMapVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { HashMap uriVariables = new HashMap<>(); URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); @@ -89,7 +89,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void expandArrayVariablesShouldPrefixRoot() { + void expandArrayVariablesShouldPrefixRoot() { Object[] uriVariables = new Object[0]; URI expanded = this.handler.expand("/hello", uriVariables); verify(this.delegate).expand("https://example.com/hello", uriVariables); @@ -97,7 +97,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void expandArrayVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { + void expandArrayVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { Object[] uriVariables = new Object[0]; URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); @@ -105,7 +105,7 @@ public class RootUriTemplateHandlerTests { } @Test - public void applyShouldWrapExistingTemplate() { + void applyShouldWrapExistingTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setUriTemplateHandler(this.delegate); this.handler = RootUriTemplateHandler.addTo(restTemplate, "https://example.com"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java index d78a2e3a811..727a6660dc1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/context/WebServerPortFileWriterTest.java @@ -21,11 +21,10 @@ import java.util.HashSet; import java.util.Locale; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.web.server.WebServer; import org.springframework.util.StringUtils; @@ -42,28 +41,28 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class WebServerPortFileWriterTest { +class WebServerPortFileWriterTest { - @Rule - public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; - @Before - @After + @BeforeEach + @AfterEach public void reset() { System.clearProperty("PORTFILE"); } @Test - public void createPortFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void createPortFile() throws Exception { + File file = new File(this.tempDir, "port.file"); WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); assertThat(contentOf(file)).isEqualTo("8080"); } @Test - public void overridePortFileWithDefault() throws Exception { - System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath()); + void overridePortFileWithDefault() throws Exception { + System.setProperty("PORTFILE", new File(this.tempDir, "port.file").getAbsolutePath()); WebServerPortFileWriter listener = new WebServerPortFileWriter(); listener.onApplicationEvent(mockEvent("", 8080)); String content = contentOf(new File(System.getProperty("PORTFILE"))); @@ -71,9 +70,9 @@ public class WebServerPortFileWriterTest { } @Test - public void overridePortFileWithExplicitFile() throws Exception { - File file = this.temporaryFolder.newFile(); - System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath()); + void overridePortFileWithExplicitFile() throws Exception { + File file = new File(this.tempDir, "port.file"); + System.setProperty("PORTFILE", new File(this.tempDir, "override.file").getAbsolutePath()); WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); String content = contentOf(new File(System.getProperty("PORTFILE"))); @@ -81,8 +80,8 @@ public class WebServerPortFileWriterTest { } @Test - public void createManagementPortFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void createManagementPortFile() throws Exception { + File file = new File(this.tempDir, "port.file"); WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); listener.onApplicationEvent(mockEvent("management", 9090)); @@ -97,8 +96,8 @@ public class WebServerPortFileWriterTest { } @Test - public void createUpperCaseManagementPortFile() throws Exception { - File file = this.temporaryFolder.newFile(); + void createUpperCaseManagementPortFile() throws Exception { + File file = new File(this.tempDir, "port.file"); file = new File(file.getParentFile(), file.getName().toUpperCase(Locale.ENGLISH)); WebServerPortFileWriter listener = new WebServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("management", 9090)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java index 9c1ecd53c29..4317adb2817 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java @@ -22,7 +22,7 @@ import java.util.Arrays; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactoryTests; @@ -41,7 +41,7 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Madhura Bhave */ -public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { +class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected JettyReactiveWebServerFactory getFactory() { @@ -49,14 +49,14 @@ public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void setNullServerCustomizersShouldThrowException() { + void setNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setServerCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test - public void addNullServerCustomizersShouldThrowException() { + void addNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) @@ -64,7 +64,7 @@ public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void jettyCustomizersShouldBeInvoked() { + void jettyCustomizersShouldBeInvoked() { HttpHandler handler = mock(HttpHandler.class); JettyReactiveWebServerFactory factory = getFactory(); JettyServerCustomizer[] configurations = new JettyServerCustomizer[4]; @@ -79,7 +79,7 @@ public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void specificIPAddressNotReverseResolved() throws Exception { + void specificIPAddressNotReverseResolved() throws Exception { JettyReactiveWebServerFactory factory = getFactory(); InetAddress localhost = InetAddress.getLocalHost(); factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); @@ -90,14 +90,14 @@ public class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void useForwardedHeaders() { + void useForwardedHeaders() { JettyReactiveWebServerFactory factory = getFactory(); factory.setUseForwardHeaders(true); assertForwardHeaderIsUsed(factory); } @Test - public void useServerResources() throws Exception { + void useServerResources() throws Exception { JettyResourceFactory resourceFactory = new JettyResourceFactory(); resourceFactory.afterPropertiesSet(); JettyReactiveWebServerFactory factory = getFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index 098069f06fc..83ae74e836c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -41,7 +41,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.springframework.boot.web.server.PortInUseException; @@ -64,7 +64,7 @@ import static org.mockito.Mockito.mock; * @author Andy Wilkinson * @author Henri Kerola */ -public class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { +class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Override protected JettyServletWebServerFactory getFactory() { @@ -72,7 +72,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void jettyConfigurations() throws Exception { + void jettyConfigurations() throws Exception { JettyServletWebServerFactory factory = getFactory(); Configuration[] configurations = new Configuration[4]; Arrays.setAll(configurations, (i) -> mock(Configuration.class)); @@ -86,7 +86,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void jettyCustomizations() { + void jettyCustomizations() { JettyServletWebServerFactory factory = getFactory(); JettyServerCustomizer[] configurations = new JettyServerCustomizer[4]; Arrays.setAll(configurations, (i) -> mock(JettyServerCustomizer.class)); @@ -100,21 +100,21 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void sessionTimeout() { + void sessionTimeout() { JettyServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofSeconds(10)); assertTimeout(factory, 10); } @Test - public void sessionTimeoutInMins() { + void sessionTimeoutInMins() { JettyServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofMinutes(1)); assertTimeout(factory, 60); } @Test - public void sslCiphersConfiguration() { + void sslCiphersConfiguration() { Ssl ssl = new Ssl(); ssl.setKeyStore("src/test/resources/test.jks"); ssl.setKeyStorePassword("secret"); @@ -136,7 +136,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void stopCalledWithoutStart() { + void stopCalledWithoutStart() { JettyServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.stop(); @@ -154,7 +154,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void sslEnabledMultiProtocolsConfiguration() { + void sslEnabledMultiProtocolsConfiguration() { JettyServletWebServerFactory factory = getFactory(); factory.setSsl(getSslSettings("TLSv1.1", "TLSv1.2")); this.webServer = factory.getWebServer(); @@ -167,7 +167,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void sslEnabledProtocolsConfiguration() { + void sslEnabledProtocolsConfiguration() { JettyServletWebServerFactory factory = getFactory(); factory.setSsl(getSslSettings("TLSv1.1")); this.webServer = factory.getWebServer(); @@ -198,7 +198,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void wrappedHandlers() throws Exception { + void wrappedHandlers() throws Exception { JettyServletWebServerFactory factory = getFactory(); factory.setServerCustomizers(Collections.singletonList((server) -> { Handler handler = server.getHandler(); @@ -214,19 +214,19 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void basicSslClasspathKeyStore() throws Exception { + void basicSslClasspathKeyStore() throws Exception { testBasicSslWithKeyStore("classpath:test.jks"); } @Test - public void useForwardHeaders() throws Exception { + void useForwardHeaders() throws Exception { JettyServletWebServerFactory factory = getFactory(); factory.setUseForwardHeaders(true); assertForwardHeaderIsUsed(factory); } @Test - public void defaultThreadPool() { + void defaultThreadPool() { JettyServletWebServerFactory factory = getFactory(); factory.setThreadPool(null); assertThat(factory.getThreadPool()).isNull(); @@ -235,7 +235,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void customThreadPool() { + void customThreadPool() { JettyServletWebServerFactory factory = getFactory(); ThreadPool threadPool = mock(ThreadPool.class); factory.setThreadPool(threadPool); @@ -244,7 +244,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void startFailsWhenThreadPoolIsTooSmall() { + void startFailsWhenThreadPoolIsTooSmall() { JettyServletWebServerFactory factory = getFactory(); factory.addServerCustomizers((server) -> { QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class); @@ -256,7 +256,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void specificIPAddressNotReverseResolved() throws Exception { + void specificIPAddressNotReverseResolved() throws Exception { JettyServletWebServerFactory factory = getFactory(); InetAddress localhost = InetAddress.getLocalHost(); factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); @@ -267,7 +267,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void specificIPAddressWithSslIsNotReverseResolved() throws Exception { + void specificIPAddressWithSslIsNotReverseResolved() throws Exception { JettyServletWebServerFactory factory = getFactory(); InetAddress localhost = InetAddress.getLocalHost(); factory.setAddress(InetAddress.getByAddress(localhost.getAddress())); @@ -283,7 +283,7 @@ public class JettyServletWebServerFactoryTests extends AbstractServletWebServerF } @Test - public void faultyListenerCausesStartFailure() throws Exception { + void faultyListenerCausesStartFailure() throws Exception { JettyServletWebServerFactory factory = getFactory(); factory.addServerCustomizers((JettyServerCustomizer) (server) -> { Collection contexts = server.getBeans(WebAppContext.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java index 71b062d69a8..afac74efbbe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java @@ -27,7 +27,7 @@ import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.server.Http2; import org.springframework.boot.web.server.Ssl; @@ -41,11 +41,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Andy Wilkinson */ -public class SslServerCustomizerTests { +class SslServerCustomizerTests { @Test @SuppressWarnings("rawtypes") - public void whenHttp2IsNotEnabledServerConnectorHasSslAndHttpConnectionFactories() { + void whenHttp2IsNotEnabledServerConnectorHasSslAndHttpConnectionFactories() { Server server = createCustomizedServer(); assertThat(server.getConnectors()).hasSize(1); List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); @@ -55,7 +55,7 @@ public class SslServerCustomizerTests { @Test @SuppressWarnings("rawtypes") - public void whenHttp2IsEnabledServerConnectorsHasSslAlpnH2AndHttpConnectionFactories() { + void whenHttp2IsEnabledServerConnectorsHasSslAlpnH2AndHttpConnectionFactories() { Http2 http2 = new Http2(); http2.setEnabled(true); Server server = createCustomizedServer(http2); @@ -67,7 +67,7 @@ public class SslServerCustomizerTests { } @Test - public void alpnConnectionFactoryHasNullDefaultProtocolToAllowNegotiationToHttp11() { + void alpnConnectionFactoryHasNullDefaultProtocolToAllowNegotiationToHttp11() { Http2 http2 = new Http2(); http2.setEnabled(true); Server server = createCustomizedServer(http2); @@ -77,7 +77,7 @@ public class SslServerCustomizerTests { } @Test - public void configureSslWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { + void configureSslWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); assertThatExceptionOfType(Exception.class) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java index 641a75bfb63..681b0911bdb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.embedded.netty; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import reactor.netty.http.server.HttpServer; @@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { +class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected NettyReactiveWebServerFactory getFactory() { @@ -46,7 +46,7 @@ public class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void exceptionIsThrownWhenPortIsAlreadyInUse() { + void exceptionIsThrownWhenPortIsAlreadyInUse() { AbstractReactiveWebServerFactory factory = getFactory(); factory.setPort(0); this.webServer = factory.getWebServer(new EchoHandler()); @@ -61,7 +61,7 @@ public class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void nettyCustomizers() { + void nettyCustomizers() { NettyReactiveWebServerFactory factory = getFactory(); NettyServerCustomizer[] customizers = new NettyServerCustomizer[2]; for (int i = 0; i < customizers.length; i++) { @@ -77,7 +77,7 @@ public class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServe } @Test - public void useForwardedHeaders() { + void useForwardedHeaders() { NettyReactiveWebServerFactory factory = getFactory(); factory.setUseForwardHeaders(true); assertForwardHeaderIsUsed(factory); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java index f27e7bc9677..ea563b7f953 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.embedded.netty; import java.security.NoSuchProviderException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerException; @@ -31,10 +31,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Andy Wilkinson * @author Raheela Aslam */ -public class SslServerCustomizerTests { +class SslServerCustomizerTests { @Test - public void keyStoreProviderIsUsedWhenCreatingKeyStore() throws Exception { + void keyStoreProviderIsUsedWhenCreatingKeyStore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -46,7 +46,7 @@ public class SslServerCustomizerTests { } @Test - public void trustStoreProviderIsUsedWhenCreatingTrustStore() throws Exception { + void trustStoreProviderIsUsedWhenCreatingTrustStore() throws Exception { Ssl ssl = new Ssl(); ssl.setTrustStorePassword("password"); ssl.setTrustStore("src/test/resources/test.jks"); @@ -58,7 +58,7 @@ public class SslServerCustomizerTests { } @Test - public void getKeyManagerFactoryWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { + void getKeyManagerFactoryWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java index b457972555a..2dc0ba2bd9a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/CompressionConnectorCustomizerTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.web.embedded.tomcat; import org.apache.catalina.connector.Connector; import org.apache.coyote.http11.AbstractHttp11Protocol; import org.apache.coyote.http2.Http2Protocol; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.server.Compression; import org.springframework.util.unit.DataSize; @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Rudy Adams */ -public class CompressionConnectorCustomizerTests { +class CompressionConnectorCustomizerTests { private static final int MIN_SIZE = 100; @@ -42,7 +42,7 @@ public class CompressionConnectorCustomizerTests { private Compression compression; - @Before + @BeforeEach public void setup() { this.compression = new Compression(); this.compression.setEnabled(true); @@ -52,7 +52,7 @@ public class CompressionConnectorCustomizerTests { } @Test - public void shouldCustomizeCompressionForHttp1AndHttp2Protocol() { + void shouldCustomizeCompressionForHttp1AndHttp2Protocol() { CompressionConnectorCustomizer compressionConnectorCustomizer = new CompressionConnectorCustomizer( this.compression); Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java index 35c5fc91ecf..bfa1f9101ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java @@ -29,12 +29,13 @@ import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.apache.tomcat.util.net.SSLHostConfig; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.SslStoreProvider; import org.springframework.boot.web.server.WebServerException; @@ -52,16 +53,14 @@ import static org.mockito.Mockito.mock; * * @author Brian Clozel */ -public class SslConnectorCustomizerTests { +@ExtendWith(OutputCaptureExtension.class) +class SslConnectorCustomizerTests { private Tomcat tomcat; private Connector connector; - @Rule - public OutputCapture output = new OutputCapture(); - - @Before + @BeforeEach public void setup() { this.tomcat = new Tomcat(); this.connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); @@ -69,7 +68,7 @@ public class SslConnectorCustomizerTests { this.tomcat.setConnector(this.connector); } - @After + @AfterEach public void stop() throws Exception { System.clearProperty("javax.net.ssl.trustStorePassword"); ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); @@ -78,7 +77,7 @@ public class SslConnectorCustomizerTests { } @Test - public void sslCiphersConfiguration() throws Exception { + void sslCiphersConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyStore("test.jks"); ssl.setKeyStorePassword("secret"); @@ -92,7 +91,7 @@ public class SslConnectorCustomizerTests { } @Test - public void sslEnabledMultipleProtocolsConfiguration() throws Exception { + void sslEnabledMultipleProtocolsConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -108,7 +107,7 @@ public class SslConnectorCustomizerTests { } @Test - public void sslEnabledProtocolsConfiguration() throws Exception { + void sslEnabledProtocolsConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -124,7 +123,7 @@ public class SslConnectorCustomizerTests { } @Test - public void customizeWhenSslStoreProviderProvidesOnlyKeyStoreShouldUseDefaultTruststore() throws Exception { + void customizeWhenSslStoreProviderProvidesOnlyKeyStoreShouldUseDefaultTruststore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setTrustStore("src/test/resources/test.jks"); @@ -142,7 +141,7 @@ public class SslConnectorCustomizerTests { } @Test - public void customizeWhenSslStoreProviderProvidesOnlyTrustStoreShouldUseDefaultKeystore() throws Exception { + void customizeWhenSslStoreProviderProvidesOnlyTrustStoreShouldUseDefaultKeystore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -161,7 +160,8 @@ public class SslConnectorCustomizerTests { } @Test - public void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl() throws Exception { + void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl(CapturedOutput capturedOutput) + throws Exception { System.setProperty("javax.net.ssl.trustStorePassword", "trustStoreSecret"); Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); @@ -174,11 +174,11 @@ public class SslConnectorCustomizerTests { customizer.customize(connector); this.tomcat.start(); assertThat(connector.getState()).isEqualTo(LifecycleState.STARTED); - assertThat(this.output.toString()).doesNotContain("Password verification failed"); + assertThat(capturedOutput).doesNotContain("Password verification failed"); } @Test - public void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { + void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { assertThatExceptionOfType(WebServerException.class) .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) .withMessageContaining("Could not load key store 'null'"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java index af493468398..86b8b10620f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java @@ -30,9 +30,8 @@ import org.apache.catalina.core.StandardContext; import org.apache.catalina.loader.ParallelWebappClassLoader; import org.apache.catalina.webresources.StandardRoot; import org.apache.catalina.webresources.WarResourceSet; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.CollectionUtils; @@ -43,20 +42,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class TomcatEmbeddedWebappClassLoaderTests { +class TomcatEmbeddedWebappClassLoaderTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void getResourceFindsResourceFromParentClassLoader() throws Exception { + void getResourceFindsResourceFromParentClassLoader() throws Exception { File war = createWar(); withWebappClassLoader(war, (classLoader) -> assertThat(classLoader.getResource("test.txt")) .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); } @Test - public void getResourcesOnlyFindsResourcesFromParentClassLoader() throws Exception { + void getResourcesOnlyFindsResourcesFromParentClassLoader() throws Exception { File warFile = createWar(); withWebappClassLoader(warFile, (classLoader) -> { List urls = new ArrayList<>(); @@ -85,7 +84,7 @@ public class TomcatEmbeddedWebappClassLoaderTests { } private File createWar() throws IOException { - File warFile = this.temp.newFile("test.war"); + File warFile = new File(this.tempDir, "test.war"); try (JarOutputStream warOut = new JarOutputStream(new FileOutputStream(warFile))) { createEntries(warOut, "WEB-INF/", "WEB-INF/classes/", "WEB-INF/classes/test.txt"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java index 1f3ad0006fe..f207050aedf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java @@ -28,7 +28,7 @@ import org.apache.catalina.startup.Tomcat; import org.apache.catalina.valves.RemoteIpValve; import org.apache.coyote.ProtocolHandler; import org.apache.coyote.http11.AbstractHttp11Protocol; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Madhura Bhave */ -public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { +class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { @Override protected TomcatReactiveWebServerFactory getFactory() { @@ -56,7 +56,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void tomcatCustomizers() { + void tomcatCustomizers() { TomcatReactiveWebServerFactory factory = getFactory(); TomcatContextCustomizer[] customizers = new TomcatContextCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatContextCustomizer.class)); @@ -70,7 +70,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void contextIsAddedToHostBeforeCustomizersAreCalled() { + void contextIsAddedToHostBeforeCustomizersAreCalled() { TomcatReactiveWebServerFactory factory = getFactory(); TomcatContextCustomizer customizer = mock(TomcatContextCustomizer.class); factory.addContextCustomizers(customizer); @@ -81,7 +81,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void defaultTomcatListeners() { + void defaultTomcatListeners() { TomcatReactiveWebServerFactory factory = getFactory(); if (AprLifecycleListener.isAprAvailable()) { assertThat(factory.getContextLifecycleListeners()).hasSize(1).first() @@ -93,7 +93,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void tomcatListeners() { + void tomcatListeners() { TomcatReactiveWebServerFactory factory = getFactory(); LifecycleListener[] listeners = new LifecycleListener[4]; Arrays.setAll(listeners, (i) -> mock(LifecycleListener.class)); @@ -107,14 +107,14 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void setNullConnectorCustomizersShouldThrowException() { + void setNullConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test - public void addNullAddConnectorCustomizersShouldThrowException() { + void addNullAddConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) @@ -122,14 +122,14 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void setNullProtocolHandlerCustomizersShouldThrowException() { + void setNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test - public void addNullProtocolHandlerCustomizersShouldThrowException() { + void addNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) @@ -137,7 +137,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void tomcatConnectorCustomizersShouldBeInvoked() { + void tomcatConnectorCustomizersShouldBeInvoked() { TomcatReactiveWebServerFactory factory = getFactory(); HttpHandler handler = mock(HttpHandler.class); TomcatConnectorCustomizer[] customizers = new TomcatConnectorCustomizer[4]; @@ -153,7 +153,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void tomcatProtocolHandlerCustomizersShouldBeInvoked() { + void tomcatProtocolHandlerCustomizersShouldBeInvoked() { TomcatReactiveWebServerFactory factory = getFactory(); HttpHandler handler = mock(HttpHandler.class); TomcatProtocolHandlerCustomizer>[] customizers = new TomcatProtocolHandlerCustomizer[4]; @@ -168,7 +168,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void useForwardedHeaders() { + void useForwardedHeaders() { TomcatReactiveWebServerFactory factory = getFactory(); RemoteIpValve valve = new RemoteIpValve(); valve.setProtocolHeader("X-Forwarded-Proto"); @@ -177,7 +177,7 @@ public class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServ } @Test - public void referenceClearingIsDisabled() { + void referenceClearingIsDisabled() { TomcatReactiveWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(mock(HttpHandler.class)); this.webServer.start(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index c064b8e244f..8887e1c6c34 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -60,13 +60,12 @@ import org.apache.coyote.http11.AbstractHttp11Protocol; import org.apache.jasper.servlet.JspServlet; import org.apache.tomcat.JarScanFilter; import org.apache.tomcat.JarScanType; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; import org.springframework.boot.web.server.WebServerException; import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory; import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests; @@ -97,17 +96,14 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Stephane Nicoll */ -public class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { - - @Rule - public OutputCapture outputCapture = new OutputCapture(); +class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Override protected TomcatServletWebServerFactory getFactory() { return new TomcatServletWebServerFactory(0); } - @After + @AfterEach public void restoreTccl() { ReflectionTestUtils.setField(TomcatURLStreamHandlerFactory.class, "instance", null); ReflectionTestUtils.setField(URL.class, "factory", null); @@ -116,7 +112,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer // JMX MBean names clash if you get more than one Engine with the same name... @Test - public void tomcatEngineNames() { + void tomcatEngineNames() { TomcatServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(); factory.setPort(0); @@ -129,7 +125,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void defaultTomcatListeners() { + void defaultTomcatListeners() { TomcatServletWebServerFactory factory = getFactory(); if (AprLifecycleListener.isAprAvailable()) { assertThat(factory.getContextLifecycleListeners()).hasSize(1).first() @@ -141,7 +137,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tomcatListeners() { + void tomcatListeners() { TomcatServletWebServerFactory factory = getFactory(); LifecycleListener[] listeners = new LifecycleListener[4]; Arrays.setAll(listeners, (i) -> mock(LifecycleListener.class)); @@ -155,7 +151,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tomcatCustomizers() { + void tomcatCustomizers() { TomcatServletWebServerFactory factory = getFactory(); TomcatContextCustomizer[] customizers = new TomcatContextCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatContextCustomizer.class)); @@ -169,7 +165,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void contextIsAddedToHostBeforeCustomizersAreCalled() { + void contextIsAddedToHostBeforeCustomizersAreCalled() { TomcatServletWebServerFactory factory = getFactory(); TomcatContextCustomizer customizer = mock(TomcatContextCustomizer.class); factory.addContextCustomizers(customizer); @@ -180,7 +176,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tomcatConnectorCustomizers() { + void tomcatConnectorCustomizers() { TomcatServletWebServerFactory factory = getFactory(); TomcatConnectorCustomizer[] customizers = new TomcatConnectorCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatConnectorCustomizer.class)); @@ -195,7 +191,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void tomcatProtocolHandlerCustomizersShouldBeInvoked() { + void tomcatProtocolHandlerCustomizersShouldBeInvoked() { TomcatServletWebServerFactory factory = getFactory(); TomcatProtocolHandlerCustomizer>[] customizers = new TomcatProtocolHandlerCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(TomcatProtocolHandlerCustomizer.class)); @@ -209,7 +205,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tomcatProtocolHandlerCanBeCustomized() { + void tomcatProtocolHandlerCanBeCustomized() { TomcatServletWebServerFactory factory = getFactory(); TomcatProtocolHandlerCustomizer> customizer = (protocolHandler) -> protocolHandler .setProcessorCache(250); @@ -221,7 +217,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tomcatAdditionalConnectors() { + void tomcatAdditionalConnectors() { TomcatServletWebServerFactory factory = getFactory(); Connector[] connectors = new Connector[4]; Arrays.setAll(connectors, (i) -> new Connector()); @@ -232,35 +228,35 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void addNullAdditionalConnectorThrows() { + void addNullAdditionalConnectorThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) .withMessageContaining("Connectors must not be null"); } @Test - public void sessionTimeout() { + void sessionTimeout() { TomcatServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofSeconds(10)); assertTimeout(factory, 1); } @Test - public void sessionTimeoutInMins() { + void sessionTimeoutInMins() { TomcatServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofMinutes(1)); assertTimeout(factory, 1); } @Test - public void noSessionTimeout() { + void noSessionTimeout() { TomcatServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(null); assertTimeout(factory, -1); } @Test - public void valve() { + void valve() { TomcatServletWebServerFactory factory = getFactory(); Valve valve = mock(Valve.class); factory.addContextValves(valve); @@ -269,14 +265,14 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void setNullTomcatContextCustomizersThrows() { + void setNullTomcatContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatContextCustomizers(null)) .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test - public void addNullContextCustomizersThrows() { + void addNullContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) @@ -284,14 +280,14 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void setNullTomcatConnectorCustomizersThrows() { + void setNullTomcatConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test - public void addNullConnectorCustomizersThrows() { + void addNullConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) @@ -299,14 +295,14 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void setNullTomcatProtocolHandlerCustomizersThrows() { + void setNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test - public void addNullTomcatProtocolHandlerCustomizersThrows() { + void addNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) @@ -314,7 +310,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void uriEncoding() { + void uriEncoding() { TomcatServletWebServerFactory factory = getFactory(); factory.setUriEncoding(StandardCharsets.US_ASCII); Tomcat tomcat = getTomcat(factory); @@ -323,7 +319,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void defaultUriEncoding() { + void defaultUriEncoding() { TomcatServletWebServerFactory factory = getFactory(); Tomcat tomcat = getTomcat(factory); Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; @@ -331,7 +327,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void primaryConnectorPortClashThrowsWebServerException() throws IOException { + void primaryConnectorPortClashThrowsWebServerException() throws IOException { doWithBlockedPort((port) -> { TomcatServletWebServerFactory factory = getFactory(); factory.setPort(port); @@ -343,14 +339,13 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void startupFailureDoesNotResultInUnstoppedThreadsBeingReported() throws IOException { + void startupFailureDoesNotResultInUnstoppedThreadsBeingReported(CapturedOutput capturedOutput) throws IOException { super.portClashOfPrimaryConnectorResultsInPortInUseException(); - String string = this.outputCapture.toString(); - assertThat(string).doesNotContain("appears to have started a thread named [main]"); + assertThat(capturedOutput).doesNotContain("appears to have started a thread named [main]"); } @Test - public void stopCalledWithoutStart() { + void stopCalledWithoutStart() { TomcatServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.stop(); @@ -366,19 +361,18 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void useForwardHeaders() throws Exception { + void useForwardHeaders() throws Exception { TomcatServletWebServerFactory factory = getFactory(); factory.addContextValves(new RemoteIpValve()); assertForwardHeaderIsUsed(factory); } @Test - public void disableDoesNotSaveSessionFiles() throws Exception { - File baseDir = this.temporaryFolder.newFolder(); + void disableDoesNotSaveSessionFiles() throws Exception { TomcatServletWebServerFactory factory = getFactory(); // If baseDir is not set SESSIONS.ser is written to a different temp directory // each time. By setting it we can really ensure that data isn't saved - factory.setBaseDirectory(baseDir); + factory.setBaseDirectory(this.tempDir); this.webServer = factory.getWebServer(sessionServletRegistration()); this.webServer.start(); String s1 = getResponse(getLocalUrl("/session")); @@ -393,7 +387,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void jndiLookupsCanBePerformedDuringApplicationContextRefresh() throws NamingException { + void jndiLookupsCanBePerformedDuringApplicationContextRefresh() throws NamingException { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0) { @@ -416,7 +410,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void defaultLocaleCharsetMappingsAreOverridden() { + void defaultLocaleCharsetMappingsAreOverridden() { TomcatServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(); // override defaults, see org.apache.catalina.util.CharsetMapperDefault.properties @@ -425,7 +419,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void sessionIdGeneratorIsConfiguredWithAttributesFromTheManager() { + void sessionIdGeneratorIsConfiguredWithAttributesFromTheManager() { System.setProperty("jvmRoute", "test"); try { TomcatServletWebServerFactory factory = getFactory(); @@ -443,7 +437,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void tldSkipPatternsShouldBeAppliedToContextJarScanner() { + void tldSkipPatternsShouldBeAppliedToContextJarScanner() { TomcatServletWebServerFactory factory = getFactory(); factory.addTldSkipPatterns("foo.jar", "bar.jar"); this.webServer = factory.getWebServer(); @@ -457,7 +451,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void customTomcatHttpOnlyCookie() { + void customTomcatHttpOnlyCookie() { TomcatServletWebServerFactory factory = getFactory(); factory.getSession().getCookie().setHttpOnly(false); this.webServer = factory.getWebServer(); @@ -468,7 +462,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsTrue() { + void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsTrue() { TomcatServletWebServerFactory factory = getFactory(); factory.addContextCustomizers((context) -> { if (context instanceof StandardContext) { @@ -481,7 +475,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsFalse() { + void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsFalse() { TomcatServletWebServerFactory factory = getFactory(); factory.addContextCustomizers((context) -> { if (context instanceof StandardContext) { @@ -494,7 +488,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void referenceClearingIsDisabled() { + void referenceClearingIsDisabled() { TomcatServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(); this.webServer.start(); @@ -506,7 +500,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException { + void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); AtomicReference servletContextReference = new AtomicReference<>(); factory.addInitializers((servletContext) -> { @@ -539,7 +533,7 @@ public class TomcatServletWebServerFactoryTests extends AbstractServletWebServer } @Test - public void exceptionThrownOnContextListenerDestroysServer() { + void exceptionThrownOnContextListenerDestroysServer() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0) { @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java index 71e8ef55714..6db83a32de9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistenceTests.java @@ -23,10 +23,9 @@ import java.util.LinkedHashMap; import java.util.Map; import io.undertow.servlet.api.SessionPersistenceManager.PersistentSession; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -35,10 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class FileSessionPersistenceTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class FileSessionPersistenceTests { private File dir; @@ -48,20 +44,21 @@ public class FileSessionPersistenceTests { private Date expiration = new Date(System.currentTimeMillis() + 10000); - @Before - public void setup() throws IOException { - this.dir = this.temp.newFolder(); + @BeforeEach + public void setup(@TempDir File tempDir) throws IOException { + this.dir = tempDir; + this.dir.mkdir(); this.persistence = new FileSessionPersistence(this.dir); } @Test - public void loadsNullForMissingFile() { + void loadsNullForMissingFile() { Map attributes = this.persistence.loadSessionAttributes("test", this.classLoader); assertThat(attributes).isNull(); } @Test - public void persistAndLoad() { + void persistAndLoad() { Map sessionData = new LinkedHashMap<>(); Map data = new LinkedHashMap<>(); data.put("spring", "boot"); @@ -75,7 +72,7 @@ public class FileSessionPersistenceTests { } @Test - public void dontRestoreExpired() { + void dontRestoreExpired() { Date expired = new Date(System.currentTimeMillis() - 1000); Map sessionData = new LinkedHashMap<>(); Map data = new LinkedHashMap<>(); @@ -89,7 +86,7 @@ public class FileSessionPersistenceTests { } @Test - public void deleteFileOnClear() { + void deleteFileOnClear() { File sessionFile = new File(this.dir, "test.session"); Map sessionData = new LinkedHashMap<>(); this.persistence.persistSessions("test", sessionData); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/JarResourceManagerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/JarResourceManagerTests.java index 5805e13f518..0d91fd07c87 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/JarResourceManagerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/JarResourceManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,9 @@ import java.util.zip.ZipEntry; import io.undertow.server.handlers.resource.Resource; import io.undertow.server.handlers.resource.ResourceManager; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -36,16 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class JarResourceManagerTests { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); +class JarResourceManagerTests { private ResourceManager resourceManager; - @Before - public void createJar() throws IOException { - File jar = this.temp.newFile(); + @BeforeEach + public void createJar(@TempDir File tempDir) throws IOException { + File jar = new File(tempDir, "test.jar"); JarOutputStream out = new JarOutputStream(new FileOutputStream(jar)); out.putNextEntry(new ZipEntry("hello.txt")); out.write("hello".getBytes()); @@ -54,21 +50,21 @@ public class JarResourceManagerTests { } @Test - public void emptyPathIsHandledCorrectly() throws IOException { + void emptyPathIsHandledCorrectly() throws IOException { Resource resource = this.resourceManager.getResource(""); assertThat(resource).isNotNull(); assertThat(resource.isDirectory()).isTrue(); } @Test - public void rootPathIsHandledCorrectly() throws IOException { + void rootPathIsHandledCorrectly() throws IOException { Resource resource = this.resourceManager.getResource("/"); assertThat(resource).isNotNull(); assertThat(resource.isDirectory()).isTrue(); } @Test - public void resourceIsFoundInJarFile() throws IOException { + void resourceIsFoundInJarFile() throws IOException { Resource resource = this.resourceManager.getResource("/hello.txt"); assertThat(resource).isNotNull(); assertThat(resource.isDirectory()).isFalse(); @@ -76,7 +72,7 @@ public class JarResourceManagerTests { } @Test - public void resourceIsFoundInJarFileWithoutLeadingSlash() throws IOException { + void resourceIsFoundInJarFileWithoutLeadingSlash() throws IOException { Resource resource = this.resourceManager.getResource("hello.txt"); assertThat(resource).isNotNull(); assertThat(resource.isDirectory()).isFalse(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java index 77e9bab1373..a7ae5fa564e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java @@ -21,7 +21,7 @@ import java.security.NoSuchProviderException; import javax.net.ssl.KeyManager; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerException; @@ -36,10 +36,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Brian Clozel * @author Raheela Aslam */ -public class SslBuilderCustomizerTests { +class SslBuilderCustomizerTests { @Test - public void getKeyManagersWhenAliasIsNullShouldNotDecorate() throws Exception { + void getKeyManagersWhenAliasIsNullShouldNotDecorate() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -51,7 +51,7 @@ public class SslBuilderCustomizerTests { } @Test - public void keyStoreProviderIsUsedWhenCreatingKeyStore() throws Exception { + void keyStoreProviderIsUsedWhenCreatingKeyStore() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("src/test/resources/test.jks"); @@ -64,7 +64,7 @@ public class SslBuilderCustomizerTests { } @Test - public void trustStoreProviderIsUsedWhenCreatingTrustStore() throws Exception { + void trustStoreProviderIsUsedWhenCreatingTrustStore() throws Exception { Ssl ssl = new Ssl(); ssl.setTrustStorePassword("password"); ssl.setTrustStore("src/test/resources/test.jks"); @@ -77,7 +77,7 @@ public class SslBuilderCustomizerTests { } @Test - public void getKeyManagersWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { + void getKeyManagersWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() throws Exception { Ssl ssl = new Ssl(); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java index 29893894340..0a3ec122d87 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java @@ -23,9 +23,8 @@ import java.time.Duration; import java.util.Arrays; import io.undertow.Undertow; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.InOrder; import reactor.core.publisher.Mono; @@ -47,10 +46,10 @@ import static org.mockito.Mockito.mock; * @author Brian Clozel * @author Madhura Bhave */ -public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { +class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactoryTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Override protected UndertowReactiveWebServerFactory getFactory() { @@ -58,14 +57,14 @@ public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebSe } @Test - public void setNullBuilderCustomizersShouldThrowException() { + void setNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test - public void addNullBuilderCustomizersShouldThrowException() { + void addNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) @@ -73,7 +72,7 @@ public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebSe } @Test - public void builderCustomizersShouldBeInvoked() { + void builderCustomizersShouldBeInvoked() { UndertowReactiveWebServerFactory factory = getFactory(); HttpHandler handler = mock(HttpHandler.class); UndertowBuilderCustomizer[] customizers = new UndertowBuilderCustomizer[4]; @@ -88,19 +87,19 @@ public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebSe } @Test - public void useForwardedHeaders() { + void useForwardedHeaders() { UndertowReactiveWebServerFactory factory = getFactory(); factory.setUseForwardHeaders(true); assertForwardHeaderIsUsed(factory); } @Test - public void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { + void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { testAccessLog(null, null, "access_log.log"); } @Test - public void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { + void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { testAccessLog("my_access.", "logz", "my_access.logz"); } @@ -110,7 +109,7 @@ public class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebSe factory.setAccessLogEnabled(true); factory.setAccessLogPrefix(prefix); factory.setAccessLogSuffix(suffix); - File accessLogDirectory = this.temporaryFolder.getRoot(); + File accessLogDirectory = this.tempDir; factory.setAccessLogDirectory(accessLogDirectory); assertThat(accessLogDirectory.listFiles()).isEmpty(); this.webServer = factory.getWebServer(new EchoHandler()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index 951db0f1078..d9e9ec9621f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -37,7 +37,7 @@ import io.undertow.Undertow.Builder; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ServletContainer; import org.apache.jasper.servlet.JspServlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.springframework.boot.testsupport.web.servlet.ExampleServlet; @@ -63,7 +63,7 @@ import static org.mockito.Mockito.mock; * @author Ivan Sopov * @author Andy Wilkinson */ -public class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { +class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFactoryTests { @Override protected UndertowServletWebServerFactory getFactory() { @@ -71,7 +71,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void errorPage404() throws Exception { + void errorPage404() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/hello")); this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); @@ -81,14 +81,14 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void setNullBuilderCustomizersThrows() { + void setNullBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test - public void addNullAddBuilderCustomizersThrows() { + void addNullAddBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) @@ -96,7 +96,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void builderCustomizers() { + void builderCustomizers() { UndertowServletWebServerFactory factory = getFactory(); UndertowBuilderCustomizer[] customizers = new UndertowBuilderCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(UndertowBuilderCustomizer.class)); @@ -110,14 +110,14 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void setNullDeploymentInfoCustomizersThrows() { + void setNullDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) .withMessageContaining("Customizers must not be null"); } @Test - public void addNullAddDeploymentInfoCustomizersThrows() { + void addNullAddDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) @@ -125,7 +125,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void deploymentInfo() { + void deploymentInfo() { UndertowServletWebServerFactory factory = getFactory(); UndertowDeploymentInfoCustomizer[] customizers = new UndertowDeploymentInfoCustomizer[4]; Arrays.setAll(customizers, (i) -> mock(UndertowDeploymentInfoCustomizer.class)); @@ -139,12 +139,12 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void basicSslClasspathKeyStore() throws Exception { + void basicSslClasspathKeyStore() throws Exception { testBasicSslWithKeyStore("classpath:test.jks"); } @Test - public void defaultContextPath() { + void defaultContextPath() { UndertowServletWebServerFactory factory = getFactory(); final AtomicReference contextPath = new AtomicReference<>(); factory.addDeploymentInfoCustomizers((deploymentInfo) -> contextPath.set(deploymentInfo.getContextPath())); @@ -153,24 +153,24 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void useForwardHeaders() throws Exception { + void useForwardHeaders() throws Exception { UndertowServletWebServerFactory factory = getFactory(); factory.setUseForwardHeaders(true); assertForwardHeaderIsUsed(factory); } @Test - public void eachFactoryUsesADiscreteServletContainer() { + void eachFactoryUsesADiscreteServletContainer() { assertThat(getServletContainerFromNewFactory()).isNotEqualTo(getServletContainerFromNewFactory()); } @Test - public void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { + void accessLogCanBeEnabled() throws IOException, URISyntaxException, InterruptedException { testAccessLog(null, null, "access_log.log"); } @Test - public void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { + void accessLogCanBeCustomized() throws IOException, URISyntaxException, InterruptedException { testAccessLog("my_access.", "logz", "my_access.logz"); } @@ -180,7 +180,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ factory.setAccessLogEnabled(true); factory.setAccessLogPrefix(prefix); factory.setAccessLogSuffix(suffix); - File accessLogDirectory = this.temporaryFolder.getRoot(); + File accessLogDirectory = this.tempDir; factory.setAccessLogDirectory(accessLogDirectory); assertThat(accessLogDirectory.listFiles()).isEmpty(); this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(), "/hello")); @@ -198,7 +198,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void sslRestrictedProtocolsEmptyCipherFailure() throws Exception { + void sslRestrictedProtocolsEmptyCipherFailure() throws Exception { assertThatIOException() .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) @@ -206,7 +206,7 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { + void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { assertThatIOException() .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) @@ -214,19 +214,19 @@ public class UndertowServletWebServerFactoryTests extends AbstractServletWebServ } @Test - public void sslRestrictedProtocolsECDHESuccess() throws Exception { + void sslRestrictedProtocolsECDHESuccess() throws Exception { testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }); } @Test - public void sslRestrictedProtocolsRSATLS12Success() throws Exception { + void sslRestrictedProtocolsRSATLS12Success() throws Exception { testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" }); } @Test - public void sslRestrictedProtocolsRSATLS11Failure() throws Exception { + void sslRestrictedProtocolsRSATLS11Failure() throws Exception { assertThatIOException() .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java index f60c12f71dc..458a8d67272 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.web.reactive.context; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.ServerManager; import org.springframework.boot.web.reactive.context.config.ExampleReactiveWebServerApplicationConfiguration; @@ -38,26 +38,26 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class AnnotationConfigReactiveWebServerApplicationContextTests { +class AnnotationConfigReactiveWebServerApplicationContextTests { private AnnotationConfigReactiveWebServerApplicationContext context; @Test - public void createFromScan() { + void createFromScan() { this.context = new AnnotationConfigReactiveWebServerApplicationContext( ExampleReactiveWebServerApplicationConfiguration.class.getPackage().getName()); verifyContext(); } @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.context = new AnnotationConfigReactiveWebServerApplicationContext( ExampleReactiveWebServerApplicationConfiguration.class); verifyContext(); } @Test - public void registerAndRefresh() { + void registerAndRefresh() { this.context = new AnnotationConfigReactiveWebServerApplicationContext(); this.context.register(ExampleReactiveWebServerApplicationConfiguration.class); this.context.refresh(); @@ -65,7 +65,7 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { } @Test - public void multipleRegistersAndRefresh() { + void multipleRegistersAndRefresh() { this.context = new AnnotationConfigReactiveWebServerApplicationContext(); this.context.register(WebServerConfiguration.class); this.context.register(HttpHandlerConfiguration.class); @@ -75,7 +75,7 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { } @Test - public void scanAndRefresh() { + void scanAndRefresh() { this.context = new AnnotationConfigReactiveWebServerApplicationContext(); this.context.scan(ExampleReactiveWebServerApplicationConfiguration.class.getPackage().getName()); this.context.refresh(); @@ -83,7 +83,7 @@ public class AnnotationConfigReactiveWebServerApplicationContextTests { } @Test - public void httpHandlerInitialization() { + void httpHandlerInitialization() { // gh-14666 this.context = new AnnotationConfigReactiveWebServerApplicationContext(InitializationTestConfig.class); verifyContext(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java index c97bc87caf7..bd4ce645c96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/GenericReactiveWebApplicationContextTests.java @@ -16,7 +16,7 @@ package org.springframework.boot.web.reactive.context; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.Resource; @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class GenericReactiveWebApplicationContextTests { +class GenericReactiveWebApplicationContextTests { @Test - public void getResourceByPath() throws Exception { + void getResourceByPath() throws Exception { GenericReactiveWebApplicationContext context = new GenericReactiveWebApplicationContext(); Resource rootResource = context.getResourceByPath("/"); assertThat(rootResource.exists()).isFalse(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/config/ExampleReactiveWebServerApplicationConfiguration.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/config/ExampleReactiveWebServerApplicationConfiguration.java index 3be6d761556..95a56637f36 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/config/ExampleReactiveWebServerApplicationConfiguration.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/config/ExampleReactiveWebServerApplicationConfiguration.java @@ -16,7 +16,6 @@ package org.springframework.boot.web.reactive.context.config; -import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContextTests; import org.springframework.boot.web.reactive.server.MockReactiveWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,7 +25,7 @@ import static org.mockito.Mockito.mock; /** * Example {@code @Configuration} for use with - * {@link AnnotationConfigReactiveWebServerApplicationContextTests}. + * {@code AnnotationConfigReactiveWebServerApplicationContextTests}. * * @author Phillip Webb */ diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java index 50d89bebf96..519c182bee0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java @@ -22,7 +22,7 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Brian Clozel * @author Stephane Nicoll */ -public class DefaultErrorAttributesTests { +class DefaultErrorAttributesTests { private static final ResponseStatusException NOT_FOUND = new ResponseStatusException(HttpStatus.NOT_FOUND); @@ -57,7 +57,7 @@ public class DefaultErrorAttributesTests { private List> readers = ServerCodecConfigurer.create().getReaders(); @Test - public void missingExceptionAttribute() { + void missingExceptionAttribute() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); assertThatIllegalStateException().isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, false)) @@ -65,7 +65,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includeTimeStamp() { + void includeTimeStamp() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); @@ -73,7 +73,7 @@ public class DefaultErrorAttributesTests { } @Test - public void defaultStatusCode() { + void defaultStatusCode() { Error error = new OutOfMemoryError("Test error"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), @@ -83,7 +83,7 @@ public class DefaultErrorAttributesTests { } @Test - public void annotatedResponseStatusCode() { + void annotatedResponseStatusCode() { Exception error = new CustomException(); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), @@ -93,7 +93,7 @@ public class DefaultErrorAttributesTests { } @Test - public void annotatedResponseStatusCodeWithCustomReasonPhrase() { + void annotatedResponseStatusCodeWithCustomReasonPhrase() { Exception error = new Custom2Exception(); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, error), @@ -104,7 +104,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includeStatusCode() { + void includeStatusCode() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); @@ -113,7 +113,7 @@ public class DefaultErrorAttributesTests { } @Test - public void getError() { + void getError() { Error error = new OutOfMemoryError("Test error"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, error); @@ -124,7 +124,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includeException() { + void includeException() { RuntimeException error = new RuntimeException("Test"); this.errorAttributes = new DefaultErrorAttributes(true); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); @@ -136,7 +136,7 @@ public class DefaultErrorAttributesTests { } @Test - public void processResponseStatusException() { + void processResponseStatusException() { RuntimeException nested = new RuntimeException("Test"); ResponseStatusException error = new ResponseStatusException(HttpStatus.BAD_REQUEST, "invalid request", nested); this.errorAttributes = new DefaultErrorAttributes(true); @@ -150,7 +150,7 @@ public class DefaultErrorAttributesTests { } @Test - public void processResponseStatusExceptionWithNoNestedCause() { + void processResponseStatusExceptionWithNoNestedCause() { ResponseStatusException error = new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, "could not process request"); this.errorAttributes = new DefaultErrorAttributes(true); @@ -164,7 +164,7 @@ public class DefaultErrorAttributesTests { } @Test - public void notIncludeTrace() { + void notIncludeTrace() { RuntimeException ex = new RuntimeException("Test"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), @@ -173,7 +173,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includeTrace() { + void includeTrace() { RuntimeException ex = new RuntimeException("Test"); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), true); @@ -181,7 +181,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includePath() { + void includePath() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, NOT_FOUND), false); @@ -189,7 +189,7 @@ public class DefaultErrorAttributesTests { } @Test - public void includeLogPrefix() { + void includeLogPrefix() { MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); ServerRequest serverRequest = buildServerRequest(request, NOT_FOUND); Map attributes = this.errorAttributes.getErrorAttributes(serverRequest, false); @@ -197,7 +197,7 @@ public class DefaultErrorAttributesTests { } @Test - public void extractBindingResultErrors() throws Exception { + void extractBindingResultErrors() throws Exception { Method method = getClass().getMethod("method", String.class); MethodParameter stringParam = new MethodParameter(method, 0); BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java index 6934c0e13f1..0e310e4dd86 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewResolverTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.web.reactive.result.view; import java.time.Duration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; @@ -30,13 +30,13 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class MustacheViewResolverTests { +class MustacheViewResolverTests { private final String prefix = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/"; private MustacheViewResolver resolver = new MustacheViewResolver(); - @Before + @BeforeEach public void init() { GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.refresh(); @@ -46,12 +46,12 @@ public class MustacheViewResolverTests { } @Test - public void resolveNonExistent() { + void resolveNonExistent() { assertThat(this.resolver.resolveViewName("bar", null).block(Duration.ofSeconds(30))).isNull(); } @Test - public void resolveExisting() { + void resolveExisting() { assertThat(this.resolver.resolveViewName("template", null).block(Duration.ofSeconds(30))).isNotNull(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java index 34d6c771afc..69256c23a90 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java @@ -21,8 +21,8 @@ import java.time.Duration; import java.util.Collections; import com.samskivert.mustache.Mustache; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import org.springframework.http.MediaType; @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Brian Clozel */ -public class MustacheViewTests { +class MustacheViewTests { private final String templateUrl = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/template.html"; @@ -45,13 +45,13 @@ public class MustacheViewTests { private MockServerWebExchange exchange; - @Before + @BeforeEach public void init() { this.context.refresh(); } @Test - public void viewResolvesHandlebars() { + void viewResolvesHandlebars() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); MustacheView view = new MustacheView(); view.setCompiler(Mustache.compiler()); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java index 9c6e1702485..a9a739d292c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java @@ -38,15 +38,13 @@ import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.netty.NettyPipeline; import reactor.netty.http.client.HttpClient; import reactor.test.StepVerifier; -import org.springframework.boot.testsupport.rule.OutputCapture; import org.springframework.boot.web.server.Compression; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServer; @@ -75,12 +73,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; */ public abstract class AbstractReactiveWebServerFactoryTests { - @Rule - public OutputCapture output = new OutputCapture(); - protected WebServer webServer; - @After + @AfterEach public void tearDown() { if (this.webServer != null) { try { @@ -95,7 +90,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected abstract AbstractReactiveWebServerFactory getFactory(); @Test - public void specificPort() { + void specificPort() { AbstractReactiveWebServerFactory factory = getFactory(); int specificPort = SocketUtils.findAvailableTcpPort(41000); factory.setPort(specificPort); @@ -109,12 +104,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void basicSslFromClassPath() { + void basicSslFromClassPath() { testBasicSslWithKeyStore("classpath:test.jks", "password"); } @Test - public void basicSslFromFileSystem() { + void basicSslFromFileSystem() { testBasicSslWithKeyStore("src/test/resources/test.jks", "password"); } @@ -144,7 +139,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { + void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.WANT); ssl.setKeyStore("classpath:test.jks"); @@ -154,7 +149,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() { + void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.WANT); ssl.setKeyStore("classpath:test.jks"); @@ -201,7 +196,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { + void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.NEED); ssl.setKeyStore("classpath:test.jks"); @@ -211,7 +206,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() { + void sslNeedsClientAuthenticationFailsWithoutClientCertificate() { Ssl ssl = new Ssl(); ssl.setClientAuth(Ssl.ClientAuth.NEED); ssl.setKeyStore("classpath:test.jks"); @@ -244,7 +239,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void compressionOfResponseToGetRequest() { + void compressionOfResponseToGetRequest() { WebClient client = prepareCompressionTest(); ResponseEntity response = client.get().exchange().flatMap((res) -> res.toEntity(Void.class)) .block(Duration.ofSeconds(30)); @@ -252,7 +247,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void compressionOfResponseToPostRequest() { + void compressionOfResponseToPostRequest() { WebClient client = prepareCompressionTest(); ResponseEntity response = client.post().exchange().flatMap((res) -> res.toEntity(Void.class)) .block(Duration.ofSeconds(30)); @@ -260,7 +255,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void noCompressionForSmallResponse() { + void noCompressionForSmallResponse() { Compression compression = new Compression(); compression.setEnabled(true); compression.setMinResponseSize(DataSize.ofBytes(3001)); @@ -271,7 +266,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void noCompressionForMimeType() { + void noCompressionForMimeType() { Compression compression = new Compression(); compression.setMimeTypes(new String[] { "application/json" }); WebClient client = prepareCompressionTest(compression); @@ -281,7 +276,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void noCompressionForUserAgent() { + void noCompressionForUserAgent() { Compression compression = new Compression(); compression.setEnabled(true); compression.setExcludedUserAgents(new String[] { "testUserAgent" }); @@ -292,7 +287,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { } @Test - public void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() { + void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() { assertThatThrownBy(() -> testBasicSslWithKeyStore(null, null)) .hasMessageContaining("Could not load key store 'null'"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java index 58ce690450d..3bad5754297 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CompressionTests.java @@ -17,10 +17,7 @@ package org.springframework.boot.web.server; import org.apache.coyote.http11.Http11NioProtocol; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,11 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) -public class CompressionTests { +class CompressionTests { @Test - public void defaultCompressableMimeTypesMatchesTomcatsDefault() { + void defaultCompressableMimeTypesMatchesTomcatsDefault() { assertThat(new Compression().getMimeTypes()).containsExactlyInAnyOrder(getTomcatDefaultCompressableMimeTypes()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/LocalServerPortTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/LocalServerPortTests.java index 84df9655b50..a6f6d1e6c4f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/LocalServerPortTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/LocalServerPortTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.web.server; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -32,9 +32,9 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Anand Shah * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @TestPropertySource(properties = "local.server.port=8181") -public class LocalServerPortTests { +class LocalServerPortTests { @Value("${local.server.port}") private String fromValue; @@ -43,7 +43,7 @@ public class LocalServerPortTests { private String fromAnnotation; @Test - public void testLocalServerPortAnnotation() { + void testLocalServerPortAnnotation() { assertThat(this.fromAnnotation).isNotNull().isEqualTo(this.fromValue); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java index 53c61fc0dc2..7c8e2347dd4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java @@ -21,7 +21,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -31,16 +31,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Phillip Webb */ -public class MimeMappingsTests { +class MimeMappingsTests { @Test - public void defaultsCannotBeModified() { + void defaultsCannotBeModified() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar")); } @Test - public void createFromExisting() { + void createFromExisting() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); MimeMappings clone = new MimeMappings(mappings); @@ -50,7 +50,7 @@ public class MimeMappingsTests { } @Test - public void createFromMap() { + void createFromMap() { Map mappings = new HashMap<>(); mappings.put("foo", "bar"); MimeMappings clone = new MimeMappings(mappings); @@ -60,7 +60,7 @@ public class MimeMappingsTests { } @Test - public void iterate() { + void iterate() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); mappings.add("baz", "boo"); @@ -75,7 +75,7 @@ public class MimeMappingsTests { } @Test - public void getAll() { + void getAll() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); mappings.add("baz", "boo"); @@ -87,20 +87,20 @@ public class MimeMappingsTests { } @Test - public void addNew() { + void addNew() { MimeMappings mappings = new MimeMappings(); assertThat(mappings.add("foo", "bar")).isNull(); } @Test - public void addReplacesExisting() { + void addReplacesExisting() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); assertThat(mappings.add("foo", "baz")).isEqualTo("bar"); } @Test - public void remove() { + void remove() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); assertThat(mappings.remove("foo")).isEqualTo("bar"); @@ -108,20 +108,20 @@ public class MimeMappingsTests { } @Test - public void get() { + void get() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); assertThat(mappings.get("foo")).isEqualTo("bar"); } @Test - public void getMissing() { + void getMissing() { MimeMappings mappings = new MimeMappings(); assertThat(mappings.get("foo")).isNull(); } @Test - public void makeUnmodifiable() { + void makeUnmodifiable() { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); MimeMappings unmodifiable = MimeMappings.unmodifiableMappings(mappings); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index a1d289d7931..043a0f4ffac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -22,8 +22,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -40,28 +40,28 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ -public class WebServerFactoryCustomizerBeanPostProcessorTests { +class WebServerFactoryCustomizerBeanPostProcessorTests { private WebServerFactoryCustomizerBeanPostProcessor processor = new WebServerFactoryCustomizerBeanPostProcessor(); @Mock private ListableBeanFactory beanFactory; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.processor.setBeanFactory(this.beanFactory); } @Test - public void setBeanFactoryWhenNotListableShouldThrowException() { + void setBeanFactoryWhenNotListableShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) .withMessageContaining( "WebServerCustomizerBeanPostProcessor can only " + "be used with a ListableBeanFactory"); } @Test - public void postProcessBeforeShouldReturnBean() { + void postProcessBeforeShouldReturnBean() { addMockBeans(Collections.emptyMap()); Object bean = new Object(); Object result = this.processor.postProcessBeforeInitialization(bean, "foo"); @@ -69,7 +69,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterShouldReturnBean() { + void postProcessAfterShouldReturnBean() { addMockBeans(Collections.emptyMap()); Object bean = new Object(); Object result = this.processor.postProcessAfterInitialization(bean, "foo"); @@ -77,7 +77,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterShouldCallInterfaceCustomizers() { + void postProcessAfterShouldCallInterfaceCustomizers() { Map beans = addInterfaceBeans(); addMockBeans(beans); postProcessBeforeInitialization(WebServerFactory.class); @@ -87,7 +87,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterWhenWebServerFactoryOneShouldCallInterfaceCustomizers() { + void postProcessAfterWhenWebServerFactoryOneShouldCallInterfaceCustomizers() { Map beans = addInterfaceBeans(); addMockBeans(beans); postProcessBeforeInitialization(WebServerFactoryOne.class); @@ -97,7 +97,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterWhenWebServerFactoryTwoShouldCallInterfaceCustomizers() { + void postProcessAfterWhenWebServerFactoryTwoShouldCallInterfaceCustomizers() { Map beans = addInterfaceBeans(); addMockBeans(beans); postProcessBeforeInitialization(WebServerFactoryTwo.class); @@ -118,7 +118,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterShouldCallLambdaCustomizers() { + void postProcessAfterShouldCallLambdaCustomizers() { List called = new ArrayList<>(); addLambdaBeans(called); postProcessBeforeInitialization(WebServerFactory.class); @@ -126,7 +126,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterWhenWebServerFactoryOneShouldCallLambdaCustomizers() { + void postProcessAfterWhenWebServerFactoryOneShouldCallLambdaCustomizers() { List called = new ArrayList<>(); addLambdaBeans(called); postProcessBeforeInitialization(WebServerFactoryOne.class); @@ -134,7 +134,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { } @Test - public void postProcessAfterWhenWebServerFactoryTwoShouldCallLambdaCustomizers() { + void postProcessAfterWhenWebServerFactoryTwoShouldCallLambdaCustomizers() { List called = new ArrayList<>(); addLambdaBeans(called); postProcessBeforeInitialization(WebServerFactoryTwo.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index 262ee54dab3..10d94e54110 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -28,8 +28,8 @@ import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -46,7 +46,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public abstract class AbstractFilterRegistrationBeanTests { +abstract class AbstractFilterRegistrationBeanTests { @Mock ServletContext servletContext; @@ -54,14 +54,14 @@ public abstract class AbstractFilterRegistrationBeanTests { @Mock FilterRegistration.Dynamic registration; - @Before + @BeforeEach public void setupMocks() { MockitoAnnotations.initMocks(this); given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); } @Test - public void startupWithDefaults() throws Exception { + void startupWithDefaults() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter()); @@ -70,7 +70,7 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void startupWithSpecifiedValues() throws Exception { + void startupWithSpecifiedValues() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setName("test"); bean.setAsyncSupported(false); @@ -96,7 +96,7 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void specificName() throws Exception { + void specificName() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setName("specificName"); bean.onStartup(this.servletContext); @@ -104,14 +104,14 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void deducedName() throws Exception { + void deducedName() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter()); } @Test - public void disable() throws Exception { + void disable() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setEnabled(false); bean.onStartup(this.servletContext); @@ -119,14 +119,14 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void setServletRegistrationBeanMustNotBeNull() { + void setServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletRegistrationBeans(null)) .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test - public void addServletRegistrationBeanMustNotBeNull() { + void addServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException() .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) @@ -134,7 +134,7 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void setServletRegistrationBeanReplacesValue() throws Exception { + void setServletRegistrationBeanReplacesValue() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(mockServletRegistration("a")); bean.setServletRegistrationBeans( new LinkedHashSet>(Collections.singletonList(mockServletRegistration("b")))); @@ -143,7 +143,7 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void modifyInitParameters() throws Exception { + void modifyInitParameters() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); @@ -152,35 +152,35 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void setUrlPatternMustNotBeNull() { + void setUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlPatterns(null)) .withMessageContaining("UrlPatterns must not be null"); } @Test - public void addUrlPatternMustNotBeNull() { + void addUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlPatterns((String[]) null)) .withMessageContaining("UrlPatterns must not be null"); } @Test - public void setServletNameMustNotBeNull() { + void setServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletNames(null)) .withMessageContaining("ServletNames must not be null"); } @Test - public void addServletNameMustNotBeNull() { + void addServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addServletNames((String[]) null)) .withMessageContaining("ServletNames must not be null"); } @Test - public void withSpecificDispatcherTypes() throws Exception { + void withSpecificDispatcherTypes() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); @@ -189,7 +189,7 @@ public abstract class AbstractFilterRegistrationBeanTests { } @Test - public void withSpecificDispatcherTypesEnumSet() throws Exception { + void withSpecificDispatcherTypesEnumSet() throws Exception { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); EnumSet types = EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.setDispatcherTypes(types); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index ca0721bb00f..1a8912bee19 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -21,7 +21,7 @@ import javax.servlet.FilterChain; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.mock.web.MockFilterChain; @@ -43,7 +43,7 @@ import static org.mockito.ArgumentMatchers.isA; * * @author Phillip Webb */ -public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { +class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { private static ThreadLocal mockFilterInitialized = new ThreadLocal<>(); @@ -51,24 +51,24 @@ public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRe new MockServletContext()); @Test - public void targetBeanNameMustNotBeNull() { + void targetBeanNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) .withMessageContaining("TargetBeanName must not be null or empty"); } @Test - public void targetBeanNameMustNotBeEmpty() { + void targetBeanNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) .withMessageContaining("TargetBeanName must not be null or empty"); } @Test - public void nameDefaultsToTargetBeanName() { + void nameDefaultsToTargetBeanName() { assertThat(new DelegatingFilterProxyRegistrationBean("myFilter").getOrDeduceName(null)).isEqualTo("myFilter"); } @Test - public void getFilterUsesDelegatingFilterProxy() { + void getFilterUsesDelegatingFilterProxy() { DelegatingFilterProxyRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); assertThat(filter).isInstanceOf(DelegatingFilterProxy.class); @@ -77,7 +77,7 @@ public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRe } @Test - public void initShouldNotCauseEarlyInitialization() throws Exception { + void initShouldNotCauseEarlyInitialization() throws Exception { this.applicationContext.registerBeanDefinition("mockFilter", new RootBeanDefinition(MockFilter.class)); DelegatingFilterProxyRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); @@ -88,7 +88,7 @@ public class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRe } @Test - public void createServletRegistrationBeanMustNotBeNull() { + void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy( () -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index 9a65bd277a0..b1e7eff2b42 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.servlet; import javax.servlet.Filter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.servlet.mock.MockFilter; @@ -31,12 +31,12 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { +class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { private final MockFilter filter = new MockFilter(); @Test - public void setFilter() throws Exception { + void setFilter() throws Exception { FilterRegistrationBean bean = new FilterRegistrationBean<>(); bean.setFilter(this.filter); bean.onStartup(this.servletContext); @@ -44,20 +44,20 @@ public class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanT } @Test - public void setFilterMustNotBeNull() throws Exception { + void setFilterMustNotBeNull() throws Exception { FilterRegistrationBean bean = new FilterRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) .withMessageContaining("Filter must not be null"); } @Test - public void constructFilterMustNotBeNull() { + void constructFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FilterRegistrationBean<>(null)) .withMessageContaining("Filter must not be null"); } @Test - public void createServletRegistrationBeanMustNotBeNull() { + void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) .withMessageContaining("ServletRegistrationBeans must not be null"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java index 2b06710156c..1e071f6f73f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.web.servlet; import javax.servlet.Filter; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; @@ -34,11 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class FilterRegistrationIntegrationTests { +class FilterRegistrationIntegrationTests { private AnnotationConfigServletWebServerApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -46,13 +46,13 @@ public class FilterRegistrationIntegrationTests { } @Test - public void normalFiltersAreRegistered() { + void normalFiltersAreRegistered() { load(FilterConfiguration.class); assertThat(this.context.getServletContext().getFilterRegistrations()).hasSize(1); } @Test - public void scopedTargetFiltersAreNotRegistered() { + void scopedTargetFiltersAreNotRegistered() { load(ScopedTargetFilterConfiguration.class); assertThat(this.context.getServletContext().getFilterRegistrations()).isEmpty(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/MultipartConfigFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/MultipartConfigFactoryTests.java index 139294aab39..cb0b18a06b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/MultipartConfigFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/MultipartConfigFactoryTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.servlet; import javax.servlet.MultipartConfigElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.util.unit.DataSize; @@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Stephane Nicoll */ -public class MultipartConfigFactoryTests { +class MultipartConfigFactoryTests { @Test - public void sensibleDefaults() { + void sensibleDefaults() { MultipartConfigFactory factory = new MultipartConfigFactory(); MultipartConfigElement config = factory.createMultipartConfig(); assertThat(config.getLocation()).isEqualTo(""); @@ -43,7 +43,7 @@ public class MultipartConfigFactoryTests { } @Test - public void createWithDataSizes() { + void createWithDataSizes() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize(DataSize.ofBytes(1)); factory.setMaxRequestSize(DataSize.ofKilobytes(2)); @@ -55,7 +55,7 @@ public class MultipartConfigFactoryTests { } @Test - public void createWithNegativeDataSizes() { + void createWithNegativeDataSizes() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize(DataSize.ofBytes(-1)); factory.setMaxRequestSize(DataSize.ofKilobytes(-2)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java index 371b235a28e..edaf2b9d7ff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java @@ -20,8 +20,8 @@ import java.util.Map; import javax.servlet.MultipartConfigElement; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; @@ -38,11 +38,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ServletComponentScanIntegrationTests { +class ServletComponentScanIntegrationTests { private AnnotationConfigServletWebServerApplicationContext context; - @After + @AfterEach public void cleanUp() { if (this.context != null) { this.context.close(); @@ -50,7 +50,7 @@ public class ServletComponentScanIntegrationTests { } @Test - public void componentsAreRegistered() { + void componentsAreRegistered() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(TestConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); @@ -61,7 +61,7 @@ public class ServletComponentScanIntegrationTests { } @Test - public void multipartConfigIsHonoured() { + void multipartConfigIsHonoured() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(TestConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index 16cb1ba0cf1..f601022c8c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.web.servlet; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -32,11 +32,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Andy Wilkinson */ -public class ServletComponentScanRegistrarTests { +class ServletComponentScanRegistrarTests { private AnnotationConfigApplicationContext context; - @After + @AfterEach public void after() { if (this.context != null) { this.context.close(); @@ -44,7 +44,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesConfiguredWithValue() { + void packagesConfiguredWithValue() { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -52,7 +52,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesConfiguredWithValueAsm() { + void packagesConfiguredWithValueAsm() { this.context = new AnnotationConfigApplicationContext(); this.context.registerBeanDefinition("valuePackages", new RootBeanDefinition(ValuePackages.class.getName())); this.context.refresh(); @@ -62,7 +62,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesConfiguredWithBackPackages() { + void packagesConfiguredWithBackPackages() { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -70,7 +70,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesConfiguredWithBasePackageClasses() { + void packagesConfiguredWithBasePackageClasses() { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -78,7 +78,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesConfiguredWithBothValueAndBasePackages() { + void packagesConfiguredWithBothValueAndBasePackages() { assertThatExceptionOfType(AnnotationConfigurationException.class) .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) .withMessageContaining("'value'").withMessageContaining("'basePackages'") @@ -86,7 +86,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void packagesFromMultipleAnnotationsAreMerged() { + void packagesFromMultipleAnnotationsAreMerged() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -94,7 +94,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void withNoBasePackagesScanningUsesBasePackageOfAnnotatedClass() { + void withNoBasePackagesScanningUsesBasePackageOfAnnotatedClass() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -102,7 +102,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void noBasePackageAndBasePackageAreCombinedCorrectly() { + void noBasePackageAndBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); @@ -111,7 +111,7 @@ public class ServletComponentScanRegistrarTests { } @Test - public void basePackageAndNoBasePackageAreCombinedCorrectly() { + void basePackageAndNoBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java index ed85afba60e..665779a0ee1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java @@ -25,7 +25,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -39,12 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -public class ServletContextInitializerBeansTests { +class ServletContextInitializerBeansTests { private ConfigurableApplicationContext context; @Test - public void servletThatImplementsServletContextInitializerIsOnlyRegisteredOnce() { + void servletThatImplementsServletContextInitializerIsOnlyRegisteredOnce() { load(ServletConfiguration.class); ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); @@ -53,7 +53,7 @@ public class ServletContextInitializerBeansTests { } @Test - public void filterThatImplementsServletContextInitializerIsOnlyRegisteredOnce() { + void filterThatImplementsServletContextInitializerIsOnlyRegisteredOnce() { load(FilterConfiguration.class); ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); @@ -62,7 +62,7 @@ public class ServletContextInitializerBeansTests { } @Test - public void looksForInitializerBeansOfSpecifiedType() { + void looksForInitializerBeansOfSpecifiedType() { load(TestConfiguration.class); ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory(), TestServletContextInitializer.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index 2e15609d74e..d58e67709e1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -21,8 +21,8 @@ import java.util.EventListener; import javax.servlet.ServletContext; import javax.servlet.ServletContextListener; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; * * @author Dave Syer */ -public class ServletListenerRegistrationBeanTests { +class ServletListenerRegistrationBeanTests { @Mock private ServletContextListener listener; @@ -44,13 +44,13 @@ public class ServletListenerRegistrationBeanTests { @Mock private ServletContext servletContext; - @Before + @BeforeEach public void setupMocks() { MockitoAnnotations.initMocks(this); } @Test - public void startupWithDefaults() throws Exception { + void startupWithDefaults() throws Exception { ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean<>( this.listener); bean.onStartup(this.servletContext); @@ -58,7 +58,7 @@ public class ServletListenerRegistrationBeanTests { } @Test - public void disable() throws Exception { + void disable() throws Exception { ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean<>( this.listener); bean.setEnabled(false); @@ -67,7 +67,7 @@ public class ServletListenerRegistrationBeanTests { } @Test - public void cannotRegisterUnsupportedType() { + void cannotRegisterUnsupportedType() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index c7f1d1fcfe6..8932978d0e7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -28,8 +28,8 @@ import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -47,7 +47,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class ServletRegistrationBeanTests { +class ServletRegistrationBeanTests { private final MockServlet servlet = new MockServlet(); @@ -60,7 +60,7 @@ public class ServletRegistrationBeanTests { @Mock private FilterRegistration.Dynamic filterRegistration; - @Before + @BeforeEach public void setupMocks() { MockitoAnnotations.initMocks(this); given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); @@ -68,7 +68,7 @@ public class ServletRegistrationBeanTests { } @Test - public void startupWithDefaults() throws Exception { + void startupWithDefaults() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); bean.onStartup(this.servletContext); verify(this.servletContext).addServlet("mockServlet", this.servlet); @@ -77,7 +77,7 @@ public class ServletRegistrationBeanTests { } @Test - public void startupWithDoubleRegistration() throws Exception { + void startupWithDoubleRegistration() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(null); bean.onStartup(this.servletContext); @@ -86,7 +86,7 @@ public class ServletRegistrationBeanTests { } @Test - public void startupWithSpecifiedValues() throws Exception { + void startupWithSpecifiedValues() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); bean.setName("test"); bean.setServlet(this.servlet); @@ -108,7 +108,7 @@ public class ServletRegistrationBeanTests { } @Test - public void specificName() throws Exception { + void specificName() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); bean.setName("specificName"); bean.setServlet(this.servlet); @@ -117,7 +117,7 @@ public class ServletRegistrationBeanTests { } @Test - public void deducedName() throws Exception { + void deducedName() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); bean.setServlet(this.servlet); bean.onStartup(this.servletContext); @@ -125,7 +125,7 @@ public class ServletRegistrationBeanTests { } @Test - public void disable() throws Exception { + void disable() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); bean.setServlet(this.servlet); bean.setEnabled(false); @@ -134,41 +134,41 @@ public class ServletRegistrationBeanTests { } @Test - public void setServletMustNotBeNull() throws Exception { + void setServletMustNotBeNull() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) .withMessageContaining("Servlet must not be null"); } @Test - public void createServletMustNotBeNull() { + void createServletMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletRegistrationBean(null)) .withMessageContaining("Servlet must not be null"); } @Test - public void setMappingMustNotBeNull() { + void setMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlMappings(null)) .withMessageContaining("UrlMappings must not be null"); } @Test - public void createMappingMustNotBeNull() { + void createMappingMustNotBeNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) .withMessageContaining("UrlMappings must not be null"); } @Test - public void addMappingMustNotBeNull() { + void addMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlMappings((String[]) null)) .withMessageContaining("UrlMappings must not be null"); } @Test - public void setMappingReplacesValue() throws Exception { + void setMappingReplacesValue() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.setUrlMappings(new LinkedHashSet<>(Arrays.asList("/c", "/d"))); bean.onStartup(this.servletContext); @@ -176,7 +176,7 @@ public class ServletRegistrationBeanTests { } @Test - public void modifyInitParameters() throws Exception { + void modifyInitParameters() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); @@ -185,7 +185,7 @@ public class ServletRegistrationBeanTests { } @Test - public void withoutDefaultMappings() throws Exception { + void withoutDefaultMappings() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, false); bean.onStartup(this.servletContext); verify(this.registration, never()).addMapping(any(String[].class)); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 23a6367fb60..c1f8a26ed69 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -30,7 +30,7 @@ import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Andy Wilkinson */ -public class WebFilterHandlerTests { +class WebFilterHandlerTests { private final WebFilterHandler handler = new WebFilterHandler(); @@ -54,7 +54,7 @@ public class WebFilterHandlerTests { @SuppressWarnings("unchecked") @Test - public void defaultFilterConfiguration() throws IOException { + void defaultFilterConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationFilter.class.getName())); this.handler.handle(scanned, this.registry); @@ -72,7 +72,7 @@ public class WebFilterHandlerTests { } @Test - public void filterWithCustomName() throws IOException { + void filterWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory().getMetadataReader(CustomNameFilter.class.getName())); this.handler.handle(scanned, this.registry); @@ -82,7 +82,7 @@ public class WebFilterHandlerTests { } @Test - public void asyncSupported() throws IOException { + void asyncSupported() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(AsyncSupportedFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); @@ -90,7 +90,7 @@ public class WebFilterHandlerTests { @Test @SuppressWarnings("unchecked") - public void dispatcherTypes() throws IOException { + void dispatcherTypes() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(DispatcherTypesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((Set) propertyValues.get("dispatcherTypes")).containsExactly(DispatcherType.FORWARD, @@ -99,7 +99,7 @@ public class WebFilterHandlerTests { @SuppressWarnings("unchecked") @Test - public void initParameters() throws IOException { + void initParameters() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") @@ -107,28 +107,28 @@ public class WebFilterHandlerTests { } @Test - public void servletNames() throws IOException { + void servletNames() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(ServletNamesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", "bravo"); } @Test - public void urlPatterns() throws IOException { + void urlPatterns() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test - public void urlPatternsFromValue() throws IOException { + void urlPatternsFromValue() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition(UrlPatternsFromValueFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", "bravo"); } @Test - public void urlPatternsDeclaredTwice() throws IOException { + void urlPatternsDeclaredTwice() throws IOException { assertThatIllegalStateException().isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class)) .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java index 3d9497d3fd5..b2e8e98de6c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java @@ -22,7 +22,7 @@ import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.annotation.WebListener; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.context.annotation.ScannedGenericBeanDefinition; @@ -33,14 +33,14 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; * * @author Andy Wilkinson */ -public class WebListenerHandlerTests { +class WebListenerHandlerTests { private final WebListenerHandler handler = new WebListenerHandler(); private final SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); @Test - public void listener() throws IOException { + void listener() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName())); this.handler.handle(scanned, this.registry); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index 480a4f1429c..42df4f0d10c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -23,7 +23,7 @@ import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Andy Wilkinson */ -public class WebServletHandlerTests { +class WebServletHandlerTests { private final WebServletHandler handler = new WebServletHandler(); @@ -47,7 +47,7 @@ public class WebServletHandlerTests { @SuppressWarnings("unchecked") @Test - public void defaultServletConfiguration() throws IOException { + void defaultServletConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory().getMetadataReader(DefaultConfigurationServlet.class.getName())); this.handler.handle(scanned, this.registry); @@ -63,7 +63,7 @@ public class WebServletHandlerTests { } @Test - public void servletWithCustomName() throws IOException { + void servletWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory().getMetadataReader(CustomNameServlet.class.getName())); this.handler.handle(scanned, this.registry); @@ -73,7 +73,7 @@ public class WebServletHandlerTests { } @Test - public void asyncSupported() throws IOException { + void asyncSupported() throws IOException { BeanDefinition servletRegistrationBean = getBeanDefinition(AsyncSupportedServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); @@ -81,7 +81,7 @@ public class WebServletHandlerTests { @SuppressWarnings("unchecked") @Test - public void initParameters() throws IOException { + void initParameters() throws IOException { BeanDefinition servletRegistrationBean = getBeanDefinition(InitParametersServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") @@ -89,21 +89,21 @@ public class WebServletHandlerTests { } @Test - public void urlMappings() throws IOException { + void urlMappings() throws IOException { BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test - public void urlMappingsFromValue() throws IOException { + void urlMappingsFromValue() throws IOException { BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsFromValueServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo"); } @Test - public void urlPatternsDeclaredTwice() throws IOException { + void urlPatternsDeclaredTwice() throws IOException { assertThatIllegalStateException().isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class)) .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java index 94f4b9d10c9..8cfe59d740a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContextTests.java @@ -22,8 +22,8 @@ import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.context.config.ExampleServletWebServerApplicationConfiguration; @@ -46,11 +46,11 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class AnnotationConfigServletWebServerApplicationContextTests { +class AnnotationConfigServletWebServerApplicationContextTests { private AnnotationConfigServletWebServerApplicationContext context; - @After + @AfterEach public void close() { if (this.context != null) { this.context.close(); @@ -58,21 +58,21 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void createFromScan() { + void createFromScan() { this.context = new AnnotationConfigServletWebServerApplicationContext( ExampleServletWebServerApplicationConfiguration.class.getPackage().getName()); verifyContext(); } @Test - public void sessionScopeAvailable() { + void sessionScopeAvailable() { this.context = new AnnotationConfigServletWebServerApplicationContext( ExampleServletWebServerApplicationConfiguration.class, SessionScopedComponent.class); verifyContext(); } @Test - public void sessionScopeAvailableToServlet() { + void sessionScopeAvailableToServlet() { this.context = new AnnotationConfigServletWebServerApplicationContext( ExampleServletWebServerApplicationConfiguration.class, ExampleServletWithAutowired.class, SessionScopedComponent.class); @@ -81,14 +81,14 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void createFromConfigClass() { + void createFromConfigClass() { this.context = new AnnotationConfigServletWebServerApplicationContext( ExampleServletWebServerApplicationConfiguration.class); verifyContext(); } @Test - public void registerAndRefresh() { + void registerAndRefresh() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(ExampleServletWebServerApplicationConfiguration.class); this.context.refresh(); @@ -96,7 +96,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void multipleRegistersAndRefresh() { + void multipleRegistersAndRefresh() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(WebServerConfiguration.class); this.context.register(ServletContextAwareConfiguration.class); @@ -106,7 +106,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void scanAndRefresh() { + void scanAndRefresh() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.scan(ExampleServletWebServerApplicationConfiguration.class.getPackage().getName()); this.context.refresh(); @@ -114,7 +114,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void createAndInitializeCyclic() { + void createAndInitializeCyclic() { this.context = new AnnotationConfigServletWebServerApplicationContext( ServletContextAwareEmbeddedConfiguration.class); verifyContext(); @@ -124,7 +124,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { } @Test - public void createAndInitializeWithParent() { + void createAndInitializeWithParent() { AnnotationConfigServletWebServerApplicationContext parent = new AnnotationConfigServletWebServerApplicationContext( WebServerConfiguration.class); this.context = new AnnotationConfigServletWebServerApplicationContext(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java index 8dd891a0cda..413fee8ddaf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java @@ -28,10 +28,10 @@ import javax.servlet.ServletContextListener; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; @@ -45,7 +45,8 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.Scope; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer; import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; @@ -85,29 +86,27 @@ import static org.mockito.Mockito.withSettings; * @author Phillip Webb * @author Stephane Nicoll */ -public class ServletWebServerApplicationContextTests { +@ExtendWith(OutputCaptureExtension.class) +class ServletWebServerApplicationContextTests { private ServletWebServerApplicationContext context; - @Rule - public OutputCapture output = new OutputCapture(); - @Captor private ArgumentCaptor filterCaptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.context = new ServletWebServerApplicationContext(); } - @After + @AfterEach public void cleanup() { this.context.close(); } @Test - public void startRegistrations() { + void startRegistrations() { addWebServerFactoryBean(); this.context.refresh(); MockServletWebServerFactory factory = getWebServerFactory(); @@ -123,7 +122,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void doesNotRegistersShutdownHook() { + void doesNotRegistersShutdownHook() { // See gh-314 for background. We no longer register the shutdown hook // since it is really the callers responsibility. The shutdown hook could // also be problematic in a classic WAR deployment. @@ -133,7 +132,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void ServletWebServerInitializedEventPublished() { + void ServletWebServerInitializedEventPublished() { addWebServerFactoryBean(); this.context.registerBeanDefinition("listener", new RootBeanDefinition(MockListener.class)); this.context.refresh(); @@ -144,7 +143,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void localPortIsAvailable() { + void localPortIsAvailable() { addWebServerFactoryBean(); new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); @@ -154,7 +153,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void stopOnClose() { + void stopOnClose() { addWebServerFactoryBean(); this.context.refresh(); MockServletWebServerFactory factory = getWebServerFactory(); @@ -163,14 +162,14 @@ public class ServletWebServerApplicationContextTests { } @Test - public void cannotSecondRefresh() { + void cannotSecondRefresh() { addWebServerFactoryBean(); this.context.refresh(); assertThatIllegalStateException().isThrownBy(() -> this.context.refresh()); } @Test - public void servletContextAwareBeansAreInjected() { + void servletContextAwareBeansAreInjected() { addWebServerFactoryBean(); ServletContextAware bean = mock(ServletContextAware.class); this.context.registerBeanDefinition("bean", beanDefinition(bean)); @@ -179,14 +178,14 @@ public class ServletWebServerApplicationContextTests { } @Test - public void missingServletWebServerFactory() { + void missingServletWebServerFactory() { assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " + "ServletWebServerFactory bean"); } @Test - public void tooManyWebServerFactories() { + void tooManyWebServerFactories() { addWebServerFactoryBean(); this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); @@ -197,7 +196,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void singleServletBean() { + void singleServletBean() { addWebServerFactoryBean(); Servlet servlet = mock(Servlet.class); this.context.registerBeanDefinition("servletBean", beanDefinition(servlet)); @@ -208,7 +207,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void orderedBeanInsertedCorrectly() { + void orderedBeanInsertedCorrectly() { addWebServerFactoryBean(); OrderedFilter filter = new OrderedFilter(); this.context.registerBeanDefinition("filterBean", beanDefinition(filter)); @@ -224,7 +223,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void multipleServletBeans() { + void multipleServletBeans() { addWebServerFactoryBean(); Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); @@ -243,7 +242,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void multipleServletBeansWithMainDispatcher() { + void multipleServletBeansWithMainDispatcher() { addWebServerFactoryBean(); Servlet servlet1 = mock(Servlet.class, withSettings().extraInterfaces(Ordered.class)); given(((Ordered) servlet1).getOrder()).willReturn(1); @@ -262,7 +261,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletAndFilterBeans() { + void servletAndFilterBeans() { addWebServerFactoryBean(); Servlet servlet = mock(Servlet.class); Filter filter1 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class)); @@ -287,7 +286,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletContextInitializerBeans() throws Exception { + void servletContextInitializerBeans() throws Exception { addWebServerFactoryBean(); ServletContextInitializer initializer1 = mock(ServletContextInitializer.class, withSettings().extraInterfaces(Ordered.class)); @@ -305,7 +304,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletContextListenerBeans() { + void servletContextListenerBeans() { addWebServerFactoryBean(); ServletContextListener initializer = mock(ServletContextListener.class); this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); @@ -315,7 +314,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void unorderedServletContextInitializerBeans() throws Exception { + void unorderedServletContextInitializerBeans() throws Exception { addWebServerFactoryBean(); ServletContextInitializer initializer1 = mock(ServletContextInitializer.class); ServletContextInitializer initializer2 = mock(ServletContextInitializer.class); @@ -328,7 +327,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletContextInitializerBeansDoesNotSkipServletsAndFilters() throws Exception { + void servletContextInitializerBeansDoesNotSkipServletsAndFilters() throws Exception { addWebServerFactoryBean(); ServletContextInitializer initializer = mock(ServletContextInitializer.class); Servlet servlet = mock(Servlet.class); @@ -344,7 +343,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletContextInitializerBeansSkipsRegisteredServletsAndFilters() { + void servletContextInitializerBeansSkipsRegisteredServletsAndFilters() { addWebServerFactoryBean(); Servlet servlet = mock(Servlet.class); Filter filter = mock(Filter.class); @@ -359,7 +358,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void filterRegistrationBeansSkipsRegisteredFilters() { + void filterRegistrationBeansSkipsRegisteredFilters() { addWebServerFactoryBean(); Filter filter = mock(Filter.class); FilterRegistrationBean initializer = new FilterRegistrationBean<>(filter); @@ -371,7 +370,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() throws Exception { + void delegatingFilterProxyRegistrationBeansSkipsTargetBeanNames() throws Exception { addWebServerFactoryBean(); DelegatingFilterProxyRegistrationBean initializer = new DelegatingFilterProxyRegistrationBean("filterBean"); this.context.registerBeanDefinition("initializerBean", beanDefinition(initializer)); @@ -391,7 +390,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void postProcessWebServerFactory() { + void postProcessWebServerFactory() { RootBeanDefinition beanDefinition = new RootBeanDefinition(MockServletWebServerFactory.class); MutablePropertyValues pv = new MutablePropertyValues(); pv.add("port", "${port}"); @@ -407,7 +406,7 @@ public class ServletWebServerApplicationContextTests { } @Test - public void doesNotReplaceExistingScopes() { + void doesNotReplaceExistingScopes() { // gh-2082 Scope scope = mock(Scope.class); ConfigurableListableBeanFactory factory = this.context.getBeanFactory(); @@ -420,9 +419,9 @@ public class ServletWebServerApplicationContextTests { } @Test - public void servletRequestCanBeInjectedEarly() throws Exception { + void servletRequestCanBeInjectedEarly(CapturedOutput capturedOutput) throws Exception { // gh-14990 - int initialOutputLength = this.output.toString().length(); + int initialOutputLength = capturedOutput.length(); addWebServerFactoryBean(); RootBeanDefinition beanDefinition = new RootBeanDefinition(WithAutowiredServletRequest.class); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); @@ -432,12 +431,12 @@ public class ServletWebServerApplicationContextTests { assertThat(bean.getRequest()).isNotNull(); }); this.context.refresh(); - String output = this.output.toString().substring(initialOutputLength); + String output = capturedOutput.toString().substring(initialOutputLength); assertThat(output).doesNotContain("Replacing scope"); } @Test - public void webApplicationScopeIsRegistered() throws Exception { + void webApplicationScopeIsRegistered() throws Exception { addWebServerFactoryBean(); this.context.refresh(); assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java index 2ae26d0bc15..91f3de42d6d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.web.servlet.context; import java.net.URI; import java.nio.charset.StandardCharsets; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; @@ -53,11 +53,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Ivan Sopov */ -public class ServletWebServerMvcIntegrationTests { +class ServletWebServerMvcIntegrationTests { private AnnotationConfigServletWebServerApplicationContext context; - @After + @AfterEach public void closeContext() { try { this.context.close(); @@ -68,25 +68,25 @@ public class ServletWebServerMvcIntegrationTests { } @Test - public void tomcat() throws Exception { + void tomcat() throws Exception { this.context = new AnnotationConfigServletWebServerApplicationContext(TomcatConfig.class); doTest(this.context, "/hello"); } @Test - public void jetty() throws Exception { + void jetty() throws Exception { this.context = new AnnotationConfigServletWebServerApplicationContext(JettyConfig.class); doTest(this.context, "/hello"); } @Test - public void undertow() throws Exception { + void undertow() throws Exception { this.context = new AnnotationConfigServletWebServerApplicationContext(UndertowConfig.class); doTest(this.context, "/hello"); } @Test - public void advancedConfig() throws Exception { + void advancedConfig() throws Exception { this.context = new AnnotationConfigServletWebServerApplicationContext(AdvancedConfig.class); doTest(this.context, "/example/spring/hello"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java index 1bb2b1ff4f6..9b8fab137da 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.servlet.context; import javax.servlet.Servlet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.servlet.server.MockServletWebServerFactory; import org.springframework.core.io.ClassPathResource; @@ -30,7 +30,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ -public class XmlServletWebServerApplicationContextTests { +class XmlServletWebServerApplicationContextTests { private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage().getName() .replace('.', '/') + "/"; @@ -40,25 +40,25 @@ public class XmlServletWebServerApplicationContextTests { private XmlServletWebServerApplicationContext context; @Test - public void createFromResource() { + void createFromResource() { this.context = new XmlServletWebServerApplicationContext(new ClassPathResource(FILE, getClass())); verifyContext(); } @Test - public void createFromResourceLocation() { + void createFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(PATH + FILE); verifyContext(); } @Test - public void createFromRelativeResourceLocation() { + void createFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(getClass(), FILE); verifyContext(); } @Test - public void loadAndRefreshFromResource() { + void loadAndRefreshFromResource() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(new ClassPathResource(FILE, getClass())); this.context.refresh(); @@ -66,7 +66,7 @@ public class XmlServletWebServerApplicationContextTests { } @Test - public void loadAndRefreshFromResourceLocation() { + void loadAndRefreshFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(PATH + FILE); this.context.refresh(); @@ -74,7 +74,7 @@ public class XmlServletWebServerApplicationContextTests { } @Test - public void loadAndRefreshFromRelativeResourceLocation() { + void loadAndRefreshFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(getClass(), FILE); this.context.refresh(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/config/ExampleServletWebServerApplicationConfiguration.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/config/ExampleServletWebServerApplicationConfiguration.java index 9cba8d077a8..2c8da4155f3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/config/ExampleServletWebServerApplicationConfiguration.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/config/ExampleServletWebServerApplicationConfiguration.java @@ -18,7 +18,6 @@ package org.springframework.boot.web.servlet.context.config; import javax.servlet.Servlet; -import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContextTests; import org.springframework.boot.web.servlet.mock.MockServlet; import org.springframework.boot.web.servlet.server.MockServletWebServerFactory; import org.springframework.context.annotation.Bean; @@ -26,7 +25,7 @@ import org.springframework.context.annotation.Configuration; /** * Example {@code @Configuration} for use with - * {@link AnnotationConfigServletWebServerApplicationContextTests}. + * {@code AnnotationConfigServletWebServerApplicationContextTests}. * * @author Phillip Webb */ diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java index 9442b0ef7a0..85438abcecd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java @@ -22,7 +22,7 @@ import java.util.Map; import javax.servlet.ServletException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; @@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Phillip Webb * @author Vedran Pavic */ -public class DefaultErrorAttributesTests { +class DefaultErrorAttributesTests { private DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(); @@ -52,13 +52,13 @@ public class DefaultErrorAttributesTests { private WebRequest webRequest = new ServletWebRequest(this.request); @Test - public void includeTimeStamp() { + void includeTimeStamp() { Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("timestamp")).isInstanceOf(Date.class); } @Test - public void specificStatusCode() { + void specificStatusCode() { this.request.setAttribute("javax.servlet.error.status_code", 404); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("error")).isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); @@ -66,14 +66,14 @@ public class DefaultErrorAttributesTests { } @Test - public void missingStatusCode() { + void missingStatusCode() { Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("error")).isEqualTo("None"); assertThat(attributes.get("status")).isEqualTo(999); } @Test - public void mvcError() { + void mvcError() { RuntimeException ex = new RuntimeException("Test"); ModelAndView modelAndView = this.errorAttributes.resolveException(this.request, null, null, ex); this.request.setAttribute("javax.servlet.error.exception", new RuntimeException("Ignored")); @@ -85,7 +85,7 @@ public class DefaultErrorAttributesTests { } @Test - public void servletError() { + void servletError() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); @@ -95,7 +95,7 @@ public class DefaultErrorAttributesTests { } @Test - public void servletMessage() { + void servletMessage() { this.request.setAttribute("javax.servlet.error.message", "Test"); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("exception")).isNull(); @@ -103,7 +103,7 @@ public class DefaultErrorAttributesTests { } @Test - public void nullMessage() { + void nullMessage() { this.request.setAttribute("javax.servlet.error.exception", new RuntimeException()); this.request.setAttribute("javax.servlet.error.message", "Test"); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); @@ -112,7 +112,7 @@ public class DefaultErrorAttributesTests { } @Test - public void unwrapServletException() { + void unwrapServletException() { RuntimeException ex = new RuntimeException("Test"); ServletException wrapped = new ServletException(new ServletException(ex)); this.request.setAttribute("javax.servlet.error.exception", wrapped); @@ -123,7 +123,7 @@ public class DefaultErrorAttributesTests { } @Test - public void getError() { + void getError() { Error error = new OutOfMemoryError("Test error"); this.request.setAttribute("javax.servlet.error.exception", error); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); @@ -133,7 +133,7 @@ public class DefaultErrorAttributesTests { } @Test - public void extractBindingResultErrors() { + void extractBindingResultErrors() { BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new BindException(bindingResult); @@ -141,7 +141,7 @@ public class DefaultErrorAttributesTests { } @Test - public void extractMethodArgumentNotValidExceptionBindingResultErrors() { + void extractMethodArgumentNotValidExceptionBindingResultErrors() { BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new MethodArgumentNotValidException(null, bindingResult); @@ -156,7 +156,7 @@ public class DefaultErrorAttributesTests { } @Test - public void withExceptionAttribute() { + void withExceptionAttribute() { DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(true); RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); @@ -166,7 +166,7 @@ public class DefaultErrorAttributesTests { } @Test - public void trace() { + void trace() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, true); @@ -174,7 +174,7 @@ public class DefaultErrorAttributesTests { } @Test - public void noTrace() { + void noTrace() { RuntimeException ex = new RuntimeException("Test"); this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); @@ -182,7 +182,7 @@ public class DefaultErrorAttributesTests { } @Test - public void path() { + void path() { this.request.setAttribute("javax.servlet.error.request_uri", "path"); Map attributes = this.errorAttributes.getErrorAttributes(this.webRequest, false); assertThat(attributes.get("path")).isEqualTo("path"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index 40c81855664..3ad43aa3647 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -78,16 +78,17 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.jasper.EmbeddedServletOptions; import org.apache.jasper.servlet.JspServlet; -import org.junit.After; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.InOrder; import org.springframework.boot.system.ApplicationHome; import org.springframework.boot.system.ApplicationTemp; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.testsupport.web.servlet.ExampleFilter; import org.springframework.boot.testsupport.web.servlet.ExampleServlet; import org.springframework.boot.web.server.Compression; @@ -119,8 +120,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; @@ -136,19 +136,17 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Raja Kolli */ +@ExtendWith(OutputCaptureExtension.class) public abstract class AbstractServletWebServerFactoryTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Rule - public OutputCapture output = new OutputCapture(); + @TempDir + protected File tempDir; protected WebServer webServer; private final HttpClientContext httpClientContext = HttpClientContext.create(); - @After + @AfterEach public void tearDown() { if (this.webServer != null) { try { @@ -161,7 +159,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void startServlet() throws Exception { + void startServlet() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -169,7 +167,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void startCalledTwice() throws Exception { + void startCalledTwice(CapturedOutput capturedOutput) throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -177,11 +175,11 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); assertThat(this.webServer.getPort()).isEqualTo(port); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); - assertThat(this.output.toString()).containsOnlyOnce("started on port"); + assertThat(capturedOutput).containsOnlyOnce("started on port"); } @Test - public void stopCalledTwice() { + void stopCalledTwice() { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -190,7 +188,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void emptyServerWhenPortIsMinusOne() { + void emptyServerWhenPortIsMinusOne() { AbstractServletWebServerFactory factory = getFactory(); factory.setPort(-1); this.webServer = factory.getWebServer(exampleServletRegistration()); @@ -199,7 +197,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void stopServlet() throws Exception { + void stopServlet() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -209,7 +207,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void startServletAndFilter() throws Exception { + void startServletAndFilter() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration(), new FilterRegistrationBean<>(new ExampleFilter())); @@ -218,7 +216,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void startBlocksUntilReadyToServe() { + void startBlocksUntilReadyToServe() { AbstractServletWebServerFactory factory = getFactory(); final Date[] date = new Date[1]; this.webServer = factory.getWebServer((servletContext) -> { @@ -235,7 +233,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void loadOnStartAfterContextIsInitialized() { + void loadOnStartAfterContextIsInitialized() { AbstractServletWebServerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); this.webServer = factory @@ -246,7 +244,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void specificPort() throws Exception { + void specificPort() throws Exception { AbstractServletWebServerFactory factory = getFactory(); int specificPort = SocketUtils.findAvailableTcpPort(41000); factory.setPort(specificPort); @@ -257,7 +255,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void specificContextRoot() throws Exception { + void specificContextRoot() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.setContextPath("/say"); this.webServer = factory.getWebServer(exampleServletRegistration()); @@ -266,34 +264,34 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void contextPathIsLoggedOnStartup() { + void contextPathIsLoggedOnStartup(CapturedOutput capturedOutput) { AbstractServletWebServerFactory factory = getFactory(); factory.setContextPath("/custom"); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); - assertThat(this.output.toString()).containsOnlyOnce("with context path '/custom'"); + assertThat(capturedOutput).containsOnlyOnce("with context path '/custom'"); } @Test - public void contextPathMustStartWithSlash() { + void contextPathMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("missingslash")) .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test - public void contextPathMustNotEndWithSlash() { + void contextPathMustNotEndWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("extraslash/")) .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test - public void contextRootPathMustNotBeSlash() { + void contextRootPathMustNotBeSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("/")) .withMessageContaining("Root ContextPath must be specified using an empty string"); } @Test - public void multipleConfigurations() throws Exception { + void multipleConfigurations() throws Exception { AbstractServletWebServerFactory factory = getFactory(); ServletContextInitializer[] initializers = new ServletContextInitializer[6]; Arrays.setAll(initializers, (i) -> mock(ServletContextInitializer.class)); @@ -308,7 +306,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void documentRoot() throws Exception { + void documentRoot() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); this.webServer = factory.getWebServer(); @@ -317,10 +315,10 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void mimeType() throws Exception { - FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.xxcss"))); + void mimeType() throws Exception { + FileCopyUtils.copy("test", new FileWriter(new File(this.tempDir, "test.xxcss"))); AbstractServletWebServerFactory factory = getFactory(); - factory.setDocumentRoot(this.temporaryFolder.getRoot()); + factory.setDocumentRoot(this.tempDir); MimeMappings mimeMappings = new MimeMappings(); mimeMappings.add("xxcss", "text/css"); factory.setMimeMappings(mimeMappings); @@ -332,7 +330,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void errorPage() throws Exception { + void errorPage() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); this.webServer = factory.getWebServer(exampleServletRegistration(), errorServletRegistration()); @@ -342,7 +340,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void errorPageFromPutRequest() throws Exception { + void errorPageFromPutRequest() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello")); this.webServer = factory.getWebServer(exampleServletRegistration(), errorServletRegistration()); @@ -352,17 +350,17 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void basicSslFromClassPath() throws Exception { + void basicSslFromClassPath() throws Exception { testBasicSslWithKeyStore("classpath:test.jks"); } @Test - public void basicSslFromFileSystem() throws Exception { + void basicSslFromFileSystem() throws Exception { testBasicSslWithKeyStore("src/test/resources/test.jks"); } @Test - public void sslDisabled() throws Exception { + void sslDisabled() throws Exception { AbstractServletWebServerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); @@ -378,7 +376,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslGetScheme() throws Exception { // gh-2232 + void sslGetScheme() throws Exception { // gh-2232 AbstractServletWebServerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); @@ -391,7 +389,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslKeyAlias() throws Exception { + void sslKeyAlias() throws Exception { AbstractServletWebServerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "test-alias", "src/test/resources/test.jks"); factory.setSsl(ssl); @@ -409,7 +407,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void serverHeaderIsDisabledByDefaultWhenUsingSsl() throws Exception { + void serverHeaderIsDisabledByDefaultWhenUsingSsl() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); @@ -423,7 +421,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void serverHeaderCanBeCustomizedWhenUsingSsl() throws Exception { + void serverHeaderCanBeCustomizedWhenUsingSsl() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.setServerHeader("MyServer"); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); @@ -451,7 +449,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void pkcs12KeyStoreAndTrustStore() throws Exception { + void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); @@ -468,7 +466,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { + void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); @@ -485,7 +483,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { + void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); @@ -500,7 +498,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { + void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl( @@ -518,7 +516,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { + void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); @@ -532,7 +530,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslWithCustomSslStoreProvider() throws Exception { + void sslWithCustomSslStoreProvider() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); Ssl ssl = new Ssl(); @@ -558,7 +556,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void disableJspServletRegistration() throws Exception { + void disableJspServletRegistration() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.getJsp().setRegistered(false); this.webServer = factory.getWebServer(); @@ -566,7 +564,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void cannotReadClassPathFiles() throws Exception { + void cannotReadClassPathFiles() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -634,12 +632,12 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void defaultSessionTimeout() { + void defaultSessionTimeout() { assertThat(getFactory().getSession().getTimeout()).isEqualTo(Duration.ofMinutes(30)); } @Test - public void persistSession() throws Exception { + void persistSession() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setPersistent(true); this.webServer = factory.getWebServer(sessionServletRegistration()); @@ -656,9 +654,10 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void persistSessionInSpecificSessionStoreDir() throws Exception { + void persistSessionInSpecificSessionStoreDir() throws Exception { AbstractServletWebServerFactory factory = getFactory(); - File sessionStoreDir = this.temporaryFolder.newFolder(); + File sessionStoreDir = new File(this.tempDir, "sessions"); + sessionStoreDir.mkdir(); factory.getSession().setPersistent(true); factory.getSession().setStoreDir(sessionStoreDir); this.webServer = factory.getWebServer(sessionServletRegistration()); @@ -670,7 +669,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void getValidSessionStoreWhenSessionStoreNotSet() { + void getValidSessionStoreWhenSessionStoreNotSet() { AbstractServletWebServerFactory factory = getFactory(); File dir = factory.getValidSessionStoreDir(false); assertThat(dir.getName()).isEqualTo("servlet-sessions"); @@ -678,7 +677,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void getValidSessionStoreWhenSessionStoreIsRelative() { + void getValidSessionStoreWhenSessionStoreIsRelative() { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setStoreDir(new File("sessions")); File dir = factory.getValidSessionStoreDir(false); @@ -687,15 +686,17 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void getValidSessionStoreWhenSessionStoreReferencesFile() throws Exception { + void getValidSessionStoreWhenSessionStoreReferencesFile() throws Exception { AbstractServletWebServerFactory factory = getFactory(); - factory.getSession().setStoreDir(this.temporaryFolder.newFile()); + File file = new File(this.tempDir, "file"); + file.createNewFile(); + factory.getSession().setStoreDir(file); assertThatIllegalStateException().isThrownBy(() -> factory.getValidSessionStoreDir(false)) .withMessageContaining("points to a file"); } @Test - public void sessionCookieConfiguration() { + void sessionCookieConfiguration() { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().getCookie().setName("testname"); factory.getSession().getCookie().setDomain("testdomain"); @@ -717,7 +718,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sslSessionTracking() { + void sslSessionTracking() { AbstractServletWebServerFactory factory = getFactory(); Ssl ssl = new Ssl(); ssl.setEnabled(true); @@ -732,33 +733,33 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void compressionOfResponseToGetRequest() throws Exception { + void compressionOfResponseToGetRequest() throws Exception { assertThat(doTestCompression(10000, null, null)).isTrue(); } @Test - public void compressionOfResponseToPostRequest() throws Exception { + void compressionOfResponseToPostRequest() throws Exception { assertThat(doTestCompression(10000, null, null, HttpMethod.POST)).isTrue(); } @Test - public void noCompressionForSmallResponse() throws Exception { + void noCompressionForSmallResponse() throws Exception { assertThat(doTestCompression(100, null, null)).isFalse(); } @Test - public void noCompressionForMimeType() throws Exception { + void noCompressionForMimeType() throws Exception { String[] mimeTypes = new String[] { "text/html", "text/xml", "text/css" }; assertThat(doTestCompression(10000, mimeTypes, null)).isFalse(); } @Test - public void noCompressionForUserAgent() throws Exception { + void noCompressionForUserAgent() throws Exception { assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })).isFalse(); } @Test - public void compressionWithoutContentSizeHeader() throws Exception { + void compressionWithoutContentSizeHeader() throws Exception { AbstractServletWebServerFactory factory = getFactory(); Compression compression = new Compression(); compression.setEnabled(true); @@ -774,7 +775,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void mimeMappingsAreCorrectlyConfigured() { + void mimeMappingsAreCorrectlyConfigured() { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(); Map configuredMimeMappings = getActualMimeMappings(); @@ -788,7 +789,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void rootServletContextResource() { + void rootServletContextResource() { AbstractServletWebServerFactory factory = getFactory(); final AtomicReference rootResource = new AtomicReference<>(); this.webServer = factory.getWebServer((servletContext) -> { @@ -804,7 +805,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void customServerHeader() throws Exception { + void customServerHeader() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.setServerHeader("MyServer"); this.webServer = factory.getWebServer(exampleServletRegistration()); @@ -814,7 +815,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void serverHeaderIsDisabledByDefault() throws Exception { + void serverHeaderIsDisabledByDefault() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -823,7 +824,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { + protected void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); @@ -835,7 +836,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { + void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); @@ -847,7 +848,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void localeCharsetMappingsAreConfigured() { + void localeCharsetMappingsAreConfigured() { AbstractServletWebServerFactory factory = getFactory(); Map mappings = new HashMap<>(); mappings.put(Locale.GERMAN, StandardCharsets.UTF_8); @@ -858,29 +859,29 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void jspServletInitParameters() throws Exception { + void jspServletInitParameters() throws Exception { Map initParameters = new HashMap<>(); initParameters.put("a", "alpha"); AbstractServletWebServerFactory factory = getFactory(); factory.getJsp().setInitParameters(initParameters); this.webServer = factory.getWebServer(); - Assume.assumeThat(getJspServlet(), notNullValue()); + Assumptions.assumeFalse(getJspServlet() == null); JspServlet jspServlet = getJspServlet(); assertThat(jspServlet.getInitParameter("a")).isEqualTo("alpha"); } @Test - public void jspServletIsNotInDevelopmentModeByDefault() throws Exception { + void jspServletIsNotInDevelopmentModeByDefault() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(); - Assume.assumeThat(getJspServlet(), notNullValue()); + Assumptions.assumeFalse(getJspServlet() == null); JspServlet jspServlet = getJspServlet(); EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils.getField(jspServlet, "options"); assertThat(options.getDevelopment()).isFalse(); } @Test - public void faultyFilterCausesStartFailure() { + void faultyFilterCausesStartFailure() { AbstractServletWebServerFactory factory = getFactory(); factory.addInitializers((servletContext) -> servletContext.addFilter("faulty", new Filter() { @@ -904,7 +905,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void sessionConfiguration() { + void sessionConfiguration() { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setTimeout(Duration.ofSeconds(123)); factory.getSession().setTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)); @@ -930,7 +931,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() throws Exception { + void servletContextListenerContextDestroyedIsCalledWhenContainerIsStopped() throws Exception { ServletContextListener listener = mock(ServletContextListener.class); this.webServer = getFactory().getWebServer((servletContext) -> servletContext.addListener(listener)); this.webServer.start(); @@ -939,7 +940,7 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void exceptionThrownOnLoadFailureIsRethrown() { + void exceptionThrownOnLoadFailureIsRethrown() { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); @@ -955,6 +956,7 @@ public abstract class AbstractServletWebServerFactoryTests { } cause = cause.getCause(); } + fail("Exception did not wrap FailingServletException"); } @@ -1019,8 +1021,8 @@ public abstract class AbstractServletWebServerFactoryTests { protected abstract Charset getCharset(Locale locale); private void addTestTxtFile(AbstractServletWebServerFactory factory) throws IOException { - FileCopyUtils.copy("test", new FileWriter(this.temporaryFolder.newFile("test.txt"))); - factory.setDocumentRoot(this.temporaryFolder.getRoot()); + FileCopyUtils.copy("test", new FileWriter(new File(this.tempDir, "test.txt"))); + factory.setDocumentRoot(this.tempDir); } protected String getLocalUrl(String resourcePath) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java index 4de37f5536e..bbe4f49ac9c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/DocumentRootTests.java @@ -22,9 +22,8 @@ import java.security.CodeSource; import java.security.cert.Certificate; import org.apache.commons.logging.LogFactory; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -33,36 +32,38 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Phillip Webb */ -public class DocumentRootTests { +class DocumentRootTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; private DocumentRoot documentRoot = new DocumentRoot(LogFactory.getLog(getClass())); @Test - public void explodedWarFileDocumentRootWhenRunningFromExplodedWar() throws Exception { - File webInfClasses = this.temporaryFolder.newFolder("test.war", "WEB-INF", "lib", "spring-boot.jar"); - File directory = this.documentRoot.getExplodedWarFileDocumentRoot(webInfClasses); - assertThat(directory).isEqualTo(webInfClasses.getParentFile().getParentFile().getParentFile()); + void explodedWarFileDocumentRootWhenRunningFromExplodedWar() throws Exception { + File codeSourceFile = new File(this.tempDir, "test.war/WEB-INF/lib/spring-boot.jar"); + codeSourceFile.getParentFile().mkdirs(); + codeSourceFile.createNewFile(); + File directory = this.documentRoot.getExplodedWarFileDocumentRoot(codeSourceFile); + assertThat(directory).isEqualTo(codeSourceFile.getParentFile().getParentFile().getParentFile()); } @Test - public void explodedWarFileDocumentRootWhenRunningFromPackagedWar() throws Exception { - File codeSourceFile = this.temporaryFolder.newFile("test.war"); + void explodedWarFileDocumentRootWhenRunningFromPackagedWar() throws Exception { + File codeSourceFile = new File(this.tempDir, "test.war"); File directory = this.documentRoot.getExplodedWarFileDocumentRoot(codeSourceFile); assertThat(directory).isNull(); } @Test - public void codeSourceArchivePath() throws Exception { + void codeSourceArchivePath() throws Exception { CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/some/test/path/")); } @Test - public void codeSourceArchivePathContainingSpaces() throws Exception { + void codeSourceArchivePathContainingSpaces() throws Exception { CodeSource codeSource = new CodeSource(new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/test/path/with space/")); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java index f63ba3e1185..b95731436e9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/StaticResourceJarsTests.java @@ -25,9 +25,8 @@ import java.util.function.Consumer; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; @@ -37,41 +36,41 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Rupert Madden-Abbott * @author Andy Wilkinson */ -public class StaticResourceJarsTests { +class StaticResourceJarsTests { - @Rule - public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File tempDir; @Test - public void includeJarWithStaticResources() throws Exception { + void includeJarWithStaticResources() throws Exception { File jarFile = createResourcesJar("test-resources.jar"); List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test - public void includeJarWithStaticResourcesWithUrlEncodedSpaces() throws Exception { + void includeJarWithStaticResourcesWithUrlEncodedSpaces() throws Exception { File jarFile = createResourcesJar("test resources.jar"); List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test - public void includeJarWithStaticResourcesWithPlusInItsPath() throws Exception { + void includeJarWithStaticResourcesWithPlusInItsPath() throws Exception { File jarFile = createResourcesJar("test + resources.jar"); List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(1); } @Test - public void excludeJarWithoutStaticResources() throws Exception { + void excludeJarWithoutStaticResources() throws Exception { File jarFile = createJar("dependency.jar"); List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL()); assertThat(staticResourceJarUrls).hasSize(0); } @Test - public void uncPathsAreTolerated() throws Exception { + void uncPathsAreTolerated() throws Exception { File jarFile = createResourcesJar("test-resources.jar"); List staticResourceJarUrls = new StaticResourceJars().getUrlsFrom(jarFile.toURI().toURL(), new URL("file://unc.example.com/test.jar")); @@ -96,7 +95,7 @@ public class StaticResourceJarsTests { } private File createJar(String name, Consumer customizer) throws IOException { - File jarFile = this.temporaryFolder.newFile(name); + File jarFile = new File(this.tempDir, name); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile)); if (customizer != null) { customizer.accept(jarOutputStream); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java index b876f0b3ebc..c420d57824e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterIntegrationTests.java @@ -23,9 +23,9 @@ import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.xnio.channels.UnsupportedOptionException; import org.springframework.beans.factory.annotation.Autowired; @@ -42,7 +42,7 @@ import org.springframework.stereotype.Controller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.MergedContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.support.AbstractContextLoader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @@ -63,11 +63,11 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Phillip Webb */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @DirtiesContext @ContextConfiguration(classes = ErrorPageFilterIntegrationTests.TomcatConfig.class, loader = EmbeddedWebContextLoader.class) -public class ErrorPageFilterIntegrationTests { +class ErrorPageFilterIntegrationTests { @Autowired private HelloWorldController controller; @@ -75,19 +75,19 @@ public class ErrorPageFilterIntegrationTests { @Autowired private AnnotationConfigServletWebServerApplicationContext context; - @After + @AfterEach public void init() { this.controller.reset(); } @Test - public void created() throws Exception { + void created() throws Exception { doTest(this.context, "/create", HttpStatus.CREATED); assertThat(this.controller.getStatus()).isEqualTo(201); } @Test - public void ok() throws Exception { + void ok() throws Exception { doTest(this.context, "/hello", HttpStatus.OK); assertThat(this.controller.getStatus()).isEqualTo(200); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java index 2b1418c33ff..c2ee16ca420 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java @@ -31,10 +31,11 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.apache.catalina.connector.ClientAbortException; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.server.ErrorPage; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockFilterChain; @@ -60,7 +61,8 @@ import static org.mockito.Mockito.verify; * @author Dave Syer * @author Andy Wilkinson */ -public class ErrorPageFilterTests { +@ExtendWith(OutputCaptureExtension.class) +class ErrorPageFilterTests { private ErrorPageFilter filter = new ErrorPageFilter(); @@ -71,11 +73,8 @@ public class ErrorPageFilterTests { private MockFilterChain chain = new TestFilterChain((request, response, chain) -> { }); - @Rule - public OutputCapture output = new OutputCapture(); - @Test - public void notAnError() throws Exception { + void notAnError() throws Exception { this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response); @@ -84,7 +83,7 @@ public class ErrorPageFilterTests { } @Test - public void notAnErrorButNotOK() throws Exception { + void notAnErrorButNotOK() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> { response.setStatus(201); chain.call(); @@ -98,7 +97,7 @@ public class ErrorPageFilterTests { } @Test - public void unauthorizedWithErrorPath() throws Exception { + void unauthorizedWithErrorPath() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new TestFilterChain((request, response, chain) -> response.sendError(401, "UNAUTHORIZED")); this.filter.doFilter(this.request, this.response, this.chain); @@ -113,7 +112,7 @@ public class ErrorPageFilterTests { } @Test - public void responseCommitted() throws Exception { + void responseCommitted() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.response.setCommitted(true); this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); @@ -126,7 +125,7 @@ public class ErrorPageFilterTests { } @Test - public void responseCommittedWhenFromClientAbortException() throws Exception { + void responseCommittedWhenFromClientAbortException(CapturedOutput capturedOutput) throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.response.setCommitted(true); this.chain = new TestFilterChain((request, response, chain) -> { @@ -135,11 +134,11 @@ public class ErrorPageFilterTests { }); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.response.isCommitted()).isTrue(); - assertThat(this.output.toString()).doesNotContain("Cannot forward"); + assertThat(capturedOutput).doesNotContain("Cannot forward"); } @Test - public void responseUncommittedWithoutErrorPage() throws Exception { + void responseUncommittedWithoutErrorPage() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); @@ -150,7 +149,7 @@ public class ErrorPageFilterTests { } @Test - public void oncePerRequest() throws Exception { + void oncePerRequest() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> { response.sendError(400, "BAD"); assertThat(request.getAttribute("FILTER.FILTERED")).isNotNull(); @@ -160,7 +159,7 @@ public class ErrorPageFilterTests { } @Test - public void globalError() throws Exception { + void globalError() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); @@ -173,7 +172,7 @@ public class ErrorPageFilterTests { } @Test - public void statusError() throws Exception { + void statusError() throws Exception { this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.chain = new TestFilterChain((request, response, chain) -> response.sendError(400, "BAD")); this.filter.doFilter(this.request, this.response, this.chain); @@ -186,7 +185,7 @@ public class ErrorPageFilterTests { } @Test - public void statusErrorWithCommittedResponse() throws Exception { + void statusErrorWithCommittedResponse() throws Exception { this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.chain = new TestFilterChain((request, response, chain) -> { response.sendError(400, "BAD"); @@ -199,7 +198,7 @@ public class ErrorPageFilterTests { } @Test - public void exceptionError() throws Exception { + void exceptionError() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new TestFilterChain((request, response, chain) -> { chain.call(); @@ -220,7 +219,7 @@ public class ErrorPageFilterTests { } @Test - public void exceptionErrorWithCommittedResponse() throws Exception { + void exceptionErrorWithCommittedResponse() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new TestFilterChain((request, response, chain) -> { chain.call(); @@ -232,14 +231,14 @@ public class ErrorPageFilterTests { } @Test - public void statusCode() throws Exception { + void statusCode() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> assertThat(response.getStatus()).isEqualTo(200)); this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(200); } @Test - public void subClassExceptionError() throws Exception { + void subClassExceptionError() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new TestFilterChain((request, response, chain) -> { chain.call(); @@ -260,7 +259,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsNotCommittedWhenRequestIsAsync() throws Exception { + void responseIsNotCommittedWhenRequestIsAsync() throws Exception { this.request.setAsyncStarted(true); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); @@ -269,7 +268,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() throws Exception { + void responseIsCommittedWhenRequestIsAsyncAndExceptionIsThrown() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new TestFilterChain((request, response, chain) -> { @@ -283,7 +282,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() throws Exception { + void responseIsCommittedWhenRequestIsAsyncAndStatusIs400Plus() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); this.request.setAsyncStarted(true); this.chain = new TestFilterChain((request, response, chain) -> { @@ -297,7 +296,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsNotCommittedDuringAsyncDispatch() throws Exception { + void responseIsNotCommittedDuringAsyncDispatch() throws Exception { setUpAsyncDispatch(); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.chain.getRequest()).isEqualTo(this.request); @@ -306,7 +305,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() throws Exception { + void responseIsCommittedWhenExceptionIsThrownDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new TestFilterChain((request, response, chain) -> { @@ -320,7 +319,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() throws Exception { + void responseIsCommittedWhenStatusIs400PlusDuringAsyncDispatch() throws Exception { this.filter.addErrorPages(new ErrorPage("/error")); setUpAsyncDispatch(); this.chain = new TestFilterChain((request, response, chain) -> { @@ -334,7 +333,7 @@ public class ErrorPageFilterTests { } @Test - public void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() throws Exception { + void responseIsNotFlushedIfStatusIsLessThan400AndItHasAlreadyBeenCommitted() throws Exception { HttpServletResponse committedResponse = mock(HttpServletResponse.class); given(committedResponse.isCommitted()).willReturn(true); given(committedResponse.getStatus()).willReturn(200); @@ -343,7 +342,7 @@ public class ErrorPageFilterTests { } @Test - public void errorMessageForRequestWithoutPathInfo() throws IOException, ServletException { + void errorMessageForRequestWithoutPathInfo(CapturedOutput capturedOutput) throws IOException, ServletException { this.request.setServletPath("/test"); this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new TestFilterChain((request, response, chain) -> { @@ -351,11 +350,11 @@ public class ErrorPageFilterTests { throw new RuntimeException(); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.output.toString()).contains("request [/test]"); + assertThat(capturedOutput).contains("request [/test]"); } @Test - public void errorMessageForRequestWithPathInfo() throws IOException, ServletException { + void errorMessageForRequestWithPathInfo(CapturedOutput capturedOutput) throws IOException, ServletException { this.request.setServletPath("/test"); this.request.setPathInfo("/alpha"); this.filter.addErrorPages(new ErrorPage("/error")); @@ -364,11 +363,11 @@ public class ErrorPageFilterTests { throw new RuntimeException(); }); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.output.toString()).contains("request [/test/alpha]"); + assertThat(capturedOutput).contains("request [/test/alpha]"); } @Test - public void nestedServletExceptionIsUnwrapped() throws Exception { + void nestedServletExceptionIsUnwrapped() throws Exception { this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.chain = new TestFilterChain((request, response, chain) -> { chain.call(); @@ -389,7 +388,7 @@ public class ErrorPageFilterTests { } @Test - public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() throws Exception { + void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() throws Exception { this.chain = new TestFilterChain((request, response, chain) -> { response.sendError(400); response.getWriter().flush(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java index ea00be7c98c..557ddeb9d2a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.web.servlet.support; import javax.servlet.ServletContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.WebApplicationContext; @@ -32,27 +32,27 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class ServletContextApplicationContextInitializerTests { +class ServletContextApplicationContextInitializerTests { private final ServletContext servletContext = mock(ServletContext.class); private final ConfigurableWebApplicationContext applicationContext = mock(ConfigurableWebApplicationContext.class); @Test - public void servletContextIsSetOnTheApplicationContext() { + void servletContextIsSetOnTheApplicationContext() { new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); verify(this.applicationContext).setServletContext(this.servletContext); } @Test - public void applicationContextIsNotStoredInServletContextByDefault() { + void applicationContextIsNotStoredInServletContextByDefault() { new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); verify(this.servletContext, never()).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } @Test - public void applicationContextCanBeStoredInServletContext() { + void applicationContextCanBeStoredInServletContext() { new ServletContextApplicationContextInitializer(this.servletContext, true).initialize(this.applicationContext); verify(this.servletContext).setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index bb7d8a85102..15a2d19726d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -20,14 +20,15 @@ import java.util.Collections; import javax.servlet.ServletContext; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.boot.testsupport.rule.OutputCapture; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.WebServer; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; @@ -52,22 +53,20 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb * @author Andy Wilkinson */ -public class SpringBootServletInitializerTests { - - @Rule - public OutputCapture output = new OutputCapture(); +@ExtendWith(OutputCaptureExtension.class) +class SpringBootServletInitializerTests { private ServletContext servletContext = new MockServletContext(); private SpringApplication application; - @After - public void verifyLoggingOutput() { - assertThat(this.output.toString()).doesNotContain(StandardServletEnvironment.class.getSimpleName()); + @AfterEach + public void verifyLoggingOutput(CapturedOutput capturedOutput) { + assertThat(capturedOutput).doesNotContain(StandardServletEnvironment.class.getSimpleName()); } @Test - public void failsWithoutConfigure() { + void failsWithoutConfigure() { assertThatIllegalStateException() .isThrownBy( () -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) @@ -75,34 +74,34 @@ public class SpringBootServletInitializerTests { } @Test - public void withConfigurationAnnotation() { + void withConfigurationAnnotation() { new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); assertThat(this.application.getAllSources()).containsOnly(WithConfigurationAnnotation.class, ErrorPageFilterConfiguration.class); } @Test - public void withConfiguredSource() { + void withConfiguredSource() { new WithConfiguredSource().createRootApplicationContext(this.servletContext); assertThat(this.application.getAllSources()).containsOnly(Config.class, ErrorPageFilterConfiguration.class); } @Test - public void applicationBuilderCanBeCustomized() { + void applicationBuilderCanBeCustomized() { CustomSpringBootServletInitializer servletInitializer = new CustomSpringBootServletInitializer(); servletInitializer.createRootApplicationContext(this.servletContext); assertThat(servletInitializer.applicationBuilder.built).isTrue(); } @Test - public void mainClassHasSensibleDefault() { + void mainClassHasSensibleDefault() { new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); assertThat(this.application).hasFieldOrPropertyWithValue("mainApplicationClass", WithConfigurationAnnotation.class); } @Test - public void errorPageFilterRegistrationCanBeDisabled() { + void errorPageFilterRegistrationCanBeDisabled() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() .createRootApplicationContext(servletContext)) { @@ -118,14 +117,14 @@ public class SpringBootServletInitializerTests { } @Test - public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() { + void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() { try (ConfigurableApplicationContext context = new SpringApplication(ExecutableWar.class).run()) { assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } } @Test - public void servletContextPropertySourceIsAvailablePriorToRefresh() { + void servletContextPropertySourceIsAvailablePriorToRefresh() { ServletContext servletContext = mock(ServletContext.class); given(servletContext.getInitParameterNames()) .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java index 0fdedf45434..af316e5f30e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewResolverTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.web.servlet.view; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.web.MockServletContext; @@ -31,13 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer * @author Andy Wilkinson */ -public class MustacheViewResolverTests { +class MustacheViewResolverTests { private final String prefix = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/"; private MustacheViewResolver resolver = new MustacheViewResolver(); - @Before + @BeforeEach public void init() { GenericApplicationContext applicationContext = new GenericApplicationContext(); applicationContext.refresh(); @@ -48,17 +48,17 @@ public class MustacheViewResolverTests { } @Test - public void resolveNonExistent() throws Exception { + void resolveNonExistent() throws Exception { assertThat(this.resolver.resolveViewName("bar", null)).isNull(); } @Test - public void resolveExisting() throws Exception { + void resolveExisting() throws Exception { assertThat(this.resolver.resolveViewName("template", null)).isNotNull(); } @Test - public void setsContentType() throws Exception { + void setsContentType() throws Exception { this.resolver.setContentType("application/octet-stream"); View view = this.resolver.resolveViewName("template", null); assertThat(view.getContentType()).isEqualTo("application/octet-stream"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java index 98566d8a0a2..c6daddaa742 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/MustacheViewTests.java @@ -19,8 +19,8 @@ package org.springframework.boot.web.servlet.view; import java.util.Collections; import com.samskivert.mustache.Mustache; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Dave Syer */ -public class MustacheViewTests { +class MustacheViewTests { private final String templateUrl = "classpath:/" + getClass().getPackage().getName().replace(".", "/") + "/template.html"; @@ -46,7 +46,7 @@ public class MustacheViewTests { private AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); - @Before + @BeforeEach public void init() { this.context.refresh(); MockServletContext servletContext = new MockServletContext(); @@ -55,7 +55,7 @@ public class MustacheViewTests { } @Test - public void viewResolvesHandlebars() throws Exception { + void viewResolvesHandlebars() throws Exception { MustacheView view = new MustacheView(); view.setCompiler(Mustache.compiler()); view.setUrl(this.templateUrl); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java index c4492838a20..8a625255f96 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.webservices.client; import java.time.Duration; import org.apache.http.client.config.RequestConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -36,10 +36,10 @@ import static org.mockito.Mockito.mock; * * @author Stephane Nicoll */ -public class HttpWebServiceMessageSenderBuilderTests { +class HttpWebServiceMessageSenderBuilderTests { @Test - public void buildWithRequestFactorySupplier() { + void buildWithRequestFactorySupplier() { ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class); ClientHttpRequestMessageSender messageSender = build( new HttpWebServiceMessageSenderBuilder().requestFactory(() -> requestFactory)); @@ -47,7 +47,7 @@ public class HttpWebServiceMessageSenderBuilderTests { } @Test - public void buildWithReadAndConnectTimeout() { + void buildWithReadAndConnectTimeout() { ClientHttpRequestMessageSender messageSender = build( new HttpWebServiceMessageSenderBuilder().requestFactory(SimpleClientHttpRequestFactory::new) .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); @@ -58,7 +58,7 @@ public class HttpWebServiceMessageSenderBuilderTests { } @Test - public void buildUsesHttpComponentsByDefault() { + void buildUsesHttpComponentsByDefault() { ClientHttpRequestMessageSender messageSender = build(new HttpWebServiceMessageSenderBuilder() .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java index bce8787e7cf..87314337599 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java @@ -23,8 +23,8 @@ import java.util.Set; import javax.xml.transform.sax.SAXTransformerFactory; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -56,7 +56,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Stephane Nicoll * @author Dmytro Nosan */ -public class WebServiceTemplateBuilderTests { +class WebServiceTemplateBuilderTests { private final WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder(); @@ -66,20 +66,20 @@ public class WebServiceTemplateBuilderTests { @Mock private ClientInterceptor interceptor; - @Before + @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); } @Test - public void createWithCustomizersShouldApplyCustomizers() { + void createWithCustomizersShouldApplyCustomizers() { WebServiceTemplateCustomizer customizer = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = new WebServiceTemplateBuilder(customizer).build(); verify(customizer).customize(template); } @Test - public void buildShouldDetectHttpMessageSender() { + void buildShouldDetectHttpMessageSender() { WebServiceTemplate webServiceTemplate = this.builder.build(); assertThat(webServiceTemplate.getMessageSenders()).hasSize(1); WebServiceMessageSender messageSender = webServiceTemplate.getMessageSenders()[0]; @@ -87,55 +87,55 @@ public class WebServiceTemplateBuilderTests { } @Test - public void detectHttpMessageSenderWhenFalseShouldDisableDetection() { + void detectHttpMessageSenderWhenFalseShouldDisableDetection() { WebServiceTemplate webServiceTemplate = this.builder.detectHttpMessageSender(false).build(); assertThat(webServiceTemplate.getMessageSenders()).hasSize(1); assertThat(webServiceTemplate.getMessageSenders()[0]).isInstanceOf(HttpUrlConnectionMessageSender.class); } @Test - public void messageSendersWhenSendersAreAreNullShouldThrowException() { + void messageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) .withMessageContaining("MessageSenders must not be null"); } @Test - public void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { + void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.messageSenders((Collection) null)) .withMessageContaining("MessageSenders must not be null"); } @Test - public void messageSendersShouldApply() { + void messageSendersShouldApply() { WebServiceTemplate template = this.builder.messageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @Test - public void messageSendersShouldReplaceExisting() { + void messageSendersShouldReplaceExisting() { WebServiceTemplate template = this.builder.messageSenders(new ClientHttpRequestMessageSender()) .messageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @Test - public void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { + void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) .withMessageContaining("MessageSenders must not be null"); } @Test - public void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { + void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> this.builder.additionalMessageSenders((Collection) null)) .withMessageContaining("MessageSenders must not be null"); } @Test - public void additionalMessageSendersShouldAddToExisting() { + void additionalMessageSendersShouldAddToExisting() { ClientHttpRequestMessageSender httpMessageSender = new ClientHttpRequestMessageSender(); WebServiceTemplate template = this.builder.messageSenders(httpMessageSender) .additionalMessageSenders(this.messageSender).build(); @@ -143,54 +143,54 @@ public class WebServiceTemplateBuilderTests { } @Test - public void additionalMessageSendersShouldKeepDetectedHttpMessageSender() { + void additionalMessageSendersShouldKeepDetectedHttpMessageSender() { WebServiceTemplate template = this.builder.additionalMessageSenders(this.messageSender).build(); assertThat(template.getMessageSenders()).contains(this.messageSender); assertThat(template.getMessageSenders()).hasSize(2); } @Test - public void interceptorsWhenInterceptorsAreNullShouldThrowException() { + void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) .withMessageContaining("Interceptors must not be null"); } @Test - public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { + void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.interceptors((Collection) null)) .withMessageContaining("Interceptors must not be null"); } @Test - public void interceptorsShouldApply() { + void interceptorsShouldApply() { WebServiceTemplate template = this.builder.interceptors(this.interceptor).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test - public void interceptorsShouldReplaceExisting() { + void interceptorsShouldReplaceExisting() { WebServiceTemplate template = this.builder.interceptors(mock(ClientInterceptor.class)) .interceptors(Collections.singleton(this.interceptor)).build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test - public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { + void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) .withMessageContaining("Interceptors must not be null"); } @Test - public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { + void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) .withMessageContaining("Interceptors must not be null"); } @Test - public void additionalInterceptorsShouldAddToExisting() { + void additionalInterceptorsShouldAddToExisting() { ClientInterceptor interceptor = mock(ClientInterceptor.class); WebServiceTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor) .build(); @@ -198,7 +198,7 @@ public class WebServiceTemplateBuilderTests { } @Test - public void additionalInterceptorsShouldAddToExistingWebServiceTemplate() { + void additionalInterceptorsShouldAddToExistingWebServiceTemplate() { ClientInterceptor f1 = Mockito.mock(ClientInterceptor.class); ClientInterceptor f2 = Mockito.mock(ClientInterceptor.class); WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); @@ -208,28 +208,28 @@ public class WebServiceTemplateBuilderTests { } @Test - public void customizersWhenCustomizersAreNullShouldThrowException() { + void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { + void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.customizers((Collection) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void customizersShouldApply() { + void customizersShouldApply() { WebServiceTemplateCustomizer customizer = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer).build(); verify(customizer).customize(template); } @Test - public void customizersShouldBeAppliedLast() { + void customizersShouldBeAppliedLast() { WebServiceTemplate template = spy(new WebServiceTemplate()); this.builder .additionalCustomizers(((webServiceTemplate) -> verify(webServiceTemplate).setMessageSenders(any()))); @@ -237,7 +237,7 @@ public class WebServiceTemplateBuilderTests { } @Test - public void customizersShouldReplaceExisting() { + void customizersShouldReplaceExisting() { WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer1) @@ -247,21 +247,21 @@ public class WebServiceTemplateBuilderTests { } @Test - public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { + void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> this.builder.additionalCustomizers((Collection) null)) .withMessageContaining("Customizers must not be null"); } @Test - public void additionalCustomizersShouldAddToExisting() { + void additionalCustomizersShouldAddToExisting() { WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer1).additionalCustomizers(customizer2).build(); @@ -270,14 +270,14 @@ public class WebServiceTemplateBuilderTests { } @Test - public void setCheckConnectionForFault() { + void setCheckConnectionForFault() { WebServiceTemplate template = mock(WebServiceTemplate.class); this.builder.setCheckConnectionForFault(false).configure(template); verify(template).setCheckConnectionForFault(false); } @Test - public void setCheckConnectionForError() { + void setCheckConnectionForError() { WebServiceTemplate template = mock(WebServiceTemplate.class); this.builder.setCheckConnectionForError(false).configure(template); verify(template).setCheckConnectionForError(false); @@ -285,49 +285,49 @@ public class WebServiceTemplateBuilderTests { } @Test - public void setTransformerFactoryClass() { + void setTransformerFactoryClass() { WebServiceTemplate template = mock(WebServiceTemplate.class); this.builder.setTransformerFactoryClass(SAXTransformerFactory.class).configure(template); verify(template).setTransformerFactoryClass(SAXTransformerFactory.class); } @Test - public void setWebServiceMessageFactory() { + void setWebServiceMessageFactory() { WebServiceMessageFactory messageFactory = mock(WebServiceMessageFactory.class); WebServiceTemplate template = this.builder.setWebServiceMessageFactory(messageFactory).build(); assertThat(template.getMessageFactory()).isEqualTo(messageFactory); } @Test - public void setMarshaller() { + void setMarshaller() { Marshaller marshaller = mock(Marshaller.class); WebServiceTemplate template = this.builder.setMarshaller(marshaller).build(); assertThat(template.getMarshaller()).isEqualTo(marshaller); } @Test - public void setUnmarshaller() { + void setUnmarshaller() { Unmarshaller unmarshaller = mock(Unmarshaller.class); WebServiceTemplate webServiceTemplate = this.builder.setUnmarshaller(unmarshaller).build(); assertThat(webServiceTemplate.getUnmarshaller()).isEqualTo(unmarshaller); } @Test - public void setFaultMessageResolver() { + void setFaultMessageResolver() { FaultMessageResolver faultMessageResolver = mock(FaultMessageResolver.class); WebServiceTemplate webServiceTemplate = this.builder.setFaultMessageResolver(faultMessageResolver).build(); assertThat(webServiceTemplate.getFaultMessageResolver()).isEqualTo(faultMessageResolver); } @Test - public void setDefaultUri() { + void setDefaultUri() { URI uri = URI.create("http://localhost:8080"); WebServiceTemplate webServiceTemplate = this.builder.setDefaultUri(uri.toString()).build(); assertThat(webServiceTemplate.getDestinationProvider().getDestination()).isEqualTo(uri); } @Test - public void setDestinationProvider() { + void setDestinationProvider() { DestinationProvider destinationProvider = () -> URI.create("http://localhost:8080"); WebServiceTemplate webServiceTemplate = this.builder.setDestinationProvider(destinationProvider).build(); assertThat(webServiceTemplate.getDestinationProvider()).isEqualTo(destinationProvider); diff --git a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/SpringApplicationExtensionsTests.kt b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/SpringApplicationExtensionsTests.kt index f5a3c54db61..e35d774b5ba 100644 --- a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/SpringApplicationExtensionsTests.kt +++ b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/SpringApplicationExtensionsTests.kt @@ -19,7 +19,7 @@ import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue -import org.junit.Test +import org.junit.jupiter.api.Test import org.springframework.beans.factory.getBean import org.springframework.boot.web.servlet.server.MockServletWebServerFactory diff --git a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/KotlinConfigurationPropertiesBeanRegistrarTests.kt b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/KotlinConfigurationPropertiesBeanRegistrarTests.kt index 09fbf89da97..4e0940c53d3 100644 --- a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/KotlinConfigurationPropertiesBeanRegistrarTests.kt +++ b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/KotlinConfigurationPropertiesBeanRegistrarTests.kt @@ -1,7 +1,7 @@ package org.springframework.boot.context.properties import org.assertj.core.api.Assertions.assertThat -import org.junit.Test +import org.junit.jupiter.api.Test import org.springframework.beans.factory.support.DefaultListableBeanFactory import org.springframework.beans.factory.support.GenericBeanDefinition import org.springframework.core.type.AnnotationMetadata diff --git a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/bind/KotlinConstructorParametersBinderTests.kt b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/bind/KotlinConstructorParametersBinderTests.kt index 0ad27e24639..7db41f66de0 100644 --- a/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/bind/KotlinConstructorParametersBinderTests.kt +++ b/spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/bind/KotlinConstructorParametersBinderTests.kt @@ -1,7 +1,7 @@ package org.springframework.boot.context.properties.bind import org.assertj.core.api.Assertions.assertThat -import org.junit.Test +import org.junit.jupiter.api.Test import org.springframework.boot.context.properties.source.ConfigurationPropertyName import org.springframework.boot.context.properties.source.MockConfigurationPropertySource diff --git a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java index db06fc9738a..0812cd1bfe8 100644 --- a/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-parent-context/src/test/java/sample/parent/consumer/SampleIntegrationParentApplicationTests.java @@ -32,7 +32,7 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.util.StreamUtils; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Basic integration tests for service demo application. diff --git a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java index b4560af4496..ed2949f1ae4 100644 --- a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java +++ b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java @@ -16,7 +16,7 @@ package sample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; diff --git a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java index 9adc31cde44..069ffd3d3ae 100644 --- a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java +++ b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java @@ -18,7 +18,7 @@ package sample; import java.net.URI; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; diff --git a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java index 68930a30522..dfc5061a5ef 100644 --- a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java +++ b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java @@ -16,7 +16,7 @@ package sample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; diff --git a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java index d0fc90cac72..af7a3fa9f22 100644 --- a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java +++ b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java @@ -16,7 +16,7 @@ package sample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; diff --git a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wlp/src/test/java/sample/SampleWlpDeployApplicationIT.java b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wlp/src/test/java/sample/SampleWlpDeployApplicationIT.java index 883ec750572..3fbeac500f7 100644 --- a/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wlp/src/test/java/sample/SampleWlpDeployApplicationIT.java +++ b/spring-boot-tests/spring-boot-deployment-tests/spring-boot-deployment-test-wlp/src/test/java/sample/SampleWlpDeployApplicationIT.java @@ -16,7 +16,7 @@ package sample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java index bafe78c3da4..ae561e538bd 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-configuration-processor-tests/src/test/java/org/springframework/boot/configurationprocessor/tests/ConfigurationProcessorIntegrationTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.configurationprocessor.tests; import java.io.IOException; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepository; @@ -34,11 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConfigurationProcessorIntegrationTests { +class ConfigurationProcessorIntegrationTests { private static ConfigurationMetadataRepository repository; - @BeforeClass + @BeforeAll public static void readMetadata() throws IOException { Resource resource = new ClassPathResource("META-INF/spring-configuration-metadata.json"); assertThat(resource.exists()).isTrue(); @@ -49,7 +49,7 @@ public class ConfigurationProcessorIntegrationTests { } @Test - public void extractTypeFromAnnotatedGetter() { + void extractTypeFromAnnotatedGetter() { ConfigurationMetadataProperty property = repository.getAllProperties().get("annotated.name"); assertThat(property).isNotNull(); assertThat(property.getType()).isEqualTo("java.lang.String"); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java index 322ea877898..936c3722dd7 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java @@ -28,15 +28,11 @@ import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.DynamicType.Builder; import net.bytebuddy.implementation.FixedValue; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.testsupport.BuildOutput; @@ -52,41 +48,34 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) public class DevToolsIntegrationTests { - @ClassRule - public static final TemporaryFolder temp = new TemporaryFolder(); + @TempDir + static File temp; private static final BuildOutput buildOutput = new BuildOutput(DevToolsIntegrationTests.class); private LaunchedApplication launchedApplication; - private final File serverPortFile; + private final File serverPortFile = new File(buildOutput.getRootLocation(), "server.port"); - private final ApplicationLauncher applicationLauncher; + @RegisterExtension + final JvmLauncher javaLauncher = new JvmLauncher(); - @Rule - public JvmLauncher javaLauncher = new JvmLauncher(); - - public DevToolsIntegrationTests(ApplicationLauncher applicationLauncher) { - this.applicationLauncher = applicationLauncher; - this.serverPortFile = new File(DevToolsIntegrationTests.buildOutput.getRootLocation(), "server.port"); - } - - @Before - public void launchApplication() throws Exception { + private void launchApplication(ApplicationLauncher applicationLauncher) throws Exception { this.serverPortFile.delete(); - this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile); + this.launchedApplication = applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile); } - @After + @AfterEach public void stopApplication() throws InterruptedException { this.launchedApplication.stop(); } - @Test - public void addARequestMappingToAnExistingController() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void addARequestMappingToAnExistingController(ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -98,8 +87,11 @@ public class DevToolsIntegrationTests { assertThat(template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); } - @Test - public void removeARequestMappingFromAnExistingController() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void removeARequestMappingFromAnExistingController(ApplicationLauncher applicationLauncher) + throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -109,8 +101,10 @@ public class DevToolsIntegrationTests { .isEqualTo(HttpStatus.NOT_FOUND); } - @Test - public void createAController() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void createAController(ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -123,8 +117,10 @@ public class DevToolsIntegrationTests { } - @Test - public void createAControllerAndThenAddARequestMapping() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void createAControllerAndThenAddARequestMapping(ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -139,8 +135,11 @@ public class DevToolsIntegrationTests { assertThat(template.getForObject(urlBase + "/three", String.class)).isEqualTo("three"); } - @Test - public void createAControllerAndThenAddARequestMappingToAnExistingController() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void createAControllerAndThenAddARequestMappingToAnExistingController( + ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -157,8 +156,10 @@ public class DevToolsIntegrationTests { assertThat(template.getForObject(urlBase + "/three", String.class)).isEqualTo("three"); } - @Test - public void deleteAController() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void deleteAController(ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -170,8 +171,10 @@ public class DevToolsIntegrationTests { } - @Test - public void createAControllerAndThenDeleteIt() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void createAControllerAndThenDeleteIt(ApplicationLauncher applicationLauncher) throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -215,8 +218,7 @@ public class DevToolsIntegrationTests { return new ControllerBuilder(name, this.launchedApplication.getClassesDirectory()); } - @Parameters(name = "{0}") - public static Object[] parameters() throws IOException { + static Object[] parameters() throws IOException { Directories directories = new Directories(buildOutput, temp); return new Object[] { new Object[] { new LocalApplicationLauncher(directories) }, new Object[] { new ExplodedRemoteApplicationLauncher(directories) }, diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java index 7238dfea9e5..f1529710a17 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java @@ -28,14 +28,11 @@ import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.implementation.FixedValue; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.testsupport.BuildOutput; @@ -51,42 +48,36 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Madhura Bhave */ -@RunWith(Parameterized.class) public class DevToolsWithLazyInitializationIntegrationTests { - @ClassRule - public static final TemporaryFolder temp = new TemporaryFolder(); + @TempDir + static File temp; private static final BuildOutput buildOutput = new BuildOutput(DevToolsIntegrationTests.class); private LaunchedApplication launchedApplication; - private final File serverPortFile; + private final File serverPortFile = new File(buildOutput.getRootLocation(), "server.port"); - private final ApplicationLauncher applicationLauncher; + @RegisterExtension + final JvmLauncher javaLauncher = new JvmLauncher(); - @Rule - public JvmLauncher javaLauncher = new JvmLauncher(); - - public DevToolsWithLazyInitializationIntegrationTests(ApplicationLauncher applicationLauncher) { - this.applicationLauncher = applicationLauncher; - this.serverPortFile = new File(buildOutput.getRootLocation(), "server.port"); - } - - @Before - public void launchApplication() throws Exception { + private void launchApplication(ApplicationLauncher applicationLauncher) throws Exception { this.serverPortFile.delete(); - this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile, + this.launchedApplication = applicationLauncher.launchApplication(this.javaLauncher, this.serverPortFile, "--spring.main.lazy-initialization=true"); } - @After + @AfterEach public void stopApplication() throws InterruptedException { this.launchedApplication.stop(); } - @Test - public void addARequestMappingToAnExistingControllerWhenLazyInit() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void addARequestMappingToAnExistingControllerWhenLazyInit(ApplicationLauncher applicationLauncher) + throws Exception { + launchApplication(applicationLauncher); TestRestTemplate template = new TestRestTemplate(); String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -125,8 +116,7 @@ public class DevToolsWithLazyInitializationIntegrationTests { return new ControllerBuilder(name, this.launchedApplication.getClassesDirectory()); } - @Parameterized.Parameters(name = "{0}") - public static Object[] parameters() throws IOException { + static Object[] parameters() throws IOException { Directories directories = new Directories(buildOutput, temp); return new Object[] { new Object[] { new LocalApplicationLauncher(directories) }, new Object[] { new ExplodedRemoteApplicationLauncher(directories) }, diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/Directories.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/Directories.java index fee718e2e01..13a4535337d 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/Directories.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/Directories.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package org.springframework.boot.devtools.tests; import java.io.File; -import org.junit.rules.TemporaryFolder; - import org.springframework.boot.testsupport.BuildOutput; /** @@ -31,9 +29,9 @@ class Directories { private final BuildOutput buildOutput; - private final TemporaryFolder temp; + private final File temp; - Directories(BuildOutput buildOutput, TemporaryFolder temp) { + Directories(BuildOutput buildOutput, File temp) { this.buildOutput = buildOutput; this.temp = temp; } @@ -43,7 +41,7 @@ class Directories { } File getRemoteAppDirectory() { - return new File(this.temp.getRoot(), "remote"); + return new File(this.temp, "remote"); } File getDependenciesDirectory() { @@ -51,7 +49,7 @@ class Directories { } File getAppDirectory() { - return new File(this.temp.getRoot(), "app"); + return new File(this.temp, "app"); } } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java index 332b0f7efab..7c43e0977cd 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/JvmLauncher.java @@ -23,20 +23,20 @@ import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.util.StringUtils; /** - * JUnit {@link TestRule} that launched a JVM and redirects its output to a test + * {@link Extension} that launches a JVM and redirects its output to a test * method-specific location. * * @author Andy Wilkinson */ -class JvmLauncher implements TestRule { +class JvmLauncher implements BeforeTestExecutionCallback { private static final Pattern NON_ALPHABET_PATTERN = Pattern.compile("[^A-Za-z]+"); @@ -45,11 +45,10 @@ class JvmLauncher implements TestRule { private File outputDirectory; @Override - public Statement apply(Statement base, Description description) { + public void beforeTestExecution(ExtensionContext context) throws Exception { this.outputDirectory = new File(this.buildOutput.getRootLocation(), - "output/" + NON_ALPHABET_PATTERN.matcher(description.getMethodName()).replaceAll("")); + "output/" + NON_ALPHABET_PATTERN.matcher(context.getRequiredTestMethod().getName()).replaceAll("")); this.outputDirectory.mkdirs(); - return base; } LaunchedJvm launch(String name, String classpath, String... args) throws IOException { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-hibernate52-tests/src/test/java/org/springframework/boot/tests/hibernate52/Hibernate52ApplicationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-hibernate52-tests/src/test/java/org/springframework/boot/tests/hibernate52/Hibernate52ApplicationTests.java index deeb0e9480c..dde20489845 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-hibernate52-tests/src/test/java/org/springframework/boot/tests/hibernate52/Hibernate52ApplicationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-hibernate52-tests/src/test/java/org/springframework/boot/tests/hibernate52/Hibernate52ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,10 @@ package org.springframework.boot.tests.hibernate52; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringRunner.class) @SpringBootTest public class Hibernate52ApplicationTests { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java index 43200e19556..e5b2437a7e5 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java @@ -46,18 +46,14 @@ import com.github.dockerjava.core.util.CompressArchiveUtil; import com.github.dockerjava.jaxrs.AbstrSyncDockerCmdExec; import com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory; import org.assertj.core.api.Condition; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.boot.ansi.AnsiColor; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assume.assumeThat; /** * Integration tests for Spring Boot's launch script on OSs that use SysVinit. @@ -65,19 +61,213 @@ import static org.junit.Assume.assumeThat; * @author Andy Wilkinson * @author Ali Shahbour */ -@RunWith(Parameterized.class) public class SysVinitLaunchScriptIT { private final SpringBootDockerCmdExecFactory commandExecFactory = new SpringBootDockerCmdExecFactory(); private static final char ESC = 27; - private final String os; + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void statusWhenStopped(String os, String version) throws Exception { + String output = doTest(os, version, "status-when-stopped.sh"); + assertThat(output).contains("Status: 3"); + assertThat(output).has(coloredString(AnsiColor.RED, "Not running")); + } - private final String version; + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void statusWhenStarted(String os, String version) throws Exception { + String output = doTest(os, version, "status-when-started.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + } - @Parameters(name = "{0} {1}") - public static List parameters() { + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void statusWhenKilled(String os, String version) throws Exception { + String output = doTest(os, version, "status-when-killed.sh"); + assertThat(output).contains("Status: 1"); + assertThat(output) + .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void stopWhenStopped(String os, String version) throws Exception { + String output = doTest(os, version, "stop-when-stopped.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void forceStopWhenStopped(String os, String version) throws Exception { + String output = doTest(os, version, "force-stop-when-stopped.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void startWhenStarted(String os, String version) throws Exception { + String output = doTest(os, version, "start-when-started.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Already running [" + extractPid(output) + "]")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void restartWhenStopped(String os, String version) throws Exception { + String output = doTest(os, version, "restart-when-stopped.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void restartWhenStarted(String os, String version) throws Exception { + String output = doTest(os, version, "restart-when-started.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extract("PID1", output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID2", output) + "]")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void startWhenStopped(String os, String version) throws Exception { + String output = doTest(os, version, "start-when-stopped.sh"); + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void basicLaunch(String os, String version) throws Exception { + String output = doTest(os, version, "basic-launch.sh"); + assertThat(output).doesNotContain("PID_FOLDER"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithMissingLogFolderGeneratesAWarning(String os, String version) throws Exception { + String output = doTest(os, version, "launch-with-missing-log-folder.sh"); + assertThat(output).has( + coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithMissingPidFolderGeneratesAWarning(String os, String version) throws Exception { + String output = doTest(os, version, "launch-with-missing-pid-folder.sh"); + assertThat(output).has( + coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithSingleCommandLineArgument(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-single-command-line-argument.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithMultipleCommandLineArguments(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-multiple-command-line-arguments.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithSingleRunArg(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-single-run-arg.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithMultipleRunArgs(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-multiple-run-args.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithSingleJavaOpt(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-single-java-opt.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithDoubleLinkSingleJavaOpt(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-double-link-single-java-opt.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithMultipleJavaOpts(String os, String version) throws Exception { + doLaunch(os, version, "launch-with-multiple-java-opts.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithUseOfStartStopDaemonDisabled(String os, String version) throws Exception { + // CentOS doesn't have start-stop-daemon + Assumptions.assumeFalse(os.equals("CentOS")); + doLaunch(os, version, "launch-with-use-of-start-stop-daemon-disabled.sh"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithRelativePidFolder(String os, String version) throws Exception { + String output = doTest(os, version, "launch-with-relative-pid-folder.sh"); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void pidFolderOwnership(String os, String version) throws Exception { + String output = doTest(os, version, "pid-folder-ownership.sh"); + assertThat(output).contains("phil root"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void pidFileOwnership(String os, String version) throws Exception { + String output = doTest(os, version, "pid-file-ownership.sh"); + assertThat(output).contains("phil root"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void logFileOwnership(String os, String version) throws Exception { + String output = doTest(os, version, "log-file-ownership.sh"); + assertThat(output).contains("phil root"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void logFileOwnershipIsChangedWhenCreated(String os, String version) throws Exception { + String output = doTest(os, version, "log-file-ownership-is-changed-when-created.sh"); + assertThat(output).contains("andy root"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void logFileOwnershipIsUnchangedWhenExists(String os, String version) throws Exception { + String output = doTest(os, version, "log-file-ownership-is-unchanged-when-exists.sh"); + assertThat(output).contains("root root"); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parameters") + public void launchWithRelativeLogFolder(String os, String version) throws Exception { + String output = doTest(os, version, "launch-with-relative-log-folder.sh"); + assertThat(output).contains("Log written"); + } + + static List parameters() { List parameters = new ArrayList<>(); for (File os : new File("src/test/resources/conf").listFiles()) { for (File version : os.listFiles()) { @@ -87,191 +277,13 @@ public class SysVinitLaunchScriptIT { return parameters; } - public SysVinitLaunchScriptIT(String os, String version) { - this.os = os; - this.version = version; + private void doLaunch(String os, String version, String script) throws Exception { + assertThat(doTest(os, version, script)).contains("Launched"); } - @Test - public void statusWhenStopped() throws Exception { - String output = doTest("status-when-stopped.sh"); - assertThat(output).contains("Status: 3"); - assertThat(output).has(coloredString(AnsiColor.RED, "Not running")); - } - - @Test - public void statusWhenStarted() throws Exception { - String output = doTest("status-when-started.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - } - - @Test - public void statusWhenKilled() throws Exception { - String output = doTest("status-when-killed.sh"); - assertThat(output).contains("Status: 1"); - assertThat(output) - .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); - } - - @Test - public void stopWhenStopped() throws Exception { - String output = doTest("stop-when-stopped.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); - } - - @Test - public void forceStopWhenStopped() throws Exception { - String output = doTest("force-stop-when-stopped.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); - } - - @Test - public void startWhenStarted() throws Exception { - String output = doTest("start-when-started.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, "Already running [" + extractPid(output) + "]")); - } - - @Test - public void restartWhenStopped() throws Exception { - String output = doTest("restart-when-stopped.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - } - - @Test - public void restartWhenStarted() throws Exception { - String output = doTest("restart-when-started.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extract("PID1", output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID2", output) + "]")); - } - - @Test - public void startWhenStopped() throws Exception { - String output = doTest("start-when-stopped.sh"); - assertThat(output).contains("Status: 0"); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - } - - @Test - public void basicLaunch() throws Exception { - String output = doTest("basic-launch.sh"); - assertThat(output).doesNotContain("PID_FOLDER"); - } - - @Test - public void launchWithMissingLogFolderGeneratesAWarning() throws Exception { - String output = doTest("launch-with-missing-log-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); - } - - @Test - public void launchWithMissingPidFolderGeneratesAWarning() throws Exception { - String output = doTest("launch-with-missing-pid-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); - } - - @Test - public void launchWithSingleCommandLineArgument() throws Exception { - doLaunch("launch-with-single-command-line-argument.sh"); - } - - @Test - public void launchWithMultipleCommandLineArguments() throws Exception { - doLaunch("launch-with-multiple-command-line-arguments.sh"); - } - - @Test - public void launchWithSingleRunArg() throws Exception { - doLaunch("launch-with-single-run-arg.sh"); - } - - @Test - public void launchWithMultipleRunArgs() throws Exception { - doLaunch("launch-with-multiple-run-args.sh"); - } - - @Test - public void launchWithSingleJavaOpt() throws Exception { - doLaunch("launch-with-single-java-opt.sh"); - } - - @Test - public void launchWithDoubleLinkSingleJavaOpt() throws Exception { - doLaunch("launch-with-double-link-single-java-opt.sh"); - } - - @Test - public void launchWithMultipleJavaOpts() throws Exception { - doLaunch("launch-with-multiple-java-opts.sh"); - } - - @Test - public void launchWithUseOfStartStopDaemonDisabled() throws Exception { - // CentOS doesn't have start-stop-daemon - assumeThat(this.os, is(not("CentOS"))); - doLaunch("launch-with-use-of-start-stop-daemon-disabled.sh"); - } - - @Test - public void launchWithRelativePidFolder() throws Exception { - String output = doTest("launch-with-relative-pid-folder.sh"); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Running [" + extractPid(output) + "]")); - assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extractPid(output) + "]")); - } - - @Test - public void pidFolderOwnership() throws Exception { - String output = doTest("pid-folder-ownership.sh"); - assertThat(output).contains("phil root"); - } - - @Test - public void pidFileOwnership() throws Exception { - String output = doTest("pid-file-ownership.sh"); - assertThat(output).contains("phil root"); - } - - @Test - public void logFileOwnership() throws Exception { - String output = doTest("log-file-ownership.sh"); - assertThat(output).contains("phil root"); - } - - @Test - public void logFileOwnershipIsChangedWhenCreated() throws Exception { - String output = doTest("log-file-ownership-is-changed-when-created.sh"); - assertThat(output).contains("andy root"); - } - - @Test - public void logFileOwnershipIsUnchangedWhenExists() throws Exception { - String output = doTest("log-file-ownership-is-unchanged-when-exists.sh"); - assertThat(output).contains("root root"); - } - - @Test - public void launchWithRelativeLogFolder() throws Exception { - String output = doTest("launch-with-relative-log-folder.sh"); - assertThat(output).contains("Log written"); - } - - private void doLaunch(String script) throws Exception { - assertThat(doTest(script)).contains("Launched"); - } - - private String doTest(String script) throws Exception { + private String doTest(String os, String version, String script) throws Exception { DockerClient docker = createClient(); - String imageId = buildImage(docker); + String imageId = buildImage(os, version, docker); String container = createContainer(docker, imageId, script); try { copyFilesToContainer(docker, container, script); @@ -309,9 +321,9 @@ public class SysVinitLaunchScriptIT { return DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(this.commandExecFactory).build(); } - private String buildImage(DockerClient docker) { - String dockerfile = "src/test/resources/conf/" + this.os + "/" + this.version + "/Dockerfile"; - String tag = "spring-boot-it/" + this.os.toLowerCase(Locale.ENGLISH) + ":" + this.version; + private String buildImage(String os, String version, DockerClient docker) { + String dockerfile = "src/test/resources/conf/" + os + "/" + version + "/Dockerfile"; + String tag = "spring-boot-it/" + os.toLowerCase(Locale.ENGLISH) + ":" + version; BuildImageResultCallback resultCallback = new BuildImageResultCallback() { private List items = new ArrayList<>(); diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java index 9c46a637c12..210a69687cc 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java @@ -24,7 +24,9 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.List; -import org.junit.rules.ExternalResource; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.boot.testsupport.BuildOutput; import org.springframework.util.FileCopyUtils; @@ -32,12 +34,11 @@ import org.springframework.util.StreamUtils; import org.springframework.util.StringUtils; /** - * Base {@link ExternalResource} for launching a Spring Boot application as part of a - * JUnit test. + * Base class for launching a Spring Boot application as part of a JUnit test. * * @author Andy Wilkinson */ -abstract class AbstractApplicationLauncher extends ExternalResource { +abstract class AbstractApplicationLauncher implements BeforeEachCallback, AfterEachCallback { private final ApplicationBuilder applicationBuilder; @@ -53,13 +54,13 @@ abstract class AbstractApplicationLauncher extends ExternalResource { } @Override - protected final void before() throws Throwable { - this.process = startApplication(); + public void afterEach(ExtensionContext context) throws Exception { + this.process.destroy(); } @Override - protected final void after() { - this.process.destroy(); + public void beforeEach(ExtensionContext context) throws Exception { + this.process = startApplication(); } public final int getHttpPort() { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java deleted file mode 100644 index 1ad46088791..00000000000 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.context.embedded; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; - -import org.springframework.boot.testsupport.BuildOutput; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.StringUtils; -import org.springframework.web.client.ResponseErrorHandler; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriTemplateHandler; - -/** - * Base class for embedded servlet container integration tests. - * - * @author Andy Wilkinson - */ -public abstract class AbstractEmbeddedServletContainerIntegrationTests { - - @ClassRule - public static final TemporaryFolder temporaryFolder = new TemporaryFolder() { - - @Override - public void delete() { - } - - }; - - public static final BuildOutput buildOutput = new BuildOutput( - AbstractEmbeddedServletContainerIntegrationTests.class); - - @Rule - public final AbstractApplicationLauncher launcher; - - protected final RestTemplate rest = new RestTemplate(); - - public static Object[] parameters(String packaging, - List> applicationLaunchers) { - List parameters = new ArrayList<>(); - parameters.addAll(createParameters(packaging, "jetty", applicationLaunchers)); - parameters.addAll(createParameters(packaging, "tomcat", applicationLaunchers)); - parameters.addAll(createParameters(packaging, "undertow", applicationLaunchers)); - return parameters.toArray(new Object[0]); - } - - private static List createParameters(String packaging, String container, - List> applicationLaunchers) { - List parameters = new ArrayList<>(); - ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, packaging, container); - for (Class launcherClass : applicationLaunchers) { - try { - AbstractApplicationLauncher launcher = launcherClass - .getDeclaredConstructor(ApplicationBuilder.class, BuildOutput.class) - .newInstance(applicationBuilder, buildOutput); - String name = StringUtils.capitalize(container) + ": " + launcher.getDescription(packaging); - parameters.add(new Object[] { name, launcher }); - } - catch (Exception ex) { - throw new RuntimeException(ex); - } - } - return parameters; - } - - protected AbstractEmbeddedServletContainerIntegrationTests(String name, AbstractApplicationLauncher launcher) { - this.launcher = launcher; - this.rest.setErrorHandler(new ResponseErrorHandler() { - - @Override - public boolean hasError(ClientHttpResponse response) throws IOException { - return false; - } - - @Override - public void handleError(ClientHttpResponse response) throws IOException { - - } - - }); - this.rest.setUriTemplateHandler(new UriTemplateHandler() { - - @Override - public URI expand(String uriTemplate, Object... uriVariables) { - return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); - } - - @Override - public URI expand(String uriTemplate, Map uriVariables) { - return URI.create("http://localhost:" + launcher.getHttpPort() + uriTemplate); - } - - }); - } - -} diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java index 38a3b4ff0a1..5f8baabc75b 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/ApplicationBuilder.java @@ -21,6 +21,7 @@ import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -33,7 +34,6 @@ import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.apache.maven.shared.invoker.MavenInvocationException; -import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; @@ -48,26 +48,34 @@ import static org.assertj.core.api.Assertions.assertThat; */ class ApplicationBuilder { - private final TemporaryFolder temp; + private final Path temp; private final String packaging; private final String container; - ApplicationBuilder(TemporaryFolder temp, String packaging, String container) { + ApplicationBuilder(Path temp, String packaging, String container) { this.temp = temp; this.packaging = packaging; this.container = container; } File buildApplication() throws Exception { - File containerFolder = new File(this.temp.getRoot(), this.container); + File containerFolder = new File(this.temp.toFile(), this.container); if (containerFolder.exists()) { return new File(containerFolder, "app/target/app-0.0.1." + this.packaging); } return doBuildApplication(containerFolder); } + String getPackaging() { + return this.packaging; + } + + String getContainer() { + return this.container; + } + private File doBuildApplication(File containerFolder) throws IOException, MavenInvocationException { File resourcesJar = createResourcesJar(); File appFolder = new File(containerFolder, "app"); @@ -80,7 +88,7 @@ class ApplicationBuilder { } private File createResourcesJar() throws IOException { - File resourcesJar = new File(this.temp.getRoot(), "resources.jar"); + File resourcesJar = new File(this.temp.toFile(), "resources.jar"); if (resourcesJar.exists()) { return resourcesJar; } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java new file mode 100644 index 00000000000..4f753493b29 --- /dev/null +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java @@ -0,0 +1,189 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.context.embedded; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestTemplateInvocationContext; +import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; +import org.junit.platform.commons.util.ReflectionUtils; + +import org.springframework.boot.testsupport.BuildOutput; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.util.FileSystemUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriTemplateHandler; + +/** + * {@link TestTemplateInvocationContextProvider} for templated + * {@link EmbeddedServletContainerTest embedded servlet container tests}. + * + * @author Andy Wilkinson + */ +class EmbeddedServerContainerInvocationContextProvider + implements TestTemplateInvocationContextProvider, AfterAllCallback { + + private static final Set CONTAINERS = new HashSet<>(Arrays.asList("jetty", "tomcat", "undertow")); + + private static final BuildOutput buildOutput = new BuildOutput( + EmbeddedServerContainerInvocationContextProvider.class); + + private final Path tempDir; + + public EmbeddedServerContainerInvocationContextProvider() throws IOException { + this.tempDir = Files.createTempDirectory("embedded-servlet-container-tests"); + } + + @Override + public boolean supportsTestTemplate(ExtensionContext context) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { + EmbeddedServletContainerTest annotation = context.getRequiredTestClass() + .getAnnotation(EmbeddedServletContainerTest.class); + return CONTAINERS.stream() + .map((container) -> new ApplicationBuilder(this.tempDir, annotation.packaging(), container)) + .flatMap((builder) -> { + return Stream.of(annotation.launchers()) + .map((launcherClass) -> ReflectionUtils.newInstance(launcherClass, builder, buildOutput)) + .map((launcher) -> new EmbeddedServletContainerInvocationContext( + StringUtils.capitalize(builder.getContainer()) + ": " + + launcher.getDescription(builder.getPackaging()), + launcher)); + }); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + FileSystemUtils.deleteRecursively(this.tempDir); + } + + static class EmbeddedServletContainerInvocationContext implements TestTemplateInvocationContext, ParameterResolver { + + private final String name; + + private final AbstractApplicationLauncher launcher; + + public EmbeddedServletContainerInvocationContext(String name, AbstractApplicationLauncher launcher) { + this.name = name; + this.launcher = launcher; + } + + @Override + public List getAdditionalExtensions() { + return Arrays.asList(this.launcher, new RestTemplateParameterResolver(this.launcher)); + } + + @Override + public String getDisplayName(int invocationIndex) { + return this.name; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + if (parameterContext.getParameter().getType().equals(AbstractApplicationLauncher.class)) { + return true; + } + if (parameterContext.getParameter().getType().equals(RestTemplate.class)) { + return true; + } + return false; + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + if (parameterContext.getParameter().getType().equals(AbstractApplicationLauncher.class)) { + return this.launcher; + } + return null; + } + + } + + private static class RestTemplateParameterResolver implements ParameterResolver { + + private final AbstractApplicationLauncher launcher; + + private RestTemplateParameterResolver(AbstractApplicationLauncher launcher) { + this.launcher = launcher; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return parameterContext.getParameter().getType().equals(RestTemplate.class); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + RestTemplate rest = new RestTemplate(); + rest.setErrorHandler(new ResponseErrorHandler() { + + @Override + public boolean hasError(ClientHttpResponse response) throws IOException { + return false; + } + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + + } + + }); + rest.setUriTemplateHandler(new UriTemplateHandler() { + + @Override + public URI expand(String uriTemplate, Object... uriVariables) { + return URI.create("http://localhost:" + RestTemplateParameterResolver.this.launcher.getHttpPort() + + uriTemplate); + } + + @Override + public URI expand(String uriTemplate, Map uriVariables) { + return URI.create("http://localhost:" + RestTemplateParameterResolver.this.launcher.getHttpPort() + + uriTemplate); + } + + }); + return rest; + } + + } + +} diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java index 6b61c999862..54174d20e41 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarDevelopmentIntegrationTests.java @@ -16,15 +16,11 @@ package org.springframework.boot.context.embedded; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -34,29 +30,19 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class EmbeddedServletContainerJarDevelopmentIntegrationTests - extends AbstractEmbeddedServletContainerIntegrationTests { +@EmbeddedServletContainerTest(packaging = "jar", + launchers = { BootRunApplicationLauncher.class, IdeApplicationLauncher.class }) +public class EmbeddedServletContainerJarDevelopmentIntegrationTests { - @Parameters(name = "{0}") - public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", - Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); - } - - public EmbeddedServletContainerJarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { - super(name, launcher); - } - - @Test - public void metaInfResourceFromDependencyIsAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); + @TestTemplate + public void metaInfResourceFromDependencyIsAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + @TestTemplate + public void metaInfResourceFromDependencyIsAvailableViaServletContext(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java index 06900c056e6..04b0c5f2b55 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java @@ -16,15 +16,11 @@ package org.springframework.boot.context.embedded; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -34,49 +30,39 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class EmbeddedServletContainerJarPackagingIntegrationTests - extends AbstractEmbeddedServletContainerIntegrationTests { +@EmbeddedServletContainerTest(packaging = "jar", + launchers = { PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class }) +public class EmbeddedServletContainerJarPackagingIntegrationTests { - @Parameters(name = "{0}") - public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("jar", - Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); - } - - public EmbeddedServletContainerJarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { - super(name, launcher); - } - - @Test - public void nestedMetaInfResourceIsAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); + @TestTemplate + public void nestedMetaInfResourceIsAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + @TestTemplate + public void nestedMetaInfResourceIsAvailableViaServletContext(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); + @TestTemplate + public void nestedJarIsNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } - @Test - public void applicationClassesAreNotAvailableViaHttp() { - ResponseEntity entity = this.rest + @TestTemplate + public void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } - @Test - public void launcherIsNotAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/org/springframework/boot/loader/Launcher.class", + @TestTemplate + public void launcherIsNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/org/springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerTest.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerTest.java new file mode 100644 index 00000000000..425710f2d39 --- /dev/null +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.context.embedded; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.extension.ExtendWith; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author awilkinson + */ +@Retention(RUNTIME) +@Target(TYPE) +@ExtendWith(EmbeddedServerContainerInvocationContextProvider.class) +public @interface EmbeddedServletContainerTest { + + String packaging(); + + Class[] launchers(); + +} diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java index c0731c56381..b1031da5ed1 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java @@ -16,15 +16,11 @@ package org.springframework.boot.context.embedded; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -34,36 +30,26 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class EmbeddedServletContainerWarDevelopmentIntegrationTests - extends AbstractEmbeddedServletContainerIntegrationTests { +@EmbeddedServletContainerTest(packaging = "war", + launchers = { BootRunApplicationLauncher.class, IdeApplicationLauncher.class }) +public class EmbeddedServletContainerWarDevelopmentIntegrationTests { - @Parameters(name = "{0}") - public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", - Arrays.asList(BootRunApplicationLauncher.class, IdeApplicationLauncher.class)); - } - - public EmbeddedServletContainerWarDevelopmentIntegrationTests(String name, AbstractApplicationLauncher launcher) { - super(name, launcher); - } - - @Test - public void metaInfResourceFromDependencyIsAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); + @TestTemplate + public void metaInfResourceFromDependencyIsAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + @TestTemplate + public void metaInfResourceFromDependencyIsAvailableViaServletContext(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void webappResourcesAreAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", String.class); + @TestTemplate + public void webappResourcesAreAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java index cd938996511..19e9f91d75b 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java @@ -16,15 +16,11 @@ package org.springframework.boot.context.embedded; -import java.util.Arrays; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -34,59 +30,48 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class EmbeddedServletContainerWarPackagingIntegrationTests - extends AbstractEmbeddedServletContainerIntegrationTests { +@EmbeddedServletContainerTest(packaging = "war", + launchers = { PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class }) +public class EmbeddedServletContainerWarPackagingIntegrationTests { - @Parameters(name = "{0}") - public static Object[] parameters() { - return AbstractEmbeddedServletContainerIntegrationTests.parameters("war", - Arrays.asList(PackagedApplicationLauncher.class, ExplodedApplicationLauncher.class)); - } - - public EmbeddedServletContainerWarPackagingIntegrationTests(String name, AbstractApplicationLauncher launcher) { - super(name, launcher); - } - - @Test - public void nestedMetaInfResourceIsAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); + @TestTemplate + public void nestedMetaInfResourceIsAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + @TestTemplate + public void nestedMetaInfResourceIsAvailableViaServletContext(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); + @TestTemplate + public void nestedJarIsNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } - @Test - public void applicationClassesAreNotAvailableViaHttp() { - ResponseEntity entity = this.rest + @TestTemplate + public void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } - @Test - public void webappResourcesAreAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", String.class); + @TestTemplate + public void webappResourcesAreAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - @Test - public void loaderClassesAreNotAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/org/springframework/boot/loader/Launcher.class", + @TestTemplate + public void loaderClassesAreNotAvailableViaHttp(RestTemplate rest) { + ResponseEntity entity = rest.getForEntity("/org/springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - entity = this.rest.getForEntity("/org/springframework/../springframework/boot/loader/Launcher.class", - String.class); + entity = rest.getForEntity("/org/springframework/../springframework/boot/loader/Launcher.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); }