diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/build.gradle b/spring-boot-project/spring-boot-actuator-autoconfigure/build.gradle index 4bb6065924..2cebf9cec5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/build.gradle +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/build.gradle @@ -129,6 +129,7 @@ dependencies { testImplementation("org.hsqldb:hsqldb") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.skyscreamer:jsonassert") testImplementation("org.springframework:spring-orm") testImplementation("org.springframework.data:spring-data-elasticsearch") { 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 645b3bd287..5e88fd55cb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,9 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive; 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.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -41,6 +42,7 @@ import static org.mockito.BDDMockito.given; * * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ReactiveCloudFoundrySecurityInterceptorTests { @Mock @@ -53,7 +55,6 @@ class ReactiveCloudFoundrySecurityInterceptorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id"); } 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 c541e25758..b2ca744728 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -31,8 +31,9 @@ import java.util.concurrent.ConcurrentHashMap; 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.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.PublisherProbe; @@ -52,6 +53,7 @@ import static org.mockito.BDDMockito.given; * * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ReactiveTokenValidatorTests { private static final byte[] DOT = ".".getBytes(); @@ -85,7 +87,6 @@ class ReactiveTokenValidatorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); VALID_KEYS.put("valid-key", VALID_KEY); INVALID_KEYS.put("invalid-key", INVALID_KEY); this.tokenValidator = new ReactiveTokenValidator(this.securityService); @@ -159,7 +160,6 @@ class ReactiveTokenValidatorTests { void validateTokenWhenCacheValidShouldNotFetchTokenKeys() throws Exception { PublisherProbe> fetchTokenKeys = PublisherProbe.empty(); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); - given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; 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 8ccaf56103..c45a66e15b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,10 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AccessLevel; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; @@ -41,6 +42,7 @@ import static org.mockito.Mockito.verify; * * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class CloudFoundrySecurityInterceptorTests { @Mock @@ -55,7 +57,6 @@ class CloudFoundrySecurityInterceptorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id"); this.request = new MockHttpServletRequest(); } 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 a707f2ee7a..da6b83b0cd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -31,9 +31,10 @@ import java.util.function.Consumer; 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.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; @@ -52,6 +53,7 @@ import static org.mockito.Mockito.verify; * * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class TokenValidatorTests { private static final byte[] DOT = ".".getBytes(); @@ -85,7 +87,6 @@ class TokenValidatorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.tokenValidator = new TokenValidator(this.securityService); } @@ -135,7 +136,6 @@ class TokenValidatorTests { void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", Collections.singletonMap("valid-key", INVALID_KEY)); - given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( @@ -145,7 +145,6 @@ class TokenValidatorTests { @Test 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\"]}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java index 66f332b451..3b439bbc16 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.actuate.autoconfigure.endpoint.expose; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.MockitoAnnotations; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.endpoint.EndpointFilter; import org.springframework.boot.actuate.endpoint.EndpointId; @@ -36,15 +36,11 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class IncludeExcludeEndpointFilterTests { private IncludeExcludeEndpointFilter filter; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenEndpointTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() @@ -123,7 +119,7 @@ class IncludeExcludeEndpointFilterTests { environment.setProperty("foo.include", "bar"); environment.setProperty("foo.exclude", ""); this.filter = new IncludeExcludeEndpointFilter<>(DifferentTestExposableWebEndpoint.class, environment, "foo"); - assertThat(match(EndpointId.of("baz"))).isTrue(); + assertThat(match()).isTrue(); } @Test @@ -161,10 +157,16 @@ class IncludeExcludeEndpointFilterTests { this.filter = new IncludeExcludeEndpointFilter<>(TestExposableWebEndpoint.class, environment, "foo", "def"); } + private boolean match() { + return match(null); + } + @SuppressWarnings({ "rawtypes", "unchecked" }) private boolean match(EndpointId id) { ExposableEndpoint endpoint = mock(TestExposableWebEndpoint.class); - given(endpoint.getEndpointId()).willReturn(id); + if (id != null) { + given(endpoint.getEndpointId()).willReturn(id); + } return ((EndpointFilter) this.filter).match(endpoint); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java index c7797017bd..3c22e80dae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java @@ -20,10 +20,10 @@ import java.security.Principal; import java.util.Arrays; import java.util.Collections; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.autoconfigure.health.HealthProperties.Show; import org.springframework.boot.actuate.endpoint.SecurityContext; @@ -41,6 +41,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class AutoConfiguredHealthEndpointGroupTests { @Mock @@ -55,11 +56,6 @@ class AutoConfiguredHealthEndpointGroupTests { @Mock private Principal principal; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void isMemberWhenMemberPredicateMatchesAcceptsTrue() { AutoConfiguredHealthEndpointGroup group = new AutoConfiguredHealthEndpointGroup((name) -> name.startsWith("a"), @@ -112,17 +108,17 @@ class AutoConfiguredHealthEndpointGroupTests { this.statusAggregator, this.httpCodeStatusMapper, null, Show.WHEN_AUTHORIZED, Arrays.asList("admin", "root", "bossmode")); given(this.securityContext.getPrincipal()).willReturn(this.principal); + given(this.securityContext.isUserInRole("admin")).willReturn(false); given(this.securityContext.isUserInRole("root")).willReturn(true); assertThat(group.showDetails(this.securityContext)).isTrue(); } @Test - void showDetailsWhenShowDetailsIsWhenAuthorizedAndUseIsNotInRoleReturnsFalse() { + void showDetailsWhenShowDetailsIsWhenAuthorizedAndUserIsNotInRoleReturnsFalse() { AutoConfiguredHealthEndpointGroup group = new AutoConfiguredHealthEndpointGroup((name) -> true, this.statusAggregator, this.httpCodeStatusMapper, null, Show.WHEN_AUTHORIZED, - Arrays.asList("admin", "rot", "bossmode")); + Arrays.asList("admin", "root", "bossmode")); given(this.securityContext.getPrincipal()).willReturn(this.principal); - given(this.securityContext.isUserInRole("root")).willReturn(true); assertThat(group.showDetails(this.securityContext)).isFalse(); } @@ -198,17 +194,17 @@ class AutoConfiguredHealthEndpointGroupTests { this.statusAggregator, this.httpCodeStatusMapper, Show.WHEN_AUTHORIZED, Show.NEVER, Arrays.asList("admin", "root", "bossmode")); given(this.securityContext.getPrincipal()).willReturn(this.principal); + given(this.securityContext.isUserInRole("admin")).willReturn(false); given(this.securityContext.isUserInRole("root")).willReturn(true); assertThat(group.showComponents(this.securityContext)).isTrue(); } @Test - void showComponentsWhenShowComponentsIsWhenAuthorizedAndUseIsNotInRoleReturnsFalse() { + void showComponentsWhenShowComponentsIsWhenAuthorizedAndUserIsNotInRoleReturnsFalse() { AutoConfiguredHealthEndpointGroup group = new AutoConfiguredHealthEndpointGroup((name) -> true, this.statusAggregator, this.httpCodeStatusMapper, Show.WHEN_AUTHORIZED, Show.NEVER, Arrays.asList("admin", "rot", "bossmode")); given(this.securityContext.getPrincipal()).willReturn(this.principal); - given(this.securityContext.isUserInRole("root")).willReturn(true); assertThat(group.showComponents(this.securityContext)).isFalse(); } 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 0ad0f7af5e..bb9dbe5d08 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -25,11 +25,11 @@ import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.core.instrument.config.MeterFilter; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.ObjectProvider; @@ -46,6 +46,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * @author Phillip Webb * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class MeterRegistryConfigurerTests { private List binders = new ArrayList<>(); @@ -69,12 +70,6 @@ class MeterRegistryConfigurerTests { @Mock private Config mockConfig; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - given(this.mockRegistry.config()).willReturn(this.mockConfig); - } - @Test void configureWhenCompositeShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); @@ -87,6 +82,7 @@ class MeterRegistryConfigurerTests { @Test void configureShouldApplyCustomizer() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); this.customizers.add(this.mockCustomizer); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -96,6 +92,7 @@ class MeterRegistryConfigurerTests { @Test void configureShouldApplyFilter() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); this.filters.add(this.mockFilter); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -105,6 +102,7 @@ class MeterRegistryConfigurerTests { @Test void configureShouldApplyBinder() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); this.binders.add(this.mockBinder); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); @@ -124,15 +122,16 @@ class MeterRegistryConfigurerTests { @Test void configureShouldNotApplyBinderWhenCompositeExists() { - this.binders.add(this.mockBinder); + given(this.mockRegistry.config()).willReturn(this.mockConfig); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), - createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); + createObjectProvider(this.filters), null, false, true); configurer.configure(this.mockRegistry); verifyNoInteractions(this.mockBinder); } @Test void configureShouldBeCalledInOrderCustomizerFilterBinder() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); this.customizers.add(this.mockCustomizer); this.filters.add(this.mockFilter); this.binders.add(this.mockBinder); @@ -147,6 +146,7 @@ class MeterRegistryConfigurerTests { @Test void configureWhenAddToGlobalRegistryShouldAddToGlobalRegistry() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), createObjectProvider(this.filters), createObjectProvider(this.binders), true, false); try { @@ -160,6 +160,7 @@ class MeterRegistryConfigurerTests { @Test void configureWhenNotAddToGlobalRegistryShouldAddToGlobalRegistry() { + given(this.mockRegistry.config()).willReturn(this.mockConfig); 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/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 4beabea7bf..0e7ab62d5c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,10 @@ import java.util.Collections; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.amqp.rabbit.core.ChannelCallback; import org.springframework.amqp.rabbit.core.RabbitTemplate; @@ -41,6 +41,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class RabbitHealthIndicatorTests { @Mock @@ -49,15 +50,6 @@ class RabbitHealthIndicatorTests { @Mock private Channel channel; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - given(this.rabbitTemplate.execute(any())).willAnswer((invocation) -> { - ChannelCallback callback = invocation.getArgument(0); - return callback.doInRabbit(this.channel); - }); - } - @Test void createWhenRabbitTemplateIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RabbitHealthIndicator(null)) @@ -66,6 +58,7 @@ class RabbitHealthIndicatorTests { @Test void healthWhenConnectionSucceedsShouldReturnUpWithVersion() { + givenTemplateExecutionWillInvokeCallback(); Connection connection = mock(Connection.class); given(this.channel.getConnection()).willReturn(connection); given(connection.getServerProperties()).willReturn(Collections.singletonMap("version", "123")); @@ -76,9 +69,17 @@ class RabbitHealthIndicatorTests { @Test void healthWhenConnectionFailsShouldReturnDown() { + givenTemplateExecutionWillInvokeCallback(); given(this.channel.getConnection()).willThrow(new RuntimeException()); Health health = new RabbitHealthIndicator(this.rabbitTemplate).health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); } + private void givenTemplateExecutionWillInvokeCallback() { + given(this.rabbitTemplate.execute(any())).willAnswer((invocation) -> { + ChannelCallback callback = invocation.getArgument(0); + return callback.doInRabbit(this.channel); + }); + } + } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java index 5d013e9291..e7823e4f6c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java @@ -16,10 +16,10 @@ package org.springframework.boot.actuate.availability; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Status; import org.springframework.boot.availability.ApplicationAvailability; @@ -35,16 +35,12 @@ import static org.mockito.BDDMockito.given; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class AvailabilityStateHealthIndicatorTests { @Mock private ApplicationAvailability applicationAvailability; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenApplicationAvailabilityIsNullThrowsException() { assertThatIllegalArgumentException() 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 c70db883f0..07e1d9cc11 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,9 @@ import java.util.function.Function; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.endpoint.EndpointId; import org.springframework.boot.actuate.endpoint.OperationType; @@ -45,6 +46,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Stephane Nicoll */ +@ExtendWith(MockitoExtension.class) class CachingOperationInvokerAdvisorTests { @Mock @@ -57,7 +59,6 @@ class CachingOperationInvokerAdvisorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.advisor = new CachingOperationInvokerAdvisor(this.timeToLive); } 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 c9a102ddb4..b58b9f56ec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -27,10 +27,12 @@ import javax.management.ObjectName; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jmx.JmxException; import org.springframework.jmx.export.MBeanExportException; @@ -42,7 +44,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** @@ -51,12 +52,14 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class JmxEndpointExporterTests { @Mock private MBeanServer mBeanServer; - private EndpointObjectNameFactory objectNameFactory = spy(new TestEndpointObjectNameFactory()); + @Spy + private EndpointObjectNameFactory objectNameFactory = new TestEndpointObjectNameFactory(); private JmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @@ -72,7 +75,6 @@ class JmxEndpointExporterTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.exporter = new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, this.endpoints); } 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 861293c57d..e4e2a419c5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -26,12 +26,12 @@ import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.endpoint.EndpointId; @@ -49,6 +49,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Stephane Nicoll */ +@ExtendWith(MockitoExtension.class) class ServletEndpointRegistrarTests { @Mock @@ -60,12 +61,6 @@ class ServletEndpointRegistrarTests { @Captor private ArgumentCaptor servlet; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); - } - @Test void createWhenServletEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null)) @@ -93,6 +88,7 @@ class ServletEndpointRegistrarTests { } private void assertBasePath(String basePath, String expectedMapping) throws ServletException { + given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); @@ -103,6 +99,7 @@ class ServletEndpointRegistrarTests { @Test void onStartupWhenHasInitParametersShouldRegisterInitParameters() throws Exception { + given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); ExposableServletEndpoint endpoint = mockEndpoint( new EndpointServlet(TestServlet.class).withInitParameter("a", "b")); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); @@ -112,6 +109,7 @@ class ServletEndpointRegistrarTests { @Test void onStartupWhenHasLoadOnStartupShouldRegisterLoadOnStartup() throws Exception { + given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class).withLoadOnStartup(7)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); registrar.onStartup(this.servletContext); @@ -120,6 +118,7 @@ class ServletEndpointRegistrarTests { @Test void onStartupWhenHasNotLoadOnStartupShouldRegisterDefaultValue() throws Exception { + given(this.servletContext.addServlet(any(String.class), any(Servlet.class))).willReturn(this.dynamic); 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/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 740168a1ca..167558f59d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,12 +24,12 @@ import java.util.concurrent.ScheduledFuture; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.exporter.PushGateway; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager.PushGatewayTaskScheduler; import org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager.ShutdownOperation; @@ -51,6 +51,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class PrometheusPushGatewayManagerTests { @Mock @@ -59,6 +60,7 @@ class PrometheusPushGatewayManagerTests { @Mock private CollectorRegistry registry; + @Mock private TaskScheduler scheduler; private Duration pushRate = Duration.ofSeconds(1); @@ -71,12 +73,6 @@ class PrometheusPushGatewayManagerTests { @Mock private ScheduledFuture future; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - this.scheduler = mockScheduler(TaskScheduler.class); - } - @Test void createWhenPushGatewayIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, @@ -122,7 +118,8 @@ class PrometheusPushGatewayManagerTests { @Test void shutdownWhenOwnsSchedulerDoesShutdownScheduler() { - PushGatewayTaskScheduler ownedScheduler = mockScheduler(PushGatewayTaskScheduler.class); + PushGatewayTaskScheduler ownedScheduler = givenScheduleAtFixedRateWillReturnFuture( + mock(PushGatewayTaskScheduler.class)); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, ownedScheduler, this.pushRate, "job", this.groupingKey, null); manager.shutdown(); @@ -131,7 +128,8 @@ class PrometheusPushGatewayManagerTests { @Test void shutdownWhenDoesNotOwnSchedulerDoesNotShutdownScheduler() { - ThreadPoolTaskScheduler otherScheduler = mockScheduler(ThreadPoolTaskScheduler.class); + ThreadPoolTaskScheduler otherScheduler = givenScheduleAtFixedRateWillReturnFuture( + mock(ThreadPoolTaskScheduler.class)); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, otherScheduler, this.pushRate, "job", this.groupingKey, null); manager.shutdown(); @@ -140,6 +138,7 @@ class PrometheusPushGatewayManagerTests { @Test void shutdownWhenShutdownOperationIsPushPerformsPushOnShutdown() throws Exception { + givenScheduleAtFixedRateWithReturnFuture(); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.PUSH); manager.shutdown(); @@ -149,6 +148,7 @@ class PrometheusPushGatewayManagerTests { @Test void shutdownWhenShutdownOperationIsDeletePerformsDeleteOnShutdown() throws Exception { + givenScheduleAtFixedRateWithReturnFuture(); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.DELETE); manager.shutdown(); @@ -158,6 +158,7 @@ class PrometheusPushGatewayManagerTests { @Test void shutdownWhenShutdownOperationIsNoneDoesNothing() { + givenScheduleAtFixedRateWithReturnFuture(); PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.NONE); manager.shutdown(); @@ -167,6 +168,7 @@ class PrometheusPushGatewayManagerTests { @Test void pushWhenUnknownHostExceptionIsThrownDoesShutdown() throws Exception { + givenScheduleAtFixedRateWithReturnFuture(); new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", this.groupingKey, null); verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); @@ -185,9 +187,12 @@ class PrometheusPushGatewayManagerTests { this.task.getValue().run(); } + private void givenScheduleAtFixedRateWithReturnFuture() { + givenScheduleAtFixedRateWillReturnFuture(this.scheduler); + } + @SuppressWarnings({ "unchecked", "rawtypes" }) - private T mockScheduler(Class type) { - T scheduler = mock(type); + private T givenScheduleAtFixedRateWillReturnFuture(T scheduler) { given(scheduler.scheduleAtFixedRate(isA(Runnable.class), isA(Duration.class))) .willReturn((ScheduledFuture) this.future); return scheduler; 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 42dd5388ad..b631c492bd 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 @@ -20,8 +20,9 @@ import java.io.File; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; @@ -37,6 +38,7 @@ import static org.mockito.BDDMockito.given; * @author Mattias Severson * @author Stephane Nicoll */ +@ExtendWith(MockitoExtension.class) class DiskSpaceHealthIndicatorTests { private static final DataSize THRESHOLD = DataSize.ofKilobytes(1); @@ -50,13 +52,12 @@ class DiskSpaceHealthIndicatorTests { @BeforeEach void setUp() { - MockitoAnnotations.initMocks(this); - given(this.fileMock.exists()).willReturn(true); this.healthIndicator = new DiskSpaceHealthIndicator(this.fileMock, THRESHOLD); } @Test void diskSpaceIsUp() { + given(this.fileMock.exists()).willReturn(true); long freeSpace = THRESHOLD.toBytes() + 10; given(this.fileMock.getUsableSpace()).willReturn(freeSpace); given(this.fileMock.getTotalSpace()).willReturn(TOTAL_SPACE.toBytes()); @@ -70,6 +71,7 @@ class DiskSpaceHealthIndicatorTests { @Test void diskSpaceIsDown() { + given(this.fileMock.exists()).willReturn(true); 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-autoconfigure/build.gradle b/spring-boot-project/spring-boot-autoconfigure/build.gradle index 6be22e43b5..8dc8e1da75 100644 --- a/spring-boot-project/spring-boot-autoconfigure/build.gradle +++ b/spring-boot-project/spring-boot-autoconfigure/build.gradle @@ -171,6 +171,7 @@ dependencies { testImplementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.springframework:spring-test") testImplementation("org.springframework.kafka:spring-kafka-test") testImplementation("org.springframework.security:spring-security-test") 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 86bf63ffb4..2a627c33c9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,9 @@ import java.util.Map; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -53,6 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Greg Turnquist * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ConditionEvaluationReportTests { private DefaultListableBeanFactory beanFactory; @@ -76,7 +78,6 @@ class ConditionEvaluationReportTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.beanFactory = new DefaultListableBeanFactory(); this.report = ConditionEvaluationReport.get(this.beanFactory); } 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 b58da5f8d6..2a9c9ba297 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,10 @@ import java.util.function.Consumer; import java.util.function.Supplier; import org.hibernate.cfg.AvailableSettings; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy; @@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author Artsiom Yudovin */ +@ExtendWith(MockitoExtension.class) class HibernatePropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() @@ -53,11 +54,6 @@ class HibernatePropertiesTests { @Mock private Supplier ddlAutoSupplier; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void noCustomNamingStrategy() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> { 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 0dc8ac0f4e..e89efe4468 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,9 @@ import java.util.Collections; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationContext; import org.springframework.core.io.ResourceLoader; @@ -40,6 +41,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class TemplateAvailabilityProvidersTests { private TemplateAvailabilityProviders providers; @@ -58,7 +60,6 @@ class TemplateAvailabilityProvidersTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider)); } 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 884861cb7b..7bd0e43703 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 @@ -22,9 +22,10 @@ import java.util.Map; import io.netty.channel.ChannelOption; 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.mockito.junit.jupiter.MockitoExtension; import reactor.netty.http.server.HttpRequestDecoderSpec; import reactor.netty.http.server.HttpServer; @@ -49,6 +50,7 @@ import static org.mockito.Mockito.verify; * @author Brian Clozel * @author Artsiom Yudovin */ +@ExtendWith(MockitoExtension.class) class NettyWebServerFactoryCustomizerTests { private MockEnvironment environment; @@ -62,7 +64,6 @@ class NettyWebServerFactoryCustomizerTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.environment = new MockEnvironment(); this.serverProperties = new ServerProperties(); ConfigurationPropertySources.attach(this.environment); 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 daab03ba0a..f0b6e4fbb2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +24,9 @@ import javax.servlet.http.HttpServletRequest; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider; import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProviders; @@ -56,6 +57,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * @author Phillip Webb * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class DefaultErrorViewResolverTests { private DefaultErrorViewResolver resolver; @@ -71,7 +73,6 @@ class DefaultErrorViewResolverTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.refresh(); this.resourceProperties = new ResourceProperties(); @@ -115,6 +116,8 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/503"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); 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, @@ -124,6 +127,8 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); 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); @@ -170,9 +175,10 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); - given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), + any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); + verifyNoMoreInteractions(this.templateAvailabilityProvider); MockHttpServletResponse response = render(resolved); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); diff --git a/spring-boot-project/spring-boot-cli/build.gradle b/spring-boot-project/spring-boot-cli/build.gradle index 12d967371e..515de9e7de 100644 --- a/spring-boot-project/spring-boot-cli/build.gradle +++ b/spring-boot-project/spring-boot-cli/build.gradle @@ -63,6 +63,7 @@ dependencies { testImplementation("org.codehaus.groovy:groovy-templates") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.springframework:spring-test") testRepository(project(path: ":spring-boot-project:spring-boot-starters:spring-boot-starter-actuator", configuration: "mavenRepository")) 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 0bd3e95b7c..2ebd1023e0 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 @@ -22,16 +22,17 @@ import java.util.Set; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.cli.command.core.HelpCommand; import org.springframework.boot.cli.command.core.HintCommand; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; /** @@ -40,6 +41,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Dave Syer */ +@ExtendWith(MockitoExtension.class) class CommandRunnerTests { private CommandRunner commandRunner; @@ -63,7 +65,6 @@ class CommandRunnerTests { @BeforeEach void setup() { this.loader = Thread.currentThread().getContextClassLoader(); - MockitoAnnotations.initMocks(this); this.commandRunner = new CommandRunner("spring") { @Override @@ -84,9 +85,9 @@ class CommandRunnerTests { super.printStackTrace(ex); } }; - given(this.anotherCommand.getName()).willReturn("another"); - given(this.regularCommand.getName()).willReturn("command"); - given(this.regularCommand.getDescription()).willReturn("A regular command"); + lenient().doReturn("another").when(this.anotherCommand).getName(); + lenient().doReturn("command").when(this.regularCommand).getName(); + lenient().doReturn("A regular command").when(this.regularCommand).getDescription(); this.commandRunner.addCommand(this.regularCommand); this.commandRunner.addCommand(new HelpCommand(this.commandRunner)); this.commandRunner.addCommand(new HintCommand(this.commandRunner)); 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 4775330b11..dbe11c77c7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,9 +19,10 @@ package org.springframework.boot.cli.command.encodepassword; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.cli.command.status.ExitStatus; import org.springframework.boot.cli.util.MockLog; @@ -37,6 +38,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class EncodePasswordCommandTests { private MockLog log; @@ -46,7 +48,6 @@ class EncodePasswordCommandTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.log = MockLog.attach(); } 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 5ccaecbb84..cbdfb1664f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -27,12 +27,12 @@ import java.util.zip.ZipOutputStream; import joptsimple.OptionSet; import org.apache.http.Header; import org.apache.http.client.methods.HttpUriRequest; -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.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.cli.command.status.ExitStatus; @@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify; * @author Stephane Nicoll * @author EddĂș MelĂ©ndez */ +@ExtendWith(MockitoExtension.class) class InitCommandTests extends AbstractHttpClientMockTests { private final TestableInitCommandOptionHandler handler; @@ -54,11 +55,6 @@ class InitCommandTests extends AbstractHttpClientMockTests { @Captor private ArgumentCaptor requestCaptor; - @BeforeEach - void setupMocks() { - MockitoAnnotations.initMocks(this); - } - InitCommandTests() { InitializrService initializrService = new InitializrService(this.http); this.handler = new TestableInitCommandOptionHandler(initializrService); 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 7e5f987506..23990bb7d8 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 @@ -27,8 +27,9 @@ import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.control.SourceUnit; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver; import org.springframework.boot.cli.compiler.grape.DependencyResolutionContext; @@ -41,6 +42,7 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class DependencyCustomizerTests { private final ModuleNode moduleNode = new ModuleNode((SourceUnit) null); @@ -54,10 +56,6 @@ class DependencyCustomizerTests { @BeforeEach void setUp() { - MockitoAnnotations.initMocks(this); - given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); - given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); - given(this.resolver.getVersion("spring-boot-starter-logging")).willReturn("1.2.3"); this.moduleNode.addClass(this.classNode); this.dependencyCustomizer = new DependencyCustomizer(new GroovyClassLoader(getClass().getClassLoader()), this.moduleNode, new DependencyResolutionContext() { @@ -72,6 +70,9 @@ class DependencyCustomizerTests { @Test void basicAdd() { + given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); + given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); + given(this.resolver.getVersion("spring-boot-starter-logging")).willReturn("1.2.3"); this.dependencyCustomizer.add("spring-boot-starter-logging"); List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); @@ -82,6 +83,9 @@ class DependencyCustomizerTests { @Test void nonTransitiveAdd() { + given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); + given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); + given(this.resolver.getVersion("spring-boot-starter-logging")).willReturn("1.2.3"); this.dependencyCustomizer.add("spring-boot-starter-logging", false); List grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class)); assertThat(grabAnnotations).hasSize(1); @@ -92,6 +96,9 @@ class DependencyCustomizerTests { @Test void fullyCustomized() { + given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot"); + given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging"); + given(this.resolver.getVersion("spring-boot-starter-logging")).willReturn("1.2.3"); 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); 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 504726403f..27bf910460 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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.cli.compiler.dependencies; import java.util.Arrays; -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.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -31,6 +31,7 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class CompositeDependencyManagementTests { @Mock @@ -39,11 +40,6 @@ class CompositeDependencyManagementTests { @Mock private DependencyManagement dependencyManagement2; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void unknownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); @@ -55,7 +51,6 @@ class CompositeDependencyManagementTests { @Test 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) .getSpringBootVersion()).isEqualTo("1.2.3"); } @@ -71,7 +66,6 @@ class CompositeDependencyManagementTests { @Test 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) .find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3")); } 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 b2d6924baf..9c2125181b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,11 +24,11 @@ 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.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.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import static org.assertj.core.api.Assertions.assertThat; @@ -44,6 +44,7 @@ import static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class GrapeRootRepositorySystemSessionAutoConfigurationTests { private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); @@ -51,19 +52,8 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests { @Mock private RepositorySystem repositorySystem; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void noLocalRepositoryWhenNoGrapeRoot() { - given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class))) - .willAnswer((invocation) -> { - LocalRepository localRepository = invocation.getArgument(1); - return new SimpleLocalRepositoryManagerFactory().newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); - }); new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); verify(this.repositorySystem, never()).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); assertThat(this.session.getLocalRepository()).isNull(); 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 bd579d794b..a7cb253f83 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -27,10 +27,10 @@ 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.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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.util.TestPropertyValues; @@ -44,16 +44,12 @@ import static org.mockito.BDDMockito.given; * * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class SettingsXmlRepositorySystemSessionAutoConfigurationTests { @Mock private RepositorySystem repositorySystem; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void basicSessionCustomization() { assertSessionCustomization("src/test/resources/maven-settings/basic"); diff --git a/spring-boot-project/spring-boot-dependencies/build.gradle b/spring-boot-project/spring-boot-dependencies/build.gradle index 9bd5ef5dab..be45ba2cb4 100644 --- a/spring-boot-project/spring-boot-dependencies/build.gradle +++ b/spring-boot-project/spring-boot-dependencies/build.gradle @@ -1127,7 +1127,7 @@ bom { ] } } - library("Mockito", "3.3.3") { + library("Mockito", "3.4.6") { group("org.mockito") { modules = [ "mockito-core", diff --git a/spring-boot-project/spring-boot-devtools/build.gradle b/spring-boot-project/spring-boot-devtools/build.gradle index 13dfbc52a2..f906de163b 100644 --- a/spring-boot-project/spring-boot-devtools/build.gradle +++ b/spring-boot-project/spring-boot-devtools/build.gradle @@ -59,6 +59,7 @@ dependencies { testImplementation("org.hsqldb:hsqldb") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.postgresql:postgresql") testImplementation("org.springframework:spring-test") testImplementation("org.springframework:spring-webmvc") 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 978b8eb934..bb465eb5c1 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,12 +21,12 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.devtools.filewatch.ChangedFile; import org.springframework.boot.devtools.filewatch.ChangedFiles; @@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ClassPathFileChangeListenerTests { @Mock @@ -59,11 +60,6 @@ class ClassPathFileChangeListenerTests { @Captor private ArgumentCaptor eventCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void eventPublisherMustNotBeNull() { assertThatIllegalArgumentException() 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 d6473a8dd7..4d38810da6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,9 @@ import java.net.URI; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.devtools.autoconfigure.OptionalLiveReloadServer; import org.springframework.http.HttpMethod; @@ -42,6 +43,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class DelayedLiveReloadTriggerTests { private static final String URL = "http://localhost:8080"; @@ -68,11 +70,6 @@ class DelayedLiveReloadTriggerTests { @BeforeEach void setup() throws IOException { - MockitoAnnotations.initMocks(this); - given(this.errorRequest.execute()).willReturn(this.errorResponse); - given(this.okRequest.execute()).willReturn(this.okResponse); - given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); - given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); this.trigger = new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, URL); } @@ -106,6 +103,10 @@ class DelayedLiveReloadTriggerTests { @Test void triggerReloadOnStatus() throws Exception { + given(this.errorRequest.execute()).willReturn(this.errorResponse); + given(this.okRequest.execute()).willReturn(this.okResponse); + given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); + given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); 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 bf2def343f..942acb901f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +20,9 @@ import java.io.IOException; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; @@ -39,6 +40,7 @@ import static org.mockito.BDDMockito.given; * @author Rob Winch * @since 1.3.0 */ +@ExtendWith(MockitoExtension.class) class HttpHeaderInterceptorTests { private String name; @@ -61,13 +63,11 @@ class HttpHeaderInterceptorTests { @BeforeEach void setup() throws Exception { - MockitoAnnotations.initMocks(this); this.body = new byte[] {}; this.httpRequest = new MockHttpServletRequest(); this.request = new ServletServerHttpRequest(this.httpRequest); this.name = "X-AUTH-TOKEN"; this.value = "secret"; - given(this.execution.execute(this.request, this.body)).willReturn(this.response); this.interceptor = new HttpHeaderInterceptor(this.name, this.value); } @@ -97,6 +97,7 @@ class HttpHeaderInterceptorTests { @Test void intercept() throws IOException { + given(this.execution.execute(this.request, this.body)).willReturn(this.response); 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/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index c4a13c47b2..03826f5b4a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,11 @@ import javax.servlet.http.HttpServletResponse; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; @@ -49,6 +50,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class DispatcherFilterTests { @Mock @@ -67,7 +69,6 @@ class DispatcherFilterTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.filter = new DispatcherFilter(this.dispatcher); } 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 28fb45d722..57289906f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.Ordered; import org.springframework.http.server.ServerHttpRequest; @@ -49,27 +49,17 @@ import static org.mockito.Mockito.withSettings; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class DispatcherTests { @Mock private AccessManager accessManager; - private MockHttpServletRequest request; + private MockHttpServletResponse response = new MockHttpServletResponse(); - private MockHttpServletResponse response; + private ServerHttpRequest serverRequest = new ServletServerHttpRequest(new MockHttpServletRequest()); - private ServerHttpRequest serverRequest; - - private ServerHttpResponse serverResponse; - - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - this.request = new MockHttpServletRequest(); - this.response = new MockHttpServletResponse(); - this.serverRequest = new ServletServerHttpRequest(this.request); - this.serverResponse = new ServletServerHttpResponse(this.response); - } + private ServerHttpResponse serverResponse = new ServletServerHttpResponse(this.response); @Test void accessManagerMustNotBeNull() { 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 459f9ad492..b85fe3627f 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 @@ -22,10 +22,11 @@ import java.io.ObjectOutputStream; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; @@ -45,6 +46,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class HttpRestartServerTests { @Mock @@ -57,7 +59,6 @@ class HttpRestartServerTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.server = new HttpRestartServer(this.delegate); } 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 9253248d74..e24580493d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.devtools.test.MockClientHttpRequestFactory; import org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection.TunnelChannel; @@ -50,7 +50,7 @@ import static org.mockito.Mockito.verify; * @author Rob Winch * @author Andy Wilkinson */ -@ExtendWith(OutputCaptureExtension.class) +@ExtendWith({ OutputCaptureExtension.class, MockitoExtension.class }) class HttpTunnelConnectionTests { private String url; @@ -66,7 +66,6 @@ class HttpTunnelConnectionTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.url = "http://localhost:12345"; this.incomingData = new ByteArrayOutputStream(); this.incomingChannel = Channels.newChannel(this.incomingData); 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 c29a1bd9e0..a299cc3eea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,9 @@ import java.util.concurrent.atomic.AtomicBoolean; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload; import org.springframework.boot.devtools.tunnel.server.HttpTunnelServer.HttpConnection; @@ -57,6 +58,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class HttpTunnelServerTests { private static final int DEFAULT_LONG_POLL_TIMEOUT = 10000; @@ -82,13 +84,7 @@ class HttpTunnelServerTests { @BeforeEach void setup() throws Exception { - MockitoAnnotations.initMocks(this); this.server = new HttpTunnelServer(this.serverConnection); - given(this.serverConnection.open(anyInt())).willAnswer((invocation) -> { - MockServerChannel channel = HttpTunnelServerTests.this.serverChannel; - channel.setTimeout(invocation.getArgument(0)); - return channel; - }); this.servletRequest = new MockHttpServletRequest(); this.servletRequest.setAsyncSupported(true); this.servletResponse = new MockHttpServletResponse(); @@ -106,12 +102,14 @@ class HttpTunnelServerTests { @Test void serverConnectedOnFirstRequest() throws Exception { verify(this.serverConnection, never()).open(anyInt()); + givenServerConnectionOpenWillAnswerWithServerChannel(); this.server.handle(this.request, this.response); verify(this.serverConnection, times(1)).open(DEFAULT_LONG_POLL_TIMEOUT); } @Test void longPollTimeout() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.server.setLongPollTimeout(800); this.server.handle(this.request, this.response); verify(this.serverConnection, times(1)).open(800); @@ -125,6 +123,7 @@ class HttpTunnelServerTests { @Test void initialRequestIsSentToServer() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.servletRequest.addHeader(SEQ_HEADER, "1"); this.servletRequest.setContent("hello".getBytes()); this.server.handle(this.request, this.response); @@ -135,6 +134,7 @@ class HttpTunnelServerTests { @Test void initialRequestIsUsedForFirstServerResponse() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.servletRequest.addHeader(SEQ_HEADER, "1"); this.servletRequest.setContent("hello".getBytes()); this.server.handle(this.request, this.response); @@ -148,6 +148,7 @@ class HttpTunnelServerTests { @Test void initialRequestHasNoPayload() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.server.handle(this.request, this.response); this.serverChannel.disconnect(); this.server.getServerThread().join(); @@ -156,6 +157,7 @@ class HttpTunnelServerTests { @Test void typicalRequestResponseTraffic() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("hello server", 1); @@ -177,6 +179,7 @@ class HttpTunnelServerTests { @Test void clientIsAwareOfServerClose() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); MockHttpConnection h1 = new MockHttpConnection("1", 1); this.server.handle(h1); this.serverChannel.disconnect(); @@ -186,6 +189,7 @@ class HttpTunnelServerTests { @Test void clientCanCloseServer() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("DISCONNECT", 1); @@ -198,6 +202,7 @@ class HttpTunnelServerTests { @Test void neverMoreThanTwoHttpConnections() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); MockHttpConnection h2 = new MockHttpConnection("1", 2); @@ -212,6 +217,7 @@ class HttpTunnelServerTests { @Test void requestReceivedOutOfOrder() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); MockHttpConnection h1 = new MockHttpConnection(); MockHttpConnection h2 = new MockHttpConnection("1+2", 1); MockHttpConnection h3 = new MockHttpConnection("+3", 2); @@ -225,6 +231,7 @@ class HttpTunnelServerTests { @Test void httpConnectionsAreClosedAfterLongPollTimeout() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.server.setDisconnectTimeout(1000); this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); @@ -240,6 +247,7 @@ class HttpTunnelServerTests { @Test void disconnectTimeout() throws Exception { + givenServerConnectionOpenWillAnswerWithServerChannel(); this.server.setDisconnectTimeout(100); this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); @@ -317,6 +325,14 @@ class HttpTunnelServerTests { assertThat(connection.isOlderThan(100)).isTrue(); } + private void givenServerConnectionOpenWillAnswerWithServerChannel() throws IOException { + given(this.serverConnection.open(anyInt())).willAnswer((invocation) -> { + MockServerChannel channel = HttpTunnelServerTests.this.serverChannel; + channel.setTimeout(invocation.getArgument(0)); + return channel; + }); + } + /** * Mock {@link ByteChannel} used to simulate the server connection. */ diff --git a/spring-boot-project/spring-boot-test-autoconfigure/build.gradle b/spring-boot-project/spring-boot-test-autoconfigure/build.gradle index 68edda9b11..cd43e30aed 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/build.gradle +++ b/spring-boot-project/spring-boot-test-autoconfigure/build.gradle @@ -76,6 +76,7 @@ dependencies { testImplementation("org.junit.platform:junit-platform-engine") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.skyscreamer:jsonassert") testImplementation("org.springframework.hateoas:spring-hateoas") testImplementation("org.springframework.plugin:spring-plugin-core") 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 15154b0cc3..330f27b3a1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +22,9 @@ import javax.persistence.PersistenceUnitUtil; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -39,6 +40,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class TestEntityManagerTests { @Mock @@ -54,9 +56,7 @@ class TestEntityManagerTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.testEntityManager = new TestEntityManager(this.entityManagerFactory); - given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); } @Test @@ -69,6 +69,7 @@ class TestEntityManagerTests { void persistAndGetIdShouldPersistAndGetId() { bindEntityManager(); TestEntity entity = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Object result = this.testEntityManager.persistAndGetId(entity); verify(this.entityManager).persist(entity); @@ -79,6 +80,7 @@ class TestEntityManagerTests { void persistAndGetIdForTypeShouldPersistAndGetId() { bindEntityManager(); TestEntity entity = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Integer result = this.testEntityManager.persistAndGetId(entity, Integer.class); verify(this.entityManager).persist(entity); @@ -109,6 +111,7 @@ class TestEntityManagerTests { bindEntityManager(); TestEntity entity = new TestEntity(); TestEntity found = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); given(this.entityManager.find(TestEntity.class, 123)).willReturn(found); TestEntity result = this.testEntityManager.persistFlushFind(entity); @@ -177,6 +180,7 @@ class TestEntityManagerTests { @Test void getIdForTypeShouldGetId() { TestEntity entity = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Integer result = this.testEntityManager.getId(entity, Integer.class); assertThat(result).isEqualTo(123); @@ -185,6 +189,7 @@ class TestEntityManagerTests { @Test void getIdForTypeWhenTypeIsWrongShouldThrowException() { TestEntity entity = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); assertThatIllegalArgumentException().isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " @@ -194,6 +199,7 @@ class TestEntityManagerTests { @Test void getIdShouldGetId() { TestEntity entity = new TestEntity(); + given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); Object result = this.testEntityManager.getId(entity); assertThat(result).isEqualTo(123); diff --git a/spring-boot-project/spring-boot-test/build.gradle b/spring-boot-project/spring-boot-test/build.gradle index 7175e8c390..7a1c2913d9 100644 --- a/spring-boot-project/spring-boot-test/build.gradle +++ b/spring-boot-project/spring-boot-test/build.gradle @@ -43,6 +43,7 @@ dependencies { testImplementation("org.codehaus.groovy:groovy-xml") testImplementation("org.apache.johnzon:johnzon-jsonb") testImplementation("org.junit.jupiter:junit-jupiter") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.slf4j:slf4j-api") testImplementation("org.spockframework:spock-core") testImplementation("org.springframework:spring-webmvc") diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java index 674ea672f7..1a410e5cee 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -33,7 +33,7 @@ import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils.FieldCallback; /** - * {@link TestExecutionListener} to trigger {@link MockitoAnnotations#initMocks(Object)} + * {@link TestExecutionListener} to trigger {@link MockitoAnnotations#openMocks(Object)} * when {@link MockBean @MockBean} annotations are used. Primarily to allow * {@link Captor @Captor} annotations. * @@ -43,6 +43,8 @@ import org.springframework.util.ReflectionUtils.FieldCallback; */ public class MockitoTestExecutionListener extends AbstractTestExecutionListener { + private static final String MOCKS_ATTRIBUTE_NAME = MockitoTestExecutionListener.class.getName() + ".mocks"; + @Override public final int getOrder() { return 1950; @@ -63,9 +65,17 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener } } + @Override + public void afterTestMethod(TestContext testContext) throws Exception { + Object mocks = testContext.getAttribute(MOCKS_ATTRIBUTE_NAME); + if (mocks instanceof AutoCloseable) { + ((AutoCloseable) mocks).close(); + } + } + private void initMocks(TestContext testContext) { if (hasMockitoAnnotations(testContext)) { - MockitoAnnotations.initMocks(testContext.getTestInstance()); + testContext.setAttribute(MOCKS_ATTRIBUTE_NAME, MockitoAnnotations.openMocks(testContext.getTestInstance())); } } 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 5931b9cff7..7e84cc6a04 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +20,9 @@ import java.util.function.Supplier; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; @@ -38,6 +39,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ApplicationContextAssertProviderTests { @Mock @@ -51,7 +53,6 @@ class ApplicationContextAssertProviderTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.startupFailure = new RuntimeException(); this.mockContextSupplier = () -> this.mockContext; this.startupFailureSupplier = () -> { 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 3c1b94152a..40b9762c55 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,12 +19,12 @@ package org.springframework.boot.test.mock.mockito; import java.io.InputStream; import java.lang.reflect.Field; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationContext; import org.springframework.test.context.TestContext; @@ -43,6 +43,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class MockitoTestExecutionListenerTests { private MockitoTestExecutionListener listener = new MockitoTestExecutionListener(); @@ -56,12 +57,6 @@ class MockitoTestExecutionListenerTests { @Captor private ArgumentCaptor fieldCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); - } - @Test void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception { WithMockitoAnnotations instance = new WithMockitoAnnotations(); @@ -72,23 +67,27 @@ class MockitoTestExecutionListenerTests { @Test void prepareTestInstanceShouldInjectMockBean() throws Exception { + given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); WithMockBean instance = new WithMockBean(); - this.listener.prepareTestInstance(mockTestContext(instance)); + TestContext testContext = mockTestContext(instance); + given(testContext.getApplicationContext()).willReturn(this.applicationContext); + this.listener.prepareTestInstance(testContext); verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class)); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); } @Test void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { - WithMockBean instance = new WithMockBean(); - this.listener.beforeTestMethod(mockTestContext(instance)); + this.listener.beforeTestMethod(mock(TestContext.class)); verifyNoMoreInteractions(this.postProcessor); } @Test void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { + given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); WithMockBean instance = new WithMockBean(); TestContext mockTestContext = mockTestContext(instance); + given(mockTestContext.getApplicationContext()).willReturn(this.applicationContext); given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) .willReturn(Boolean.TRUE); this.listener.beforeTestMethod(mockTestContext); @@ -101,7 +100,6 @@ class MockitoTestExecutionListenerTests { TestContext testContext = mock(TestContext.class); given(testContext.getTestInstance()).willReturn(instance); given(testContext.getTestClass()).willReturn((Class) instance.getClass()); - given(testContext.getApplicationContext()).willReturn(this.applicationContext); return testContext; } 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 f8ba8b2cb4..2d7abb01a6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,12 +20,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -43,6 +43,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class QualifierDefinitionTests { @Mock @@ -51,11 +52,6 @@ class QualifierDefinitionTests { @Captor private ArgumentCaptor descriptorCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void forElementFieldIsNullShouldReturnNull() { assertThat(QualifierDefinition.forElement((Field) null)).isNull(); 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 9de4bf90f5..5402ecc069 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,11 @@ import java.net.URI; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.ClientHttpRequest; @@ -49,6 +50,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class RootUriRequestExpectationManagerTests { private String uri = "https://example.com"; @@ -63,7 +65,6 @@ class RootUriRequestExpectationManagerTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.manager = new RootUriRequestExpectationManager(this.uri, this.delegate); } 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 aa102543d8..9d81260b5b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -25,9 +25,10 @@ import com.gargoylesoftware.htmlunit.WebConnection; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; @@ -44,15 +45,12 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb */ @SuppressWarnings("resource") +@ExtendWith(MockitoExtension.class) class LocalHostWebClientTests { @Captor private ArgumentCaptor requestCaptor; - LocalHostWebClientTests() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null)) 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 8a543805cf..9272668202 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -25,9 +25,10 @@ import com.gargoylesoftware.htmlunit.WebConsole; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebWindow; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatcher; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.openqa.selenium.Capabilities; import org.springframework.core.env.Environment; @@ -45,13 +46,13 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class LocalHostWebConnectionHtmlUnitDriverTests { - @Mock - private WebClient webClient; + private final WebClient webClient; - LocalHostWebConnectionHtmlUnitDriverTests() { - MockitoAnnotations.initMocks(this); + LocalHostWebConnectionHtmlUnitDriverTests(@Mock WebClient webClient) { + this.webClient = webClient; given(this.webClient.getOptions()).willReturn(new WebClientOptions()); given(this.webClient.getWebConsole()).willReturn(new WebConsole()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java index 8abddb3996..c256afeb1c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java @@ -24,11 +24,12 @@ import java.net.URI; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; 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; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.buildpack.platform.docker.DockerApi.ContainerApi; import org.springframework.boot.buildpack.platform.docker.DockerApi.ImageApi; @@ -64,6 +65,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Scott Frederick */ +@ExtendWith(MockitoExtension.class) class DockerApiTests { private static final String API_URL = "/" + DockerApi.API_VERSION; @@ -81,7 +83,6 @@ class DockerApiTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.dockerApi = new DockerApi(this.http); } @@ -127,7 +128,6 @@ class DockerApiTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.api = DockerApiTests.this.dockerApi.image(); } @@ -232,7 +232,6 @@ class DockerApiTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.api = DockerApiTests.this.dockerApi.container(); } @@ -370,7 +369,6 @@ class DockerApiTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.api = DockerApiTests.this.dockerApi.volume(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java index 1e6e256c42..c4d7173c1f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java @@ -37,10 +37,11 @@ import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.buildpack.platform.docker.transport.HttpTransport.Response; import org.springframework.util.StreamUtils; @@ -58,6 +59,7 @@ import static org.mockito.Mockito.verify; * @author Mike Smithson * @author Scott Frederick */ +@ExtendWith(MockitoExtension.class) class HttpClientTransportTests { private static final String APPLICATION_JSON = "application/json"; @@ -89,16 +91,13 @@ class HttpClientTransportTests { @BeforeEach void setup() throws Exception { - MockitoAnnotations.initMocks(this); - given(this.client.execute(any(HttpHost.class), any(HttpRequest.class))).willReturn(this.response); - given(this.response.getEntity()).willReturn(this.entity); - given(this.response.getStatusLine()).willReturn(this.statusLine); this.http = new TestHttpClientTransport(this.client); this.uri = new URI("example"); } @Test void getShouldExecuteHttpGet() throws Exception { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(200); Response response = this.http.get(this.uri); @@ -112,6 +111,7 @@ class HttpClientTransportTests { @Test void postShouldExecuteHttpPost() throws Exception { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(200); Response response = this.http.post(this.uri); @@ -125,6 +125,7 @@ class HttpClientTransportTests { @Test void postWithContentShouldExecuteHttpPost() throws Exception { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(200); Response response = this.http.post(this.uri, APPLICATION_JSON, @@ -145,6 +146,7 @@ class HttpClientTransportTests { @Test void putWithContentShouldExecuteHttpPut() throws Exception { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(200); Response response = this.http.put(this.uri, APPLICATION_JSON, @@ -165,6 +167,7 @@ class HttpClientTransportTests { @Test void deleteShouldExecuteHttpDelete() throws IOException { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(200); Response response = this.http.delete(this.uri); @@ -178,6 +181,7 @@ class HttpClientTransportTests { @Test void executeWhenResponseIsIn400RangeShouldThrowDockerException() throws IOException { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("errors.json")); given(this.statusLine.getStatusCode()).willReturn(404); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) @@ -188,7 +192,8 @@ class HttpClientTransportTests { } @Test - void executeWhenResponseIsIn500RangeWithNoContentShouldThrowDockerException() { + void executeWhenResponseIsIn500RangeWithNoContentShouldThrowDockerException() throws IOException { + givenClientWillReturnResponse(); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) .satisfies((ex) -> { @@ -199,6 +204,7 @@ class HttpClientTransportTests { @Test void executeWhenResponseIsIn500RangeWithMessageShouldThrowDockerException() throws IOException { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("message.json")); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) @@ -210,6 +216,7 @@ class HttpClientTransportTests { @Test void executeWhenResponseIsIn500RangeWithOtherContentShouldThrowDockerException() throws IOException { + givenClientWillReturnResponse(); given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) @@ -233,6 +240,12 @@ class HttpClientTransportTests { return new String(out.toByteArray(), StandardCharsets.UTF_8); } + private void givenClientWillReturnResponse() throws IOException { + given(this.client.execute(any(HttpHost.class), any(HttpRequest.class))).willReturn(this.response); + given(this.response.getEntity()).willReturn(this.entity); + given(this.response.getStatusLine()).willReturn(this.statusLine); + } + /** * Test {@link HttpClientTransport} implementation. */ diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/build.gradle b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/build.gradle index b1863cbd7e..bd774a035e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/build.gradle +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/build.gradle @@ -13,4 +13,5 @@ dependencies { testImplementation("org.assertj:assertj-core") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java index 13646be6be..006529156f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java @@ -27,9 +27,10 @@ import java.util.zip.ZipOutputStream; 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.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -39,6 +40,7 @@ import static org.mockito.BDDMockito.given; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ExtractCommandTests { @TempDir @@ -57,17 +59,16 @@ class ExtractCommandTests { @BeforeEach void setup() throws Exception { - MockitoAnnotations.initMocks(this); this.jarFile = createJarFile("test.jar"); this.extract = new File(this.temp, "extract"); this.extract.mkdir(); - given(this.context.getJarFile()).willReturn(this.jarFile); - given(this.context.getWorkingDir()).willReturn(this.extract); this.command = new ExtractCommand(this.context, this.layers); } @Test void runExtractsLayers() throws Exception { + given(this.context.getJarFile()).willReturn(this.jarFile); + given(this.context.getWorkingDir()).willReturn(this.extract); this.command.run(Collections.emptyMap(), Collections.emptyList()); assertThat(this.extract.list()).containsOnly("a", "b", "c", "d"); assertThat(new File(this.extract, "a/a/a.jar")).exists(); @@ -78,6 +79,7 @@ class ExtractCommandTests { @Test void runWhenHasDestinationOptionExtractsLayers() { + given(this.context.getJarFile()).willReturn(this.jarFile); File out = new File(this.extract, "out"); this.command.run(Collections.singletonMap(ExtractCommand.DESTINATION_OPTION, out.getAbsolutePath()), Collections.emptyList()); @@ -89,6 +91,8 @@ class ExtractCommandTests { @Test void runWhenHasLayerParamsExtractsLimitedLayers() { + given(this.context.getJarFile()).willReturn(this.jarFile); + given(this.context.getWorkingDir()).willReturn(this.extract); this.command.run(Collections.emptyMap(), Arrays.asList("a", "c")); assertThat(this.extract.list()).containsOnly("a", "c"); assertThat(new File(this.extract, "a/a/a.jar")).exists(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ListCommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ListCommandTests.java index eebcf4c1e4..0c88c68e66 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ListCommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ListCommandTests.java @@ -28,9 +28,10 @@ import java.util.zip.ZipOutputStream; 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.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -41,6 +42,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ListCommandTests { @TempDir @@ -51,19 +53,18 @@ class ListCommandTests { private File jarFile; + private ListCommand command; + + private TestPrintStream out; + @BeforeEach void setup() throws Exception { - MockitoAnnotations.initMocks(this); this.jarFile = createJarFile("test.jar"); given(this.context.getJarFile()).willReturn(this.jarFile); this.command = new ListCommand(this.context); this.out = new TestPrintStream(this); } - private ListCommand command; - - private TestPrintStream out; - @Test void listLayersShouldListLayers() { Layers layers = IndexedLayers.get(this.context); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/build.gradle b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/build.gradle index 843dcd010e..b13fcf8925 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/build.gradle +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/build.gradle @@ -36,6 +36,7 @@ dependencies { testImplementation("org.assertj:assertj-core") testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.springframework:spring-core") } 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 9243bf26d3..47666041e9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -28,10 +28,11 @@ import org.apache.maven.model.Dependency; import org.apache.maven.plugin.logging.Log; 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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.loader.tools.Library; import org.springframework.boot.loader.tools.LibraryCallback; @@ -48,6 +49,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ArtifactsLibrariesTests { @Mock @@ -70,17 +72,15 @@ class ArtifactsLibrariesTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.artifacts = Collections.singleton(this.artifact); this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class)); - given(this.artifact.getFile()).willReturn(this.file); given(this.artifactHandler.getExtension()).willReturn("jar"); - given(this.artifact.getArtifactHandler()).willReturn(this.artifactHandler); } @Test void callbackForJars() throws Exception { - given(this.artifact.getType()).willReturn("jar"); + given(this.artifact.getFile()).willReturn(this.file); + given(this.artifact.getArtifactHandler()).willReturn(this.artifactHandler); given(this.artifact.getScope()).willReturn("compile"); this.libs.doWithLibraries(this.callback); verify(this.callback).library(this.libraryCaptor.capture()); @@ -92,9 +92,10 @@ class ArtifactsLibrariesTests { @Test void callbackWithUnpack() throws Exception { + given(this.artifact.getFile()).willReturn(this.file); + given(this.artifact.getArtifactHandler()).willReturn(this.artifactHandler); given(this.artifact.getGroupId()).willReturn("gid"); given(this.artifact.getArtifactId()).willReturn("aid"); - given(this.artifact.getType()).willReturn("jar"); given(this.artifact.getScope()).willReturn("compile"); Dependency unpack = new Dependency(); unpack.setGroupId("gid"); @@ -109,14 +110,12 @@ class ArtifactsLibrariesTests { void renamesDuplicates() throws Exception { Artifact artifact1 = mock(Artifact.class); Artifact artifact2 = mock(Artifact.class); - given(artifact1.getType()).willReturn("jar"); given(artifact1.getScope()).willReturn("compile"); given(artifact1.getGroupId()).willReturn("g1"); given(artifact1.getArtifactId()).willReturn("artifact"); given(artifact1.getBaseVersion()).willReturn("1.0"); given(artifact1.getFile()).willReturn(new File("a")); given(artifact1.getArtifactHandler()).willReturn(this.artifactHandler); - given(artifact2.getType()).willReturn("jar"); given(artifact2.getScope()).willReturn("compile"); given(artifact2.getGroupId()).willReturn("g2"); given(artifact2.getArtifactId()).willReturn("artifact"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java index f9d9846f4c..709a08cfb7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -25,7 +25,6 @@ import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterRegistration; -import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -34,6 +33,7 @@ import javax.servlet.ServletRegistration; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; /** @@ -66,27 +66,26 @@ public abstract class MockServletWebServer { private void initialize() { try { this.servletContext = mock(ServletContext.class); - given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willAnswer((invocation) -> { + lenient().doAnswer((invocation) -> { RegisteredServlet registeredServlet = new RegisteredServlet(invocation.getArgument(1)); MockServletWebServer.this.registeredServlets.add(registeredServlet); return registeredServlet.getRegistration(); - }); - given(this.servletContext.addFilter(anyString(), any(Filter.class))).willAnswer((invocation) -> { + }).when(this.servletContext).addServlet(anyString(), any(Servlet.class)); + lenient().doAnswer((invocation) -> { RegisteredFilter registeredFilter = new RegisteredFilter(invocation.getArgument(1)); MockServletWebServer.this.registeredFilters.add(registeredFilter); return registeredFilter.getRegistration(); - }); + }).when(this.servletContext).addFilter(anyString(), any(Filter.class)); final Map initParameters = new HashMap<>(); - given(this.servletContext.setInitParameter(anyString(), anyString())).will((invocation) -> { + lenient().doAnswer((invocation) -> { initParameters.put(invocation.getArgument(0), invocation.getArgument(1)); return null; - }); + }).when(this.servletContext).setInitParameter(anyString(), anyString()); given(this.servletContext.getInitParameterNames()) .willReturn(Collections.enumeration(initParameters.keySet())); - given(this.servletContext.getInitParameter(anyString())) - .willAnswer((invocation) -> initParameters.get(invocation.getArgument(0))); + lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))).when(this.servletContext) + .getInitParameter(anyString()); given(this.servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); - given(this.servletContext.getNamedDispatcher("default")).willReturn(mock(RequestDispatcher.class)); for (Initializer initializer : this.initializers) { initializer.onStartup(this.servletContext); } diff --git a/spring-boot-project/spring-boot/build.gradle b/spring-boot-project/spring-boot/build.gradle index 5a1219a834..1db702c445 100644 --- a/spring-boot-project/spring-boot/build.gradle +++ b/spring-boot-project/spring-boot/build.gradle @@ -92,6 +92,7 @@ dependencies { testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.mariadb.jdbc:mariadb-java-client") testImplementation("org.mockito:mockito-core") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.postgresql:postgresql") testImplementation("org.springframework:spring-context-support") testImplementation("org.springframework.data:spring-data-redis") 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 f91b4ec75b..fe4d18a7f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,12 +19,11 @@ package org.springframework.boot; import java.io.PrintStream; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.Banner.Mode; import org.springframework.boot.testsupport.system.CapturedOutput; @@ -47,7 +46,7 @@ import static org.mockito.Mockito.verify; * @author Michael Stummvoll * @author Michael Simons */ -@ExtendWith(OutputCaptureExtension.class) +@ExtendWith({ MockitoExtension.class, OutputCaptureExtension.class }) class BannerTests { private ConfigurableApplicationContext context; @@ -62,11 +61,6 @@ class BannerTests { @Captor private ArgumentCaptor> sourceClassCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void testDefaultBanner(CapturedOutput output) { SpringApplication application = createSpringApplication(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java index 51e4c10b8d..24db7cd2d6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java @@ -25,9 +25,10 @@ import java.util.function.Supplier; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.cloud.CloudPlatform; import org.springframework.boot.context.config.ConfigDataEnvironmentContributor.Kind; @@ -52,6 +53,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ConfigDataEnvironmentContributorsTests { private DeferredLogFactory logFactory = Supplier::get; @@ -69,7 +71,6 @@ class ConfigDataEnvironmentContributorsTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.environment = new MockEnvironment(); this.binder = Binder.get(this.environment); ConfigDataLocationResolvers resolvers = new ConfigDataLocationResolvers(this.logFactory, this.binder, null); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java index 7cf97d7de7..7ce9857b94 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java @@ -19,12 +19,13 @@ package org.springframework.boot.context.config; import java.util.Set; import java.util.function.Supplier; -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.mockito.Mock; import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.SpringApplication; import org.springframework.core.env.StandardEnvironment; @@ -46,13 +47,15 @@ import static org.mockito.Mockito.verifyNoInteractions; * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ConfigDataEnvironmentPostProcessorTests { - private ConfigDataEnvironment configDataEnvironment = mock(ConfigDataEnvironment.class); + private StandardEnvironment environment = new StandardEnvironment(); - private StandardEnvironment environment; + private SpringApplication application = new SpringApplication(); - private SpringApplication application; + @Mock + private ConfigDataEnvironment configDataEnvironment; @Spy private ConfigDataEnvironmentPostProcessor postProcessor = new ConfigDataEnvironmentPostProcessor(Supplier::get); @@ -63,13 +66,6 @@ class ConfigDataEnvironmentPostProcessorTests { @Captor private ArgumentCaptor resourceLoaderCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - this.application = new SpringApplication(); - this.environment = new StandardEnvironment(); - } - @Test @SuppressWarnings("deprecation") void defaultOrderMatchesDeprecatedListener() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java index 5c6e484163..9bf8b1d7bf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java @@ -23,8 +23,9 @@ import java.util.List; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.mock.env.MockPropertySource; @@ -38,6 +39,7 @@ import static org.mockito.BDDMockito.given; * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ConfigDataImporterTests { @Mock @@ -60,7 +62,6 @@ class ConfigDataImporterTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); given(this.activationContext.getProfiles()).willReturn(this.profiles); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java index f014c334dd..9b1032bad2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java @@ -23,10 +23,10 @@ import java.util.Collections; import java.util.List; import java.util.function.Supplier; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.logging.DeferredLogFactory; @@ -45,6 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class ConfigDataLocationResolversTests { private DeferredLogFactory logFactory = Supplier::get; @@ -60,11 +61,6 @@ class ConfigDataLocationResolversTests { private ResourceLoader resourceLoader = new DefaultResourceLoader(); - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenInjectingBinderCreatesResolver() { ConfigDataLocationResolvers resolvers = new ConfigDataLocationResolvers(this.logFactory, this.binder, 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 eac9731497..e50b925b46 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,10 +22,10 @@ import java.time.Duration; import java.util.List; import java.util.function.Consumer; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.boot.convert.ApplicationConversionService; @@ -48,16 +48,12 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Andy Wilkinson */ +@ExtendWith(MockitoExtension.class) class BindConverterTests { @Mock private Consumer propertyEditorInitializer; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenConversionServiceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> BindConverter.get(null, null)) 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 21c8b6298b..bb9b98d359 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,10 +22,10 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -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.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -41,6 +41,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * @author Phillip Webb * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) class BindResultTests { @Mock @@ -52,11 +53,6 @@ class BindResultTests { @Mock private Supplier supplier; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void getWhenHasValueShouldReturnValue() { BindResult result = BindResult.of("foo"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BoundPropertiesTrackingBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BoundPropertiesTrackingBindHandlerTests.java index 7f0f8dfaa5..a90c29e895 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BoundPropertiesTrackingBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BoundPropertiesTrackingBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +22,9 @@ import java.util.function.Consumer; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.context.properties.source.ConfigurationProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; @@ -39,6 +40,7 @@ import static org.mockito.Mockito.verify; * * @author Madhura Bhave */ +@ExtendWith(MockitoExtension.class) public class BoundPropertiesTrackingBindHandlerTests { private List sources = new ArrayList<>(); @@ -52,7 +54,6 @@ public class BoundPropertiesTrackingBindHandlerTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.binder = new Binder(this.sources); this.handler = new BoundPropertiesTrackingBindHandler(this.consumer); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/DefaultPropertiesPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/DefaultPropertiesPropertySourceTests.java index b3d9ac8d29..96d890ce0b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/DefaultPropertiesPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/DefaultPropertiesPropertySourceTests.java @@ -19,12 +19,12 @@ package org.springframework.boot.env; import java.util.Collections; import java.util.function.Consumer; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; @@ -40,6 +40,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class DefaultPropertiesPropertySourceTests { @Mock @@ -48,11 +49,6 @@ class DefaultPropertiesPropertySourceTests { @Captor private ArgumentCaptor captor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void nameIsDefaultProperties() { assertThat(DefaultPropertiesPropertySource.NAME).isEqualTo("defaultProperties"); 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 c369da0dec..bd709b426c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,8 +22,9 @@ import javax.sql.DataSource; 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.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -33,6 +34,7 @@ import static org.mockito.BDDMockito.given; * * @author Stephane Nicoll */ +@ExtendWith(MockitoExtension.class) class CompositeDataSourcePoolMetadataProviderTests { @Mock @@ -58,7 +60,6 @@ class CompositeDataSourcePoolMetadataProviderTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); given(this.firstProvider.getDataSourcePoolMetadata(this.firstDataSource)).willReturn(this.first); given(this.firstProvider.getDataSourcePoolMetadata(this.secondDataSource)).willReturn(this.second); } 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 75b038ab33..40f60d06bb 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 @@ -26,11 +26,11 @@ import java.util.Set; import java.util.function.Supplier; import org.apache.http.client.config.RequestConfig; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -76,6 +76,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * @author Kevin Strijbos * @author Ilya Lukyanovich */ +@ExtendWith(MockitoExtension.class) class RestTemplateBuilderTests { private RestTemplateBuilder builder = new RestTemplateBuilder(); @@ -86,11 +87,6 @@ class RestTemplateBuilderTests { @Mock private ClientHttpRequestInterceptor interceptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWhenCustomizersAreNullShouldThrowException() { RestTemplateCustomizer[] customizers = null; 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 395bb6e415..cb3ba8f7c3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,9 @@ import java.util.Map; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplateHandler; @@ -41,6 +42,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class RootUriTemplateHandlerTests { private URI uri; @@ -51,13 +53,9 @@ class RootUriTemplateHandlerTests { public UriTemplateHandler handler; @BeforeEach - @SuppressWarnings("unchecked") void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); this.uri = new URI("https://example.com/hello"); this.handler = new RootUriTemplateHandler("https://example.com", this.delegate); - given(this.delegate.expand(anyString(), any(Map.class))).willReturn(this.uri); - given(this.delegate.expand(anyString(), any(Object[].class))).willReturn(this.uri); } @Test @@ -73,7 +71,9 @@ class RootUriTemplateHandlerTests { } @Test + @SuppressWarnings("unchecked") void expandMapVariablesShouldPrefixRoot() { + given(this.delegate.expand(anyString(), any(Map.class))).willReturn(this.uri); HashMap uriVariables = new HashMap<>(); URI expanded = this.handler.expand("/hello", uriVariables); verify(this.delegate).expand("https://example.com/hello", uriVariables); @@ -81,7 +81,9 @@ class RootUriTemplateHandlerTests { } @Test + @SuppressWarnings("unchecked") void expandMapVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { + given(this.delegate.expand(anyString(), any(Map.class))).willReturn(this.uri); HashMap uriVariables = new HashMap<>(); URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); @@ -90,6 +92,7 @@ class RootUriTemplateHandlerTests { @Test void expandArrayVariablesShouldPrefixRoot() { + given(this.delegate.expand(anyString(), any(Object[].class))).willReturn(this.uri); Object[] uriVariables = new Object[0]; URI expanded = this.handler.expand("/hello", uriVariables); verify(this.delegate).expand("https://example.com/hello", uriVariables); @@ -98,6 +101,7 @@ class RootUriTemplateHandlerTests { @Test void expandArrayVariablesWhenPathDoesNotStartWithSlashShouldNotPrefixRoot() { + given(this.delegate.expand(anyString(), any(Object[].class))).willReturn(this.uri); Object[] uriVariables = new Object[0]; URI expanded = this.handler.expand("https://spring.io/hello", uriVariables); verify(this.delegate).expand("https://spring.io/hello", uriVariables); @@ -106,6 +110,7 @@ class RootUriTemplateHandlerTests { @Test void applyShouldWrapExistingTemplate() { + given(this.delegate.expand(anyString(), any(Object[].class))).willReturn(this.uri); 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/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index 8fdad62764..eb0adb7233 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,15 +17,15 @@ package org.springframework.boot.web.server; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; 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.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; @@ -40,6 +40,7 @@ import static org.mockito.Mockito.mock; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class WebServerFactoryCustomizerBeanPostProcessorTests { private WebServerFactoryCustomizerBeanPostProcessor processor = new WebServerFactoryCustomizerBeanPostProcessor(); @@ -49,7 +50,6 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.processor.setBeanFactory(this.beanFactory); } @@ -62,7 +62,6 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @Test void postProcessBeforeShouldReturnBean() { - addMockBeans(Collections.emptyMap()); Object bean = new Object(); Object result = this.processor.postProcessBeforeInitialization(bean, "foo"); assertThat(result).isSameAs(bean); @@ -70,7 +69,6 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @Test void postProcessAfterShouldReturnBean() { - addMockBeans(Collections.emptyMap()); Object bean = new Object(); Object result = this.processor.postProcessAfterInitialization(bean, "foo"); assertThat(result).isSameAs(bean); 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 af25143ba9..77c9e95139 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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. @@ -28,10 +28,10 @@ import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -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.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; @@ -46,6 +46,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) abstract class AbstractFilterRegistrationBeanTests { @Mock @@ -54,14 +55,9 @@ abstract class AbstractFilterRegistrationBeanTests { @Mock FilterRegistration.Dynamic registration; - @BeforeEach - void setupMocks() { - MockitoAnnotations.initMocks(this); - given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); - } - @Test void startupWithDefaults() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter()); @@ -71,6 +67,7 @@ abstract class AbstractFilterRegistrationBeanTests { @Test void startupWithSpecifiedValues() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setName("test"); bean.setAsyncSupported(false); @@ -135,6 +132,7 @@ abstract class AbstractFilterRegistrationBeanTests { @Test void setServletRegistrationBeanReplacesValue() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); AbstractFilterRegistrationBean bean = createFilterRegistrationBean(mockServletRegistration("a")); bean.setServletRegistrationBeans( new LinkedHashSet>(Collections.singletonList(mockServletRegistration("b")))); @@ -144,6 +142,7 @@ abstract class AbstractFilterRegistrationBeanTests { @Test void modifyInitParameters() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); @@ -181,6 +180,7 @@ abstract class AbstractFilterRegistrationBeanTests { @Test void withSpecificDispatcherTypes() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); @@ -190,6 +190,7 @@ abstract class AbstractFilterRegistrationBeanTests { @Test void withSpecificDispatcherTypesEnumSet() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); 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/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index ce325c59c0..2960aebbbc 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 @@ -32,7 +32,10 @@ import org.springframework.boot.web.servlet.mock.MockFilter; import org.springframework.web.filter.OncePerRequestFilter; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** @@ -84,6 +87,7 @@ class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { @Test void startupWithOncePerRequestDefaults() throws Exception { + given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration); FilterRegistrationBean bean = new FilterRegistrationBean<>(this.oncePerRequestFilter); bean.onStartup(this.servletContext); verify(this.servletContext).addFilter(eq("oncePerRequestFilter"), eq(this.oncePerRequestFilter)); 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 f7c65b1b23..ca1e9587a0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,10 @@ import java.util.EventListener; import javax.servlet.ServletContext; import javax.servlet.ServletContextListener; -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.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; @@ -36,6 +36,7 @@ import static org.mockito.Mockito.verify; * * @author Dave Syer */ +@ExtendWith(MockitoExtension.class) class ServletListenerRegistrationBeanTests { @Mock @@ -44,11 +45,6 @@ class ServletListenerRegistrationBeanTests { @Mock private ServletContext servletContext; - @BeforeEach - void setupMocks() { - MockitoAnnotations.initMocks(this); - } - @Test void startupWithDefaults() throws Exception { ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean<>( 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 302bd4283c..2d5ec9ad08 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,16 +22,15 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; -import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.web.servlet.mock.MockServlet; @@ -47,6 +46,7 @@ import static org.mockito.Mockito.verify; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class ServletRegistrationBeanTests { private final MockServlet servlet = new MockServlet(); @@ -60,15 +60,9 @@ class ServletRegistrationBeanTests { @Mock private FilterRegistration.Dynamic filterRegistration; - @BeforeEach - void setupMocks() { - MockitoAnnotations.initMocks(this); - given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); - given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.filterRegistration); - } - @Test void startupWithDefaults() throws Exception { + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); bean.onStartup(this.servletContext); verify(this.servletContext).addServlet("mockServlet", this.servlet); @@ -87,6 +81,7 @@ class ServletRegistrationBeanTests { @Test void startupWithSpecifiedValues() throws Exception { + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); ServletRegistrationBean bean = new ServletRegistrationBean<>(); bean.setName("test"); bean.setServlet(this.servlet); @@ -169,6 +164,7 @@ class ServletRegistrationBeanTests { @Test void setMappingReplacesValue() throws Exception { + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.setUrlMappings(new LinkedHashSet<>(Arrays.asList("/c", "/d"))); bean.onStartup(this.servletContext); @@ -177,6 +173,7 @@ class ServletRegistrationBeanTests { @Test void modifyInitParameters() throws Exception { + given(this.servletContext.addServlet(anyString(), any(Servlet.class))).willReturn(this.registration); ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet, "/a", "/b"); bean.addInitParameter("a", "b"); bean.getInitParameters().put("a", "c"); 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 82289d2cf2..154af24828 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 @@ -33,13 +33,12 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; 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; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanCreationException; @@ -94,20 +93,14 @@ import static org.mockito.Mockito.withSettings; * @author Phillip Webb * @author Stephane Nicoll */ -@ExtendWith(OutputCaptureExtension.class) +@ExtendWith({ OutputCaptureExtension.class, MockitoExtension.class }) class ServletWebServerApplicationContextTests { - private ServletWebServerApplicationContext context; + private ServletWebServerApplicationContext context = new ServletWebServerApplicationContext(); @Captor private ArgumentCaptor filterCaptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - this.context = new ServletWebServerApplicationContext(); - } - @AfterEach void cleanup() { this.context.close(); 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 31d18d94ed..707e8e744b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,10 @@ import java.util.Set; import javax.xml.transform.sax.SAXTransformerFactory; -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.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -55,6 +55,7 @@ import static org.mockito.Mockito.verifyNoInteractions; * @author Stephane Nicoll * @author Dmytro Nosan */ +@ExtendWith(MockitoExtension.class) class WebServiceTemplateBuilderTests { private final WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder(); @@ -65,11 +66,6 @@ class WebServiceTemplateBuilderTests { @Mock private ClientInterceptor interceptor; - @BeforeEach - void setup() { - MockitoAnnotations.initMocks(this); - } - @Test void createWithCustomizersShouldApplyCustomizers() { WebServiceTemplateCustomizer customizer = mock(WebServiceTemplateCustomizer.class); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/build.gradle b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/build.gradle index bf71f2ad8f..f7140cb00d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/build.gradle +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/build.gradle @@ -12,7 +12,8 @@ dependencies { runtimeOnly("com.h2database:h2") testImplementation(project(":spring-boot-project:spring-boot-starters:spring-boot-starter-test")) + testImplementation("net.sourceforge.htmlunit:htmlunit") + testImplementation("org.mockito:mockito-junit-jupiter") testImplementation("org.seleniumhq.selenium:selenium-api") testImplementation("org.seleniumhq.selenium:htmlunit-driver") - testImplementation("net.sourceforge.htmlunit:htmlunit") } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java index 600cf830a9..649f7feaed 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2020 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,9 @@ package smoketest.test.web; 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.mockito.junit.jupiter.MockitoExtension; import smoketest.test.domain.User; import smoketest.test.domain.UserRepository; import smoketest.test.domain.VehicleIdentificationNumber; @@ -37,6 +38,7 @@ import static org.mockito.BDDMockito.given; * * @author Phillip Webb */ +@ExtendWith(MockitoExtension.class) class UserVehicleServiceTests { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @@ -51,7 +53,6 @@ class UserVehicleServiceTests { @BeforeEach void setup() { - MockitoAnnotations.initMocks(this); this.service = new UserVehicleService(this.userRepository, this.vehicleDetailsService); }