Enforce use of BDDMockito

1. Replace Mockito.verify*() with BDDMockito.then()
2. Replace Mockito.doReturn() with BDDMockito.willReturn()
3. Adjust checkstyle rule

See gh-29178
pull/29667/head
Yanming Zhou 3 years ago committed by Stephane Nicoll
parent f60af4dbbd
commit b49418aaaf

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,12 +35,13 @@ import org.springframework.util.Base64Utils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Tests for {@link CloudFoundrySecurityInterceptor}. * Tests for {@link CloudFoundrySecurityInterceptor}.
* *
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class CloudFoundrySecurityInterceptorTests { class CloudFoundrySecurityInterceptorTests {
@ -115,7 +116,7 @@ class CloudFoundrySecurityInterceptorTests {
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class);
verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); then(this.tokenValidator).should().validate(tokenArgumentCaptor.capture());
Token token = tokenArgumentCaptor.getValue(); Token token = tokenArgumentCaptor.getValue();
assertThat(token.toString()).isEqualTo(accessToken); assertThat(token.toString()).isEqualTo(accessToken);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
@ -129,7 +130,7 @@ class CloudFoundrySecurityInterceptorTests {
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("info")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("info"));
ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class); ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class);
verify(this.tokenValidator).validate(tokenArgumentCaptor.capture()); then(this.tokenValidator).should().validate(tokenArgumentCaptor.capture());
Token token = tokenArgumentCaptor.getValue(); Token token = tokenArgumentCaptor.getValue();
assertThat(token.toString()).isEqualTo(accessToken); assertThat(token.toString()).isEqualTo(accessToken);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);

@ -33,7 +33,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException;
@ -46,12 +45,14 @@ import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
/** /**
* Tests for {@link TokenValidator}. * Tests for {@link TokenValidator}.
* *
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class TokenValidatorTests { class TokenValidatorTests {
@ -109,7 +110,7 @@ class TokenValidatorTests {
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}";
this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())));
verify(this.securityService).fetchTokenKeys(); then(this.securityService).should().fetchTokenKeys();
} }
@Test @Test
@ -119,7 +120,7 @@ class TokenValidatorTests {
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}";
this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())));
verify(this.securityService).fetchTokenKeys(); then(this.securityService).should().fetchTokenKeys();
} }
@Test @Test
@ -129,7 +130,7 @@ class TokenValidatorTests {
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}";
this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())));
verify(this.securityService, Mockito.never()).fetchTokenKeys(); then(this.securityService).should(never()).fetchTokenKeys();
} }
@Test @Test

@ -35,13 +35,14 @@ import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JmxEndpointAutoConfiguration}. * Tests for {@link JmxEndpointAutoConfiguration}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class JmxEndpointAutoConfigurationTests { class JmxEndpointAutoConfigurationTests {
@ -72,7 +73,7 @@ class JmxEndpointAutoConfigurationTests {
.withBean(EndpointObjectNameFactory.class, () -> factory).run((context) -> { .withBean(EndpointObjectNameFactory.class, () -> factory).run((context) -> {
ArgumentCaptor<ExposableJmxEndpoint> argumentCaptor = ArgumentCaptor ArgumentCaptor<ExposableJmxEndpoint> argumentCaptor = ArgumentCaptor
.forClass(ExposableJmxEndpoint.class); .forClass(ExposableJmxEndpoint.class);
verify(factory).getObjectName(argumentCaptor.capture()); then(factory).should().getObjectName(argumentCaptor.capture());
ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue(); ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue();
assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test"); assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test");
}); });

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,7 +33,7 @@ import org.springframework.context.annotation.Import;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
@ -46,6 +46,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* Tests for generating documentation describing {@link AuditEventsEndpoint}. * Tests for generating documentation describing {@link AuditEventsEndpoint}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@ -83,7 +84,7 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation
"Restricts the events to those with the given principal. Optional."), "Restricts the events to those with the given principal. Optional."),
parameterWithName("type") parameterWithName("type")
.description("Restricts the events to those with the given type. Optional.")))); .description("Restricts the events to those with the given type. Optional."))));
verify(this.repository).find("alice", now.toInstant(), "logout"); then(this.repository).should().find("alice", now.toInstant(), "logout");
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.restdocs.payload.JsonFieldType; import org.springframework.restdocs.payload.JsonFieldType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
@ -52,6 +52,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* Tests for generating documentation describing the {@link LoggersEndpoint}. * Tests for generating documentation describing the {@link LoggersEndpoint}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@ -114,7 +115,7 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest
.andExpect(status().isNoContent()) .andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("loggers/set", requestFields(fieldWithPath("configuredLevel") .andDo(MockMvcRestDocumentation.document("loggers/set", requestFields(fieldWithPath("configuredLevel")
.description("Level for the logger. May be omitted to clear the level.").optional()))); .description("Level for the logger. May be omitted to clear the level.").optional())));
verify(this.loggingSystem).setLogLevel("com.example", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("com.example", LogLevel.DEBUG);
} }
@Test @Test
@ -127,8 +128,8 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest
requestFields(fieldWithPath("configuredLevel").description( requestFields(fieldWithPath("configuredLevel").description(
"Level for the logger group. May be omitted to clear the level of the loggers.") "Level for the logger group. May be omitted to clear the level of the loggers.")
.optional()))); .optional())));
verify(this.loggingSystem).setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG);
verify(this.loggingSystem).setLogLevel("test.member2", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG);
resetLogger(); resetLogger();
} }
@ -142,7 +143,7 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest
this.mockMvc this.mockMvc
.perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear"));
verify(this.loggingSystem).setLogLevel("com.example", null); then(this.loggingSystem).should().setLogLevel("com.example", null);
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,7 +38,7 @@ import org.springframework.session.Session;
import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.TestPropertySource;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
@ -52,6 +52,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* Tests for generating documentation describing the {@link ShutdownEndpoint}. * Tests for generating documentation describing the {@link ShutdownEndpoint}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false") @TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false")
class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@ -102,7 +103,7 @@ class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTes
void deleteASession() throws Exception { void deleteASession() throws Exception {
this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent())
.andDo(document("sessions/delete")); .andDo(document("sessions/delete"));
verify(this.sessionRepository).deleteById(sessionTwo.getId()); then(this.sessionRepository).should().deleteById(sessionTwo.getId());
} }
private static MapSession createSession(Instant creationTime, Instant lastAccessedTime) { private static MapSession createSession(Instant creationTime, Instant lastAccessedTime) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,16 +35,16 @@ import org.springframework.beans.factory.ObjectProvider;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link MeterRegistryConfigurer}. * Tests for {@link MeterRegistryConfigurer}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class MeterRegistryConfigurerTests { class MeterRegistryConfigurerTests {
@ -77,7 +77,7 @@ class MeterRegistryConfigurerTests {
createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); createObjectProvider(this.filters), createObjectProvider(this.binders), false, false);
CompositeMeterRegistry composite = new CompositeMeterRegistry(); CompositeMeterRegistry composite = new CompositeMeterRegistry();
configurer.configure(composite); configurer.configure(composite);
verify(this.mockCustomizer).customize(composite); then(this.mockCustomizer).should().customize(composite);
} }
@Test @Test
@ -87,7 +87,7 @@ class MeterRegistryConfigurerTests {
MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers),
createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); createObjectProvider(this.filters), createObjectProvider(this.binders), false, false);
configurer.configure(this.mockRegistry); configurer.configure(this.mockRegistry);
verify(this.mockCustomizer).customize(this.mockRegistry); then(this.mockCustomizer).should().customize(this.mockRegistry);
} }
@Test @Test
@ -97,7 +97,7 @@ class MeterRegistryConfigurerTests {
MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers),
createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); createObjectProvider(this.filters), createObjectProvider(this.binders), false, false);
configurer.configure(this.mockRegistry); configurer.configure(this.mockRegistry);
verify(this.mockConfig).meterFilter(this.mockFilter); then(this.mockConfig).should().meterFilter(this.mockFilter);
} }
@Test @Test
@ -107,7 +107,7 @@ class MeterRegistryConfigurerTests {
MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers),
createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); createObjectProvider(this.filters), createObjectProvider(this.binders), false, false);
configurer.configure(this.mockRegistry); configurer.configure(this.mockRegistry);
verify(this.mockBinder).bindTo(this.mockRegistry); then(this.mockBinder).should().bindTo(this.mockRegistry);
} }
@Test @Test
@ -117,7 +117,7 @@ class MeterRegistryConfigurerTests {
createObjectProvider(this.filters), createObjectProvider(this.binders), false, true); createObjectProvider(this.filters), createObjectProvider(this.binders), false, true);
CompositeMeterRegistry composite = new CompositeMeterRegistry(); CompositeMeterRegistry composite = new CompositeMeterRegistry();
configurer.configure(composite); configurer.configure(composite);
verify(this.mockBinder).bindTo(composite); then(this.mockBinder).should().bindTo(composite);
} }
@Test @Test
@ -126,7 +126,7 @@ class MeterRegistryConfigurerTests {
MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers), MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(createObjectProvider(this.customizers),
createObjectProvider(this.filters), null, false, true); createObjectProvider(this.filters), null, false, true);
configurer.configure(this.mockRegistry); configurer.configure(this.mockRegistry);
verifyNoInteractions(this.mockBinder); then(this.mockBinder).shouldHaveNoInteractions();
} }
@Test @Test
@ -139,9 +139,9 @@ class MeterRegistryConfigurerTests {
createObjectProvider(this.filters), createObjectProvider(this.binders), false, false); createObjectProvider(this.filters), createObjectProvider(this.binders), false, false);
configurer.configure(this.mockRegistry); configurer.configure(this.mockRegistry);
InOrder ordered = inOrder(this.mockBinder, this.mockConfig, this.mockCustomizer); InOrder ordered = inOrder(this.mockBinder, this.mockConfig, this.mockCustomizer);
ordered.verify(this.mockCustomizer).customize(this.mockRegistry); then(this.mockCustomizer).should(ordered).customize(this.mockRegistry);
ordered.verify(this.mockConfig).meterFilter(this.mockFilter); then(this.mockConfig).should(ordered).meterFilter(this.mockFilter);
ordered.verify(this.mockBinder).bindTo(this.mockRegistry); then(this.mockBinder).should(ordered).bindTo(this.mockRegistry);
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,13 +33,14 @@ import org.springframework.core.annotation.Order;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link MetricsAutoConfiguration}. * Tests for {@link MetricsAutoConfiguration}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class MetricsAutoConfigurationTests { class MetricsAutoConfigurationTests {
@ -67,8 +68,8 @@ class MetricsAutoConfigurationTests {
assertThat(filters[0].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY); assertThat(filters[0].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY);
assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class); assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class);
assertThat(filters[2].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT); assertThat(filters[2].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT);
verify((MeterBinder) context.getBean("meterBinder")).bindTo(meterRegistry); then((MeterBinder) context.getBean("meterBinder")).should().bindTo(meterRegistry);
verify(context.getBean(MeterRegistryCustomizer.class)).customize(meterRegistry); then(context.getBean(MeterRegistryCustomizer.class)).should().customize(meterRegistry);
}); });
} }

@ -26,13 +26,14 @@ import org.springframework.data.repository.core.support.RepositoryFactorySupport
import org.springframework.util.function.SingletonSupplier; import org.springframework.util.function.SingletonSupplier;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link MetricsRepositoryMethodInvocationListenerBeanPostProcessor} . * Tests for {@link MetricsRepositoryMethodInvocationListenerBeanPostProcessor} .
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests { class MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests {
@ -49,10 +50,10 @@ class MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests {
assertThat(result).isSameAs(bean); assertThat(result).isSameAs(bean);
ArgumentCaptor<RepositoryFactoryCustomizer> customizer = ArgumentCaptor ArgumentCaptor<RepositoryFactoryCustomizer> customizer = ArgumentCaptor
.forClass(RepositoryFactoryCustomizer.class); .forClass(RepositoryFactoryCustomizer.class);
verify(bean).addRepositoryFactoryCustomizer(customizer.capture()); then(bean).should().addRepositoryFactoryCustomizer(customizer.capture());
RepositoryFactorySupport repositoryFactory = mock(RepositoryFactorySupport.class); RepositoryFactorySupport repositoryFactory = mock(RepositoryFactorySupport.class);
customizer.getValue().customize(repositoryFactory); customizer.getValue().customize(repositoryFactory);
verify(repositoryFactory).addInvocationListener(this.listener); then(repositoryFactory).should().addInvocationListener(this.listener);
} }
@Test @Test

@ -31,8 +31,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JerseyChildManagementContextConfiguration}. * Tests for {@link JerseyChildManagementContextConfiguration}.
@ -89,7 +89,7 @@ class JerseyChildManagementContextConfigurationTests {
ResourceConfig config = context.getBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class);
ManagementContextResourceConfigCustomizer customizer = context ManagementContextResourceConfigCustomizer customizer = context
.getBean(ManagementContextResourceConfigCustomizer.class); .getBean(ManagementContextResourceConfigCustomizer.class);
verify(customizer).customize(config); then(customizer).should().customize(config);
}); });
} }

@ -32,8 +32,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JerseySameManagementContextConfiguration}. * Tests for {@link JerseySameManagementContextConfiguration}.
@ -99,7 +99,7 @@ class JerseySameManagementContextConfigurationTests {
ResourceConfig config = context.getBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class);
ManagementContextResourceConfigCustomizer customizer = context ManagementContextResourceConfigCustomizer customizer = context
.getBean(ManagementContextResourceConfigCustomizer.class); .getBean(ManagementContextResourceConfigCustomizer.class);
verify(customizer).customize(config); then(customizer).should().customize(config);
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,13 +23,14 @@ import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository; import org.springframework.boot.actuate.audit.AuditEventRepository;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link AuditListener}. * Tests for {@link AuditListener}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class AuditListenerTests { class AuditListenerTests {
@ -39,7 +40,7 @@ class AuditListenerTests {
AuditEvent event = new AuditEvent("principal", "type", Collections.emptyMap()); AuditEvent event = new AuditEvent("principal", "type", Collections.emptyMap());
AuditListener listener = new AuditListener(repository); AuditListener listener = new AuditListener(repository);
listener.onApplicationEvent(new AuditApplicationEvent(event)); listener.onApplicationEvent(new AuditApplicationEvent(event));
verify(repository).add(event); then(repository).should().add(event);
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -34,14 +34,15 @@ import org.springframework.cache.support.SimpleCacheManager;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link CachesEndpoint}. * Tests for {@link CachesEndpoint}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class CachesEndpointTests { class CachesEndpointTests {
@ -126,8 +127,8 @@ class CachesEndpointTests {
Cache b = mockCache("b"); Cache b = mockCache("b");
CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b)));
endpoint.clearCaches(); endpoint.clearCaches();
verify(a).clear(); then(a).should().clear();
verify(b).clear(); then(b).should().clear();
} }
@Test @Test
@ -136,8 +137,8 @@ class CachesEndpointTests {
Cache b = mockCache("b"); Cache b = mockCache("b");
CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b))); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b)));
assertThat(endpoint.clearCache("a", null)).isTrue(); assertThat(endpoint.clearCache("a", null)).isTrue();
verify(a).clear(); then(a).should().clear();
verify(b, never()).clear(); then(b).should(never()).clear();
} }
@Test @Test
@ -161,9 +162,9 @@ class CachesEndpointTests {
cacheManagers.put("another", cacheManager(anotherA)); cacheManagers.put("another", cacheManager(anotherA));
CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers);
assertThat(endpoint.clearCache("a", "another")).isTrue(); assertThat(endpoint.clearCache("a", "another")).isTrue();
verify(a, never()).clear(); then(a).should(never()).clear();
verify(anotherA).clear(); then(anotherA).should().clear();
verify(b, never()).clear(); then(b).should(never()).clear();
} }
@Test @Test
@ -171,7 +172,7 @@ class CachesEndpointTests {
Cache a = mockCache("a"); Cache a = mockCache("a");
CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a)));
assertThat(endpoint.clearCache("unknown", null)).isFalse(); assertThat(endpoint.clearCache("unknown", null)).isFalse();
verify(a, never()).clear(); then(a).should(never()).clear();
} }
@Test @Test
@ -179,7 +180,7 @@ class CachesEndpointTests {
Cache a = mockCache("a"); Cache a = mockCache("a");
CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a))); CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a)));
assertThat(endpoint.clearCache("a", "unknown")).isFalse(); assertThat(endpoint.clearCache("a", "unknown")).isFalse();
verify(a, never()).clear(); then(a).should(never()).clear();
} }
private CacheManager cacheManager(Cache... caches) { private CacheManager cacheManager(Cache... caches) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -34,14 +34,15 @@ import org.springframework.boot.actuate.health.Status;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link CouchbaseHealthIndicator} * Tests for {@link CouchbaseHealthIndicator}
* *
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class CouchbaseHealthIndicatorTests { class CouchbaseHealthIndicatorTests {
@ -61,7 +62,7 @@ class CouchbaseHealthIndicatorTests {
assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk");
assertThat(health.getDetails()).containsKey("endpoints"); assertThat(health.getDetails()).containsKey("endpoints");
assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(1); assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(1);
verify(cluster).diagnostics(); then(cluster).should().diagnostics();
} }
@Test @Test
@ -82,7 +83,7 @@ class CouchbaseHealthIndicatorTests {
assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk");
assertThat(health.getDetails()).containsKey("endpoints"); assertThat(health.getDetails()).containsKey("endpoints");
assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(2); assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(2);
verify(cluster).diagnostics(); then(cluster).should().diagnostics();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,8 +35,8 @@ import org.springframework.boot.actuate.health.Status;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link CouchbaseReactiveHealthIndicator}. * Tests for {@link CouchbaseReactiveHealthIndicator}.
@ -58,7 +58,7 @@ class CouchbaseReactiveHealthIndicatorTests {
assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk");
assertThat(health.getDetails()).containsKey("endpoints"); assertThat(health.getDetails()).containsKey("endpoints");
assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(1); assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(1);
verify(cluster).diagnostics(); then(cluster).should().diagnostics();
} }
@Test @Test
@ -79,7 +79,7 @@ class CouchbaseReactiveHealthIndicatorTests {
assertThat(health.getDetails()).containsEntry("sdk", "test-sdk"); assertThat(health.getDetails()).containsEntry("sdk", "test-sdk");
assertThat(health.getDetails()).containsKey("endpoints"); assertThat(health.getDetails()).containsKey("endpoints");
assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(2); assertThat((List<Map<String, Object>>) health.getDetails().get("endpoints")).hasSize(2);
verify(cluster).diagnostics(); then(cluster).should().diagnostics();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,14 +30,15 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ConversionServiceParameterValueMapper}. * Tests for {@link ConversionServiceParameterValueMapper}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class ConversionServiceParameterValueMapperTests { class ConversionServiceParameterValueMapperTests {
@ -47,7 +48,7 @@ class ConversionServiceParameterValueMapperTests {
ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService);
Object mapped = mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); Object mapped = mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123");
assertThat(mapped).isEqualTo(123); assertThat(mapped).isEqualTo(123);
verify(conversionService).convert("123", Integer.class); then(conversionService).should().convert("123", Integer.class);
} }
@Test @Test

@ -38,13 +38,14 @@ import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Tests for {@link CachingOperationInvokerAdvisor}. * Tests for {@link CachingOperationInvokerAdvisor}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class CachingOperationInvokerAdvisorTests { class CachingOperationInvokerAdvisorTests {
@ -85,7 +86,7 @@ class CachingOperationInvokerAdvisorTests {
OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters,
this.invoker); this.invoker);
assertThat(advised).isSameAs(this.invoker); assertThat(advised).isSameAs(this.invoker);
verify(this.timeToLive).apply(EndpointId.of("foo")); then(this.timeToLive).should().apply(EndpointId.of("foo"));
} }
@Test @Test
@ -95,7 +96,7 @@ class CachingOperationInvokerAdvisorTests {
OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters, OperationInvoker advised = this.advisor.apply(EndpointId.of("foo"), OperationType.READ, parameters,
this.invoker); this.invoker);
assertThat(advised).isSameAs(this.invoker); assertThat(advised).isSameAs(this.invoker);
verify(this.timeToLive).apply(EndpointId.of("foo")); then(this.timeToLive).should().apply(EndpointId.of("foo"));
} }
@Test @Test

@ -37,10 +37,9 @@ import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Tests for {@link CachingOperationInvoker}. * Tests for {@link CachingOperationInvoker}.
@ -48,6 +47,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Christoph Dreis * @author Christoph Dreis
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class CachingOperationInvokerTests { class CachingOperationInvokerTests {
@ -143,10 +143,10 @@ class CachingOperationInvokerTests {
CachingOperationInvoker invoker = new CachingOperationInvoker(target, CACHE_TTL); CachingOperationInvoker invoker = new CachingOperationInvoker(target, CACHE_TTL);
Object response = invoker.invoke(context); Object response = invoker.invoke(context);
assertThat(response).isSameAs(expected); assertThat(response).isSameAs(expected);
verify(target, times(1)).invoke(context); then(target).should().invoke(context);
Object cachedResponse = invoker.invoke(context); Object cachedResponse = invoker.invoke(context);
assertThat(cachedResponse).isSameAs(response); assertThat(cachedResponse).isSameAs(response);
verifyNoMoreInteractions(target); then(target).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -161,7 +161,7 @@ class CachingOperationInvokerTests {
invoker.invoke(context); invoker.invoke(context);
invoker.invoke(context); invoker.invoke(context);
invoker.invoke(context); invoker.invoke(context);
verify(target, times(3)).invoke(context); then(target).should(times(3)).invoke(context);
} }
@Test @Test
@ -180,7 +180,7 @@ class CachingOperationInvokerTests {
assertThat(invoker.invoke(context)).isEqualTo(result1); assertThat(invoker.invoke(context)).isEqualTo(result1);
assertThat(invoker.invoke(context)).isEqualTo(result2); assertThat(invoker.invoke(context)).isEqualTo(result2);
assertThat(invoker.invoke(context)).isEqualTo(result3); assertThat(invoker.invoke(context)).isEqualTo(result3);
verify(target, times(3)).invoke(context); then(target).should(times(3)).invoke(context);
} }
@Test @Test
@ -201,8 +201,8 @@ class CachingOperationInvokerTests {
assertThat(invoker.invoke(authenticatedContext)).isEqualTo(authenticatedResult); assertThat(invoker.invoke(authenticatedContext)).isEqualTo(authenticatedResult);
assertThat(invoker.invoke(anonymousContext)).isEqualTo(anonymousResult); assertThat(invoker.invoke(anonymousContext)).isEqualTo(anonymousResult);
assertThat(invoker.invoke(authenticatedContext)).isEqualTo(authenticatedResult); assertThat(invoker.invoke(authenticatedContext)).isEqualTo(authenticatedResult);
verify(target, times(1)).invoke(anonymousContext); then(target).should().invoke(anonymousContext);
verify(target, times(1)).invoke(authenticatedContext); then(target).should().invoke(authenticatedContext);
} }
@Test @Test
@ -218,7 +218,7 @@ class CachingOperationInvokerTests {
Thread.sleep(10); Thread.sleep(10);
} }
invoker.invoke(context); invoker.invoke(context);
verify(target, times(2)).invoke(context); then(target).should(times(2)).invoke(context);
} }
@Test @Test
@ -235,10 +235,10 @@ class CachingOperationInvokerTests {
CachingOperationInvoker invoker = new CachingOperationInvoker(target, CACHE_TTL); CachingOperationInvoker invoker = new CachingOperationInvoker(target, CACHE_TTL);
Object response = invoker.invoke(contextV2); Object response = invoker.invoke(contextV2);
assertThat(response).isSameAs(expectedV2); assertThat(response).isSameAs(expectedV2);
verify(target, times(1)).invoke(contextV2); then(target).should().invoke(contextV2);
Object cachedResponse = invoker.invoke(contextV3); Object cachedResponse = invoker.invoke(contextV3);
assertThat(cachedResponse).isNotSameAs(response); assertThat(cachedResponse).isNotSameAs(response);
verify(target, times(1)).invoke(contextV3); then(target).should().invoke(contextV3);
} }
private static class MonoOperationInvoker implements OperationInvoker { private static class MonoOperationInvoker implements OperationInvoker {

@ -37,15 +37,16 @@ import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link EndpointMBean}. * Tests for {@link EndpointMBean}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class EndpointMBeanTests { class EndpointMBeanTests {
@ -160,8 +161,8 @@ class EndpointMBeanTests {
TestJmxOperationResponseMapper responseMapper = spy(this.responseMapper); TestJmxOperationResponseMapper responseMapper = spy(this.responseMapper);
EndpointMBean bean = new EndpointMBean(responseMapper, null, this.endpoint); EndpointMBean bean = new EndpointMBean(responseMapper, null, this.endpoint);
bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
verify(responseMapper).mapResponseType(String.class); then(responseMapper).should().mapResponseType(String.class);
verify(responseMapper).mapResponse("result"); then(responseMapper).should().mapResponse("result");
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,13 +32,14 @@ import org.springframework.boot.test.json.BasicJsonTester;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JacksonJmxOperationResponseMapper} * Tests for {@link JacksonJmxOperationResponseMapper}
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class JacksonJmxOperationResponseMapperTests { class JacksonJmxOperationResponseMapperTests {
@ -59,7 +60,7 @@ class JacksonJmxOperationResponseMapperTests {
JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(objectMapper); JacksonJmxOperationResponseMapper mapper = new JacksonJmxOperationResponseMapper(objectMapper);
Set<String> response = Collections.singleton("test"); Set<String> response = Collections.singleton("test");
mapper.mapResponse(response); mapper.mapResponse(response);
verify(objectMapper).convertValue(eq(response), any(JavaType.class)); then(objectMapper).should().convertValue(eq(response), any(JavaType.class));
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,14 +43,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JmxEndpointExporter}. * Tests for {@link JmxEndpointExporter}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class JmxEndpointExporterTests { class JmxEndpointExporterTests {
@ -112,7 +113,7 @@ class JmxEndpointExporterTests {
void afterPropertiesSetShouldRegisterMBeans() throws Exception { void afterPropertiesSetShouldRegisterMBeans() throws Exception {
this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation()));
this.exporter.afterPropertiesSet(); this.exporter.afterPropertiesSet();
verify(this.mBeanServer).registerMBean(this.objectCaptor.capture(), this.objectNameCaptor.capture()); then(this.mBeanServer).should().registerMBean(this.objectCaptor.capture(), this.objectNameCaptor.capture());
assertThat(this.objectCaptor.getValue()).isInstanceOf(EndpointMBean.class); assertThat(this.objectCaptor.getValue()).isInstanceOf(EndpointMBean.class);
assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test"); assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test");
} }
@ -121,7 +122,7 @@ class JmxEndpointExporterTests {
void registerShouldUseObjectNameFactory() throws Exception { void registerShouldUseObjectNameFactory() throws Exception {
this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation()));
this.exporter.afterPropertiesSet(); this.exporter.afterPropertiesSet();
verify(this.objectNameFactory).getObjectName(any(ExposableJmxEndpoint.class)); then(this.objectNameFactory).should().getObjectName(any(ExposableJmxEndpoint.class));
} }
@Test @Test
@ -147,7 +148,7 @@ class JmxEndpointExporterTests {
this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation()));
this.exporter.afterPropertiesSet(); this.exporter.afterPropertiesSet();
this.exporter.destroy(); this.exporter.destroy();
verify(this.mBeanServer).unregisterMBean(this.objectNameCaptor.capture()); then(this.mBeanServer).should().unregisterMBean(this.objectNameCaptor.capture());
assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test"); assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test");
} }

@ -40,14 +40,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ServletEndpointRegistrar}. * Tests for {@link ServletEndpointRegistrar}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class ServletEndpointRegistrarTests { class ServletEndpointRegistrarTests {
@ -92,9 +93,9 @@ class ServletEndpointRegistrarTests {
ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class));
ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, Collections.singleton(endpoint)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, Collections.singleton(endpoint));
registrar.onStartup(this.servletContext); registrar.onStartup(this.servletContext);
verify(this.servletContext).addServlet(eq("test-actuator-endpoint"), this.servlet.capture()); then(this.servletContext).should().addServlet(eq("test-actuator-endpoint"), this.servlet.capture());
assertThat(this.servlet.getValue()).isInstanceOf(TestServlet.class); assertThat(this.servlet.getValue()).isInstanceOf(TestServlet.class);
verify(this.dynamic).addMapping(expectedMapping); then(this.dynamic).should().addMapping(expectedMapping);
} }
@Test @Test
@ -104,7 +105,7 @@ class ServletEndpointRegistrarTests {
new EndpointServlet(TestServlet.class).withInitParameter("a", "b")); new EndpointServlet(TestServlet.class).withInitParameter("a", "b"));
ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint));
registrar.onStartup(this.servletContext); registrar.onStartup(this.servletContext);
verify(this.dynamic).setInitParameters(Collections.singletonMap("a", "b")); then(this.dynamic).should().setInitParameters(Collections.singletonMap("a", "b"));
} }
@Test @Test
@ -113,7 +114,7 @@ class ServletEndpointRegistrarTests {
ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class).withLoadOnStartup(7)); ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class).withLoadOnStartup(7));
ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint));
registrar.onStartup(this.servletContext); registrar.onStartup(this.servletContext);
verify(this.dynamic).setLoadOnStartup(7); then(this.dynamic).should().setLoadOnStartup(7);
} }
@Test @Test
@ -122,7 +123,7 @@ class ServletEndpointRegistrarTests {
ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class)); ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class));
ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint)); ServletEndpointRegistrar registrar = new ServletEndpointRegistrar("/actuator", Collections.singleton(endpoint));
registrar.onStartup(this.servletContext); registrar.onStartup(this.servletContext);
verify(this.dynamic).setLoadOnStartup(-1); then(this.dynamic).should().setLoadOnStartup(-1);
} }
private ExposableServletEndpoint mockEndpoint(EndpointServlet endpointServlet) { private ExposableServletEndpoint mockEndpoint(EndpointServlet endpointServlet) {

@ -54,7 +54,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Abstract base class for web endpoint integration tests. * Abstract base class for web endpoint integration tests.
@ -62,6 +62,7 @@ import static org.mockito.Mockito.verify;
* @param <T> the type of application context used by the tests * @param <T> the type of application context used by the tests
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Scott Frederick * @author Scott Frederick
* @author Yanming Zhou
*/ */
public abstract class AbstractWebEndpointIntegrationTests<T extends ConfigurableApplicationContext & AnnotationConfigRegistry> { public abstract class AbstractWebEndpointIntegrationTests<T extends ConfigurableApplicationContext & AnnotationConfigRegistry> {
@ -188,7 +189,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
void writeOperationWithVoidResponse() { void writeOperationWithVoidResponse() {
load(VoidWriteResponseEndpointConfiguration.class, (context, client) -> { load(VoidWriteResponseEndpointConfiguration.class, (context, client) -> {
client.post().uri("/voidwrite").exchange().expectStatus().isNoContent().expectBody().isEmpty(); client.post().uri("/voidwrite").exchange().expectStatus().isNoContent().expectBody().isEmpty();
verify(context.getBean(EndpointDelegate.class)).write(); then(context.getBean(EndpointDelegate.class)).should().write();
}); });
} }
@ -202,7 +203,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
void deleteOperationWithVoidResponse() { void deleteOperationWithVoidResponse() {
load(VoidDeleteResponseEndpointConfiguration.class, (context, client) -> { load(VoidDeleteResponseEndpointConfiguration.class, (context, client) -> {
client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent().expectBody().isEmpty(); client.delete().uri("/voiddelete").exchange().expectStatus().isNoContent().expectBody().isEmpty();
verify(context.getBean(EndpointDelegate.class)).delete(); then(context.getBean(EndpointDelegate.class)).should().delete();
}); });
} }
@ -212,7 +213,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
Map<String, Object> body = new HashMap<>(); Map<String, Object> body = new HashMap<>();
body.put("foo", "one"); body.put("foo", "one");
client.post().uri("/test").bodyValue(body).exchange().expectStatus().isNoContent().expectBody().isEmpty(); client.post().uri("/test").bodyValue(body).exchange().expectStatus().isNoContent().expectBody().isEmpty();
verify(context.getBean(EndpointDelegate.class)).write("one", null); then(context.getBean(EndpointDelegate.class)).should().write("one", null);
}); });
} }
@ -221,7 +222,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
load(TestEndpointConfiguration.class, (context, client) -> { load(TestEndpointConfiguration.class, (context, client) -> {
client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent() client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent()
.expectBody().isEmpty(); .expectBody().isEmpty();
verify(context.getBean(EndpointDelegate.class)).write(null, null); then(context.getBean(EndpointDelegate.class)).should().write(null, null);
}); });
} }

@ -28,13 +28,14 @@ import org.springframework.boot.actuate.health.Status;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link InfluxDbHealthIndicator}. * Tests for {@link InfluxDbHealthIndicator}.
* *
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Yanming Zhou
*/ */
class InfluxDbHealthIndicatorTests { class InfluxDbHealthIndicatorTests {
@ -48,7 +49,7 @@ class InfluxDbHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails().get("version")).isEqualTo("0.9"); assertThat(health.getDetails().get("version")).isEqualTo("0.9");
verify(influxDb).ping(); then(influxDb).should().ping();
} }
@Test @Test
@ -59,7 +60,7 @@ class InfluxDbHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat((String) health.getDetails().get("error")).contains("Connection failed"); assertThat((String) health.getDetails().get("error")).contains("Connection failed");
verify(influxDb).ping(); then(influxDb).should().ping();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,13 +23,14 @@ import org.springframework.integration.graph.IntegrationGraphServer;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link IntegrationGraphEndpoint}. * Tests for {@link IntegrationGraphEndpoint}.
* *
* @author Tim Ysewyn * @author Tim Ysewyn
* @author Yanming Zhou
*/ */
class IntegrationGraphEndpointTests { class IntegrationGraphEndpointTests {
@ -42,14 +43,14 @@ class IntegrationGraphEndpointTests {
Graph mockedGraph = mock(Graph.class); Graph mockedGraph = mock(Graph.class);
given(this.server.getGraph()).willReturn(mockedGraph); given(this.server.getGraph()).willReturn(mockedGraph);
Graph graph = this.endpoint.graph(); Graph graph = this.endpoint.graph();
verify(this.server).getGraph(); then(this.server).should().getGraph();
assertThat(graph).isEqualTo(mockedGraph); assertThat(graph).isEqualTo(mockedGraph);
} }
@Test @Test
void writeOperationShouldRebuildGraph() { void writeOperationShouldRebuildGraph() {
this.endpoint.rebuild(); this.endpoint.rebuild();
verify(this.server).rebuild(); then(this.server).should().rebuild();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -34,15 +34,16 @@ import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link DataSourceHealthIndicator}. * Tests for {@link DataSourceHealthIndicator}.
* *
* @author Dave Syer * @author Dave Syer
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class DataSourceHealthIndicatorTests { class DataSourceHealthIndicatorTests {
@ -106,7 +107,7 @@ class DataSourceHealthIndicatorTests {
this.indicator.setDataSource(dataSource); this.indicator.setDataSource(dataSource);
Health health = this.indicator.health(); Health health = this.indicator.health();
assertThat(health.getDetails().get("database")).isNotNull(); assertThat(health.getDetails().get("database")).isNotNull();
verify(connection, times(2)).close(); then(connection).should(times(2)).close();
} }
@Test @Test

@ -30,16 +30,16 @@ import org.springframework.boot.actuate.health.Status;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JmsHealthIndicator}. * Tests for {@link JmsHealthIndicator}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class JmsHealthIndicatorTests { class JmsHealthIndicatorTests {
@ -55,7 +55,7 @@ class JmsHealthIndicatorTests {
Health health = indicator.health(); Health health = indicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails().get("provider")).isEqualTo("JMS test provider"); assertThat(health.getDetails().get("provider")).isEqualTo("JMS test provider");
verify(connection, times(1)).close(); then(connection).should().close();
} }
@Test @Test
@ -80,7 +80,7 @@ class JmsHealthIndicatorTests {
Health health = indicator.health(); Health health = indicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails().get("provider")).isNull(); assertThat(health.getDetails().get("provider")).isNull();
verify(connection, times(1)).close(); then(connection).should().close();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -27,13 +27,14 @@ import org.springframework.ldap.core.LdapTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link LdapHealthIndicator} * Tests for {@link LdapHealthIndicator}
* *
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Yanming Zhou
*/ */
class LdapHealthIndicatorTests { class LdapHealthIndicatorTests {
@ -46,7 +47,7 @@ class LdapHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails().get("version")).isEqualTo("3"); assertThat(health.getDetails().get("version")).isEqualTo("3");
verify(ldapTemplate).executeReadOnly((ContextExecutor<String>) any()); then(ldapTemplate).should().executeReadOnly((ContextExecutor<String>) any());
} }
@Test @Test
@ -59,7 +60,7 @@ class LdapHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat((String) health.getDetails().get("error")).contains("Connection failed"); assertThat((String) health.getDetails().get("error")).contains("Connection failed");
verify(ldapTemplate).executeReadOnly((ContextExecutor<String>) any()); then(ldapTemplate).should().executeReadOnly((ContextExecutor<String>) any());
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,8 +35,8 @@ import org.springframework.boot.logging.LoggingSystem;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link LoggersEndpoint}. * Tests for {@link LoggersEndpoint}.
@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author HaiTao Zhang * @author HaiTao Zhang
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
class LoggersEndpointTests { class LoggersEndpointTests {
@ -120,25 +121,25 @@ class LoggersEndpointTests {
@Test @Test
void configureLogLevelShouldSetLevelOnLoggingSystem() { void configureLogLevelShouldSetLevelOnLoggingSystem() {
new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("ROOT", LogLevel.DEBUG); new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("ROOT", LogLevel.DEBUG);
verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG);
} }
@Test @Test
void configureLogLevelWithNullSetsLevelOnLoggingSystemToNull() { void configureLogLevelWithNullSetsLevelOnLoggingSystemToNull() {
new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("ROOT", null); new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("ROOT", null);
verify(this.loggingSystem).setLogLevel("ROOT", null); then(this.loggingSystem).should().setLogLevel("ROOT", null);
} }
@Test @Test
void configureLogLevelInLoggerGroupShouldSetLevelOnLoggingSystem() { void configureLogLevelInLoggerGroupShouldSetLevelOnLoggingSystem() {
new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("test", LogLevel.DEBUG); new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("test", LogLevel.DEBUG);
verify(this.loggingSystem).setLogLevel("test.member", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member", LogLevel.DEBUG);
} }
@Test @Test
void configureLogLevelWithNullInLoggerGroupShouldSetLevelOnLoggingSystem() { void configureLogLevelWithNullInLoggerGroupShouldSetLevelOnLoggingSystem() {
new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("test", null); new LoggersEndpoint(this.loggingSystem, this.loggerGroups).configureLogLevel("test", null);
verify(this.loggingSystem).setLogLevel("test.member", null); then(this.loggingSystem).should().setLogLevel("test.member", null);
} }
} }

@ -43,9 +43,8 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Integration tests for {@link LoggersEndpoint} when exposed via Jersey, Spring MVC, and * Integration tests for {@link LoggersEndpoint} when exposed via Jersey, Spring MVC, and
@ -58,6 +57,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author HaiTao Zhang * @author HaiTao Zhang
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
class LoggersEndpointWebIntegrationTests { class LoggersEndpointWebIntegrationTests {
@ -124,7 +124,7 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON)
.bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus()
.isNoContent(); .isNoContent();
verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG);
} }
@WebEndpointTest @WebEndpointTest
@ -132,7 +132,7 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V2_JSON)) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V2_JSON))
.bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus()
.isNoContent(); .isNoContent();
verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG);
} }
@WebEndpointTest @WebEndpointTest
@ -140,7 +140,7 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON))
.bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus()
.isNoContent(); .isNoContent();
verify(this.loggingSystem).setLogLevel("ROOT", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG);
} }
@WebEndpointTest @WebEndpointTest
@ -148,8 +148,8 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V2_JSON)) this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V2_JSON))
.bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus()
.isNoContent(); .isNoContent();
verify(this.loggingSystem).setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG);
verify(this.loggingSystem).setLogLevel("test.member2", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG);
} }
@WebEndpointTest @WebEndpointTest
@ -157,8 +157,8 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/test").contentType(MediaType.APPLICATION_JSON) this.client.post().uri("/actuator/loggers/test").contentType(MediaType.APPLICATION_JSON)
.bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus()
.isNoContent(); .isNoContent();
verify(this.loggingSystem).setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG);
verify(this.loggingSystem).setLogLevel("test.member2", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG);
} }
@WebEndpointTest @WebEndpointTest
@ -166,37 +166,37 @@ class LoggersEndpointWebIntegrationTests {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON)
.bodyValue(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus() .bodyValue(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus()
.isBadRequest(); .isBadRequest();
verifyNoInteractions(this.loggingSystem); then(this.loggingSystem).shouldHaveNoInteractions();
} }
@WebEndpointTest @WebEndpointTest
void setLoggerWithNullLogLevel() { void setLoggerWithNullLogLevel() {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON))
.bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent();
verify(this.loggingSystem).setLogLevel("ROOT", null); then(this.loggingSystem).should().setLogLevel("ROOT", null);
} }
@WebEndpointTest @WebEndpointTest
void setLoggerWithNoLogLevel() { void setLoggerWithNoLogLevel() {
this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON))
.bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent();
verify(this.loggingSystem).setLogLevel("ROOT", null); then(this.loggingSystem).should().setLogLevel("ROOT", null);
} }
@WebEndpointTest @WebEndpointTest
void setLoggerGroupWithNullLogLevel() { void setLoggerGroupWithNullLogLevel() {
this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON))
.bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent();
verify(this.loggingSystem).setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member1", null);
verify(this.loggingSystem).setLogLevel("test.member2", null); then(this.loggingSystem).should().setLogLevel("test.member2", null);
} }
@WebEndpointTest @WebEndpointTest
void setLoggerGroupWithNoLogLevel() { void setLoggerGroupWithNoLogLevel() {
this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON))
.bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent();
verify(this.loggingSystem).setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member1", null);
verify(this.loggingSystem).setLogLevel("test.member2", null); then(this.loggingSystem).should().setLogLevel("test.member2", null);
} }
@WebEndpointTest @WebEndpointTest

@ -39,16 +39,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link PrometheusPushGatewayManager}. * Tests for {@link PrometheusPushGatewayManager}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class PrometheusPushGatewayManagerTests { class PrometheusPushGatewayManagerTests {
@ -110,9 +110,9 @@ class PrometheusPushGatewayManagerTests {
void createShouldSchedulePushAsFixedRate() throws Exception { void createShouldSchedulePushAsFixedRate() throws Exception {
new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job",
this.groupingKey, null); this.groupingKey, null);
verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); then(this.scheduler).should().scheduleAtFixedRate(this.task.capture(), eq(this.pushRate));
this.task.getValue().run(); this.task.getValue().run();
verify(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); then(this.pushGateway).should().pushAdd(this.registry, "job", this.groupingKey);
} }
@Test @Test
@ -122,7 +122,7 @@ class PrometheusPushGatewayManagerTests {
PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry,
ownedScheduler, this.pushRate, "job", this.groupingKey, null); ownedScheduler, this.pushRate, "job", this.groupingKey, null);
manager.shutdown(); manager.shutdown();
verify(ownedScheduler).shutdown(); then(ownedScheduler).should().shutdown();
} }
@Test @Test
@ -132,7 +132,7 @@ class PrometheusPushGatewayManagerTests {
PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry,
otherScheduler, this.pushRate, "job", this.groupingKey, null); otherScheduler, this.pushRate, "job", this.groupingKey, null);
manager.shutdown(); manager.shutdown();
verify(otherScheduler, never()).shutdown(); then(otherScheduler).should(never()).shutdown();
} }
@Test @Test
@ -141,8 +141,8 @@ class PrometheusPushGatewayManagerTests {
PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry,
this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.PUSH); this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.PUSH);
manager.shutdown(); manager.shutdown();
verify(this.future).cancel(false); then(this.future).should().cancel(false);
verify(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); then(this.pushGateway).should().pushAdd(this.registry, "job", this.groupingKey);
} }
@Test @Test
@ -151,8 +151,8 @@ class PrometheusPushGatewayManagerTests {
PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry,
this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.DELETE); this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.DELETE);
manager.shutdown(); manager.shutdown();
verify(this.future).cancel(false); then(this.future).should().cancel(false);
verify(this.pushGateway).delete("job", this.groupingKey); then(this.pushGateway).should().delete("job", this.groupingKey);
} }
@Test @Test
@ -161,15 +161,15 @@ class PrometheusPushGatewayManagerTests {
PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry, PrometheusPushGatewayManager manager = new PrometheusPushGatewayManager(this.pushGateway, this.registry,
this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.NONE); this.scheduler, this.pushRate, "job", this.groupingKey, ShutdownOperation.NONE);
manager.shutdown(); manager.shutdown();
verify(this.future).cancel(false); then(this.future).should().cancel(false);
verifyNoInteractions(this.pushGateway); then(this.pushGateway).shouldHaveNoInteractions();
} }
@Test @Test
void pushDoesNotThrowException() throws Exception { void pushDoesNotThrowException() throws Exception {
new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job", new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, this.pushRate, "job",
this.groupingKey, null); this.groupingKey, null);
verify(this.scheduler).scheduleAtFixedRate(this.task.capture(), eq(this.pushRate)); then(this.scheduler).should().scheduleAtFixedRate(this.task.capture(), eq(this.pushRate));
willThrow(RuntimeException.class).given(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey); willThrow(RuntimeException.class).given(this.pushGateway).pushAdd(this.registry, "job", this.groupingKey);
this.task.getValue().run(); this.task.getValue().run();
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,13 +26,14 @@ import org.springframework.data.mongodb.core.MongoTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link MongoHealthIndicator}. * Tests for {@link MongoHealthIndicator}.
* *
* @author Christian Dupuis * @author Christian Dupuis
* @author Yanming Zhou
*/ */
class MongoHealthIndicatorTests { class MongoHealthIndicatorTests {
@ -46,8 +47,8 @@ class MongoHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails().get("version")).isEqualTo("2.6.4"); assertThat(health.getDetails().get("version")).isEqualTo("2.6.4");
verify(commandResult).getString("version"); then(commandResult).should().getString("version");
verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); then(mongoTemplate).should().executeCommand("{ buildInfo: 1 }");
} }
@Test @Test
@ -58,7 +59,7 @@ class MongoHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat((String) health.getDetails().get("error")).contains("Connection failed"); assertThat((String) health.getDetails().get("error")).contains("Connection failed");
verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); then(mongoTemplate).should().executeCommand("{ buildInfo: 1 }");
} }
} }

@ -36,9 +36,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link Neo4jHealthIndicator}. * Tests for {@link Neo4jHealthIndicator}.
@ -46,6 +46,7 @@ import static org.mockito.Mockito.verify;
* @author Eric Spiegelberg * @author Eric Spiegelberg
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Michael Simons * @author Michael Simons
* @author Yanming Zhou
*/ */
class Neo4jHealthIndicatorTests { class Neo4jHealthIndicatorTests {
@ -100,7 +101,7 @@ class Neo4jHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).containsEntry("server", "4711@My Home"); assertThat(health.getDetails()).containsEntry("server", "4711@My Home");
verify(session, times(2)).close(); then(session).should(times(2)).close();
} }
@Test @Test

@ -37,15 +37,16 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link Neo4jReactiveHealthIndicator}. * Tests for {@link Neo4jReactiveHealthIndicator}.
* *
* @author Michael J. Simons * @author Michael J. Simons
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class Neo4jReactiveHealthIndicatorTests { class Neo4jReactiveHealthIndicatorTests {
@ -81,7 +82,7 @@ class Neo4jReactiveHealthIndicatorTests {
assertThat(health.getDetails()).containsEntry("server", "4711@My Home"); assertThat(health.getDetails()).containsEntry("server", "4711@My Home");
assertThat(health.getDetails()).containsEntry("edition", "some edition"); assertThat(health.getDetails()).containsEntry("edition", "some edition");
}).verifyComplete(); }).verifyComplete();
verify(session, times(2)).close(); then(session).should(times(2)).close();
} }
@Test @Test

@ -75,15 +75,15 @@ import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Tests for {@link QuartzEndpoint}. * Tests for {@link QuartzEndpoint}.
* *
* @author Vedran Pavic * @author Vedran Pavic
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class QuartzEndpointTests { class QuartzEndpointTests {
@ -118,9 +118,9 @@ class QuartzEndpointTests {
QuartzReport quartzReport = this.endpoint.quartzReport(); QuartzReport quartzReport = this.endpoint.quartzReport();
assertThat(quartzReport.getJobs().getGroups()).containsOnly("jobSamples", "DEFAULT"); assertThat(quartzReport.getJobs().getGroups()).containsOnly("jobSamples", "DEFAULT");
assertThat(quartzReport.getTriggers().getGroups()).containsOnly("triggerSamples"); assertThat(quartzReport.getTriggers().getGroups()).containsOnly("triggerSamples");
verify(this.scheduler).getJobGroupNames(); then(this.scheduler).should().getJobGroupNames();
verify(this.scheduler).getTriggerGroupNames(); then(this.scheduler).should().getTriggerGroupNames();
verifyNoMoreInteractions(this.scheduler); then(this.scheduler).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -669,9 +669,9 @@ class QuartzEndpointTests {
given(sanitizer.sanitize("secret", "value")).willReturn("----"); given(sanitizer.sanitize("secret", "value")).willReturn("----");
QuartzJobDetails jobDetails = new QuartzEndpoint(this.scheduler, sanitizer).quartzJob("samples", "hello"); QuartzJobDetails jobDetails = new QuartzEndpoint(this.scheduler, sanitizer).quartzJob("samples", "hello");
assertThat(jobDetails.getData()).containsOnly(entry("test", "value"), entry("secret", "----")); assertThat(jobDetails.getData()).containsOnly(entry("test", "value"), entry("secret", "----"));
verify(sanitizer).sanitize("test", "value"); then(sanitizer).should().sanitize("test", "value");
verify(sanitizer).sanitize("secret", "value"); then(sanitizer).should().sanitize("secret", "value");
verifyNoMoreInteractions(sanitizer); then(sanitizer).shouldHaveNoMoreInteractions();
} }
private void mockJobs(JobDetail... jobs) throws SchedulerException { private void mockJobs(JobDetail... jobs) throws SchedulerException {

@ -33,9 +33,9 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link RedisHealthIndicator}. * Tests for {@link RedisHealthIndicator}.
@ -43,6 +43,7 @@ import static org.mockito.Mockito.verify;
* @author Christian Dupuis * @author Christian Dupuis
* @author Richard Santana * @author Richard Santana
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class RedisHealthIndicatorTests { class RedisHealthIndicatorTests {
@ -77,7 +78,7 @@ class RedisHealthIndicatorTests {
assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L); assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L);
assertThat(health.getDetails().get("slots_up")).isEqualTo(4L); assertThat(health.getDetails().get("slots_up")).isEqualTo(4L);
assertThat(health.getDetails().get("slots_fail")).isEqualTo(0L); assertThat(health.getDetails().get("slots_fail")).isEqualTo(0L);
verify(redisConnectionFactory, atLeastOnce()).getConnection(); then(redisConnectionFactory).should(atLeastOnce()).getConnection();
} }
@Test @Test
@ -89,7 +90,7 @@ class RedisHealthIndicatorTests {
assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L); assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L);
assertThat(health.getDetails().get("slots_up")).isEqualTo(4L); assertThat(health.getDetails().get("slots_up")).isEqualTo(4L);
assertThat(health.getDetails().get("slots_fail")).isEqualTo(0L); assertThat(health.getDetails().get("slots_fail")).isEqualTo(0L);
verify(redisConnectionFactory, atLeastOnce()).getConnection(); then(redisConnectionFactory).should(atLeastOnce()).getConnection();
} }
@Test @Test
@ -101,7 +102,7 @@ class RedisHealthIndicatorTests {
assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L); assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L);
assertThat(health.getDetails().get("slots_up")).isEqualTo(3L); assertThat(health.getDetails().get("slots_up")).isEqualTo(3L);
assertThat(health.getDetails().get("slots_fail")).isEqualTo(1L); assertThat(health.getDetails().get("slots_fail")).isEqualTo(1L);
verify(redisConnectionFactory, atLeastOnce()).getConnection(); then(redisConnectionFactory).should(atLeastOnce()).getConnection();
} }
private RedisHealthIndicator createHealthIndicator(RedisConnection redisConnection) { private RedisHealthIndicator createHealthIndicator(RedisConnection redisConnection) {

@ -34,8 +34,8 @@ import org.springframework.data.redis.connection.ReactiveServerCommands;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link RedisReactiveHealthIndicator}. * Tests for {@link RedisReactiveHealthIndicator}.
@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify;
* @author Nikolay Rybak * @author Nikolay Rybak
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Scott Frederick * @author Scott Frederick
* @author Yanming Zhou
*/ */
class RedisReactiveHealthIndicatorTests { class RedisReactiveHealthIndicatorTests {
@ -63,7 +64,7 @@ class RedisReactiveHealthIndicatorTests {
assertThat(h.getDetails()).containsOnlyKeys("version"); assertThat(h.getDetails()).containsOnlyKeys("version");
assertThat(h.getDetails().get("version")).isEqualTo("2.8.9"); assertThat(h.getDetails().get("version")).isEqualTo("2.8.9");
}).verifyComplete(); }).verifyComplete();
verify(redisConnection).closeLater(); then(redisConnection).should().closeLater();
} }
@Test @Test
@ -77,7 +78,7 @@ class RedisReactiveHealthIndicatorTests {
assertThat(h.getDetails().get("slots_up")).isEqualTo(4L); assertThat(h.getDetails().get("slots_up")).isEqualTo(4L);
assertThat(h.getDetails().get("slots_fail")).isEqualTo(0L); assertThat(h.getDetails().get("slots_fail")).isEqualTo(0L);
}).verifyComplete(); }).verifyComplete();
verify(redisConnectionFactory.getReactiveConnection()).closeLater(); then(redisConnectionFactory.getReactiveConnection()).should().closeLater();
} }
@Test @Test
@ -115,7 +116,7 @@ class RedisReactiveHealthIndicatorTests {
Mono<Health> health = healthIndicator.health(); Mono<Health> health = healthIndicator.health();
StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN))
.verifyComplete(); .verifyComplete();
verify(redisConnection).closeLater(); then(redisConnection).should().closeLater();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,9 +35,9 @@ import org.springframework.security.web.authentication.switchuser.Authentication
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link AuthenticationAuditListener}. * Tests for {@link AuthenticationAuditListener}.
@ -65,7 +65,7 @@ class AuthenticationAuditListenerTests {
this.listener.onApplicationEvent(new InteractiveAuthenticationSuccessEvent( this.listener.onApplicationEvent(new InteractiveAuthenticationSuccessEvent(
new UsernamePasswordAuthenticationToken("user", "password"), getClass())); new UsernamePasswordAuthenticationToken("user", "password"), getClass()));
// No need to audit this one (it shadows a regular AuthenticationSuccessEvent) // No need to audit this one (it shadows a regular AuthenticationSuccessEvent)
verify(this.publisher, never()).publishEvent(any(ApplicationEvent.class)); then(this.publisher).should(never()).publishEvent(any(ApplicationEvent.class));
} }
@Test @Test
@ -105,7 +105,7 @@ class AuthenticationAuditListenerTests {
private AuditApplicationEvent handleAuthenticationEvent(AbstractAuthenticationEvent event) { private AuditApplicationEvent handleAuthenticationEvent(AbstractAuthenticationEvent event) {
ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class);
this.listener.onApplicationEvent(event); this.listener.onApplicationEvent(event);
verify(this.publisher).publishEvent(eventCaptor.capture()); then(this.publisher).should().publishEvent(eventCaptor.capture());
return eventCaptor.getValue(); return eventCaptor.getValue();
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,8 +33,8 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link AuthorizationAuditListener}. * Tests for {@link AuthorizationAuditListener}.
@ -82,7 +82,7 @@ class AuthorizationAuditListenerTests {
private AuditApplicationEvent handleAuthorizationEvent(AbstractAuthorizationEvent event) { private AuditApplicationEvent handleAuthorizationEvent(AbstractAuthorizationEvent event) {
ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class); ArgumentCaptor<AuditApplicationEvent> eventCaptor = ArgumentCaptor.forClass(AuditApplicationEvent.class);
this.listener.onApplicationEvent(event); this.listener.onApplicationEvent(event);
verify(this.publisher).publishEvent(eventCaptor.capture()); then(this.publisher).should().publishEvent(eventCaptor.capture());
return eventCaptor.getValue(); return eventCaptor.getValue();
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -28,13 +28,14 @@ import org.springframework.session.Session;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link SessionsEndpoint}. * Tests for {@link SessionsEndpoint}.
* *
* @author Vedran Pavic * @author Vedran Pavic
* @author Yanming Zhou
*/ */
class SessionsEndpointTests { class SessionsEndpointTests {
@ -80,7 +81,7 @@ class SessionsEndpointTests {
@Test @Test
void deleteSession() { void deleteSession() {
this.endpoint.deleteSession(session.getId()); this.endpoint.deleteSession(session.getId());
verify(this.repository).deleteById(session.getId()); then(this.repository).should().deleteById(session.getId());
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,10 +32,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Tests for {@link SolrHealthIndicator} * Tests for {@link SolrHealthIndicator}
@ -43,6 +42,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Markus Schuch * @author Markus Schuch
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class SolrHealthIndicatorTests { class SolrHealthIndicatorTests {
@ -52,8 +52,8 @@ class SolrHealthIndicatorTests {
given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(0)); given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(0));
SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient);
assertHealth(healthIndicator, Status.UP, 0, "root"); assertHealth(healthIndicator, Status.UP, 0, "root");
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -62,8 +62,8 @@ class SolrHealthIndicatorTests {
given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(400)); given(solrClient.request(any(CoreAdminRequest.class), isNull())).willReturn(mockResponse(400));
SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient);
assertHealth(healthIndicator, Status.DOWN, 400, "root"); assertHealth(healthIndicator, Status.DOWN, 400, "root");
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -74,9 +74,9 @@ class SolrHealthIndicatorTests {
given(solrClient.ping()).willReturn(mockPingResponse(0)); given(solrClient.ping()).willReturn(mockPingResponse(0));
SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient);
assertHealth(healthIndicator, Status.UP, 0, "particular core"); assertHealth(healthIndicator, Status.UP, 0, "particular core");
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verify(solrClient, times(1)).ping(); then(solrClient).should().ping();
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -87,9 +87,9 @@ class SolrHealthIndicatorTests {
given(solrClient.ping()).willReturn(mockPingResponse(400)); given(solrClient.ping()).willReturn(mockPingResponse(400));
SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient);
assertHealth(healthIndicator, Status.DOWN, 400, "particular core"); assertHealth(healthIndicator, Status.DOWN, 400, "particular core");
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verify(solrClient, times(1)).ping(); then(solrClient).should().ping();
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -101,8 +101,8 @@ class SolrHealthIndicatorTests {
Health health = healthIndicator.health(); Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat((String) health.getDetails().get("error")).contains("Connection failed"); assertThat((String) health.getDetails().get("error")).contains("Connection failed");
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -113,12 +113,12 @@ class SolrHealthIndicatorTests {
given(solrClient.ping()).willReturn(mockPingResponse(0)); given(solrClient.ping()).willReturn(mockPingResponse(0));
SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient); SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrClient);
healthIndicator.health(); healthIndicator.health();
verify(solrClient, times(1)).request(any(CoreAdminRequest.class), isNull()); then(solrClient).should().request(any(CoreAdminRequest.class), isNull());
verify(solrClient, times(1)).ping(); then(solrClient).should().ping();
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
healthIndicator.health(); healthIndicator.health();
verify(solrClient, times(2)).ping(); then(solrClient).should(times(2)).ping();
verifyNoMoreInteractions(solrClient); then(solrClient).shouldHaveNoMoreInteractions();
} }
private void assertHealth(SolrHealthIndicator healthIndicator, Status expectedStatus, int expectedStatusCode, private void assertHealth(SolrHealthIndicator healthIndicator, Status expectedStatus, int expectedStatusCode,

@ -39,14 +39,15 @@ import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link SharedMetadataReaderFactoryContextInitializer}. * Tests for {@link SharedMetadataReaderFactoryContextInitializer}.
* *
* @author Dave Syer * @author Dave Syer
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class SharedMetadataReaderFactoryContextInitializerTests { class SharedMetadataReaderFactoryContextInitializerTests {
@ -84,7 +85,7 @@ class SharedMetadataReaderFactoryContextInitializerTests {
assertThat(bean).isSameAs(configurationAnnotationPostProcessor); assertThat(bean).isSameAs(configurationAnnotationPostProcessor);
ArgumentCaptor<MetadataReaderFactory> metadataReaderFactory = ArgumentCaptor ArgumentCaptor<MetadataReaderFactory> metadataReaderFactory = ArgumentCaptor
.forClass(MetadataReaderFactory.class); .forClass(MetadataReaderFactory.class);
verify(configurationAnnotationPostProcessor).setMetadataReaderFactory(metadataReaderFactory.capture()); then(configurationAnnotationPostProcessor).should().setMetadataReaderFactory(metadataReaderFactory.capture());
assertThat(metadataReaderFactory.getValue()) assertThat(metadataReaderFactory.getValue())
.isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class); .isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class);
} }

@ -78,9 +78,9 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link RabbitAutoConfiguration}. * Tests for {@link RabbitAutoConfiguration}.
@ -90,6 +90,7 @@ import static org.mockito.Mockito.verify;
* @author Gary Russell * @author Gary Russell
* @author HaiTao Zhang * @author HaiTao Zhang
* @author Franjo Zilic * @author Franjo Zilic
* @author Yanming Zhou
*/ */
@ExtendWith(OutputCaptureExtension.class) @ExtendWith(OutputCaptureExtension.class)
class RabbitAutoConfigurationTests { class RabbitAutoConfigurationTests {
@ -173,10 +174,10 @@ class RabbitAutoConfigurationTests {
given(rcf.newConnection(isNull(), eq(addresses), anyString())).willReturn(mock(Connection.class)); given(rcf.newConnection(isNull(), eq(addresses), anyString())).willReturn(mock(Connection.class));
ReflectionTestUtils.setField(connectionFactory, "rabbitConnectionFactory", rcf); ReflectionTestUtils.setField(connectionFactory, "rabbitConnectionFactory", rcf);
connectionFactory.createConnection(); connectionFactory.createConnection();
verify(rcf).newConnection(isNull(), eq(addresses), eq("test#0")); then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#0"));
connectionFactory.resetConnection(); connectionFactory.resetConnection();
connectionFactory.createConnection(); connectionFactory.createConnection();
verify(rcf).newConnection(isNull(), eq(addresses), eq("test#1")); then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#1"));
}); });
} }
@ -354,10 +355,11 @@ class RabbitAutoConfigurationTests {
RabbitTemplate template = mock(RabbitTemplate.class); RabbitTemplate template = mock(RabbitTemplate.class);
ConnectionFactory connectionFactory = mock(ConnectionFactory.class); ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
configurer.configure(template, connectionFactory); configurer.configure(template, connectionFactory);
verify(template).setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class)); then(template).should()
verify(template).setExchange("my-exchange"); .setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class));
verify(template).setRoutingKey("my-routing-key"); then(template).should().setExchange("my-exchange");
verify(template).setDefaultReceiveQueue("default-queue"); then(template).should().setRoutingKey("my-routing-key");
then(template).should().setDefaultReceiveQueue("default-queue");
}); });
} }
@ -428,7 +430,7 @@ class RabbitAutoConfigurationTests {
SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context
.getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class);
rabbitListenerContainerFactory.setBatchSize(10); rabbitListenerContainerFactory.setBatchSize(10);
verify(rabbitListenerContainerFactory).setBatchSize(10); then(rabbitListenerContainerFactory).should().setBatchSize(10);
assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull(); assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull();
}); });
} }
@ -548,9 +550,9 @@ class RabbitAutoConfigurationTests {
.getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class);
SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class);
configurer.configure(factory, mock(ConnectionFactory.class)); configurer.configure(factory, mock(ConnectionFactory.class));
verify(factory).setConcurrentConsumers(5); then(factory).should().setConcurrentConsumers(5);
verify(factory).setMaxConcurrentConsumers(10); then(factory).should().setMaxConcurrentConsumers(10);
verify(factory).setPrefetchCount(40); then(factory).should().setPrefetchCount(40);
}); });
} }
@ -562,7 +564,7 @@ class RabbitAutoConfigurationTests {
.getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class);
SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class);
configurer.configure(factory, mock(ConnectionFactory.class)); configurer.configure(factory, mock(ConnectionFactory.class));
verify(factory).setConsumerBatchEnabled(true); then(factory).should().setConsumerBatchEnabled(true);
}); });
} }
@ -577,9 +579,9 @@ class RabbitAutoConfigurationTests {
.getBean(DirectRabbitListenerContainerFactoryConfigurer.class); .getBean(DirectRabbitListenerContainerFactoryConfigurer.class);
DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class);
configurer.configure(factory, mock(ConnectionFactory.class)); configurer.configure(factory, mock(ConnectionFactory.class));
verify(factory).setConsumersPerQueue(5); then(factory).should().setConsumersPerQueue(5);
verify(factory).setPrefetchCount(40); then(factory).should().setPrefetchCount(40);
verify(factory).setDeBatchingEnabled(false); then(factory).should().setDeBatchingEnabled(false);
}); });
} }
@ -602,7 +604,7 @@ class RabbitAutoConfigurationTests {
Message message = mock(Message.class); Message message = mock(Message.class);
Exception ex = new Exception("test"); Exception ex = new Exception("test");
mir.recover(new Object[] { "foo", message }, ex); mir.recover(new Object[] { "foo", message }, ex);
verify(messageRecoverer).recover(message, ex); then(messageRecoverer).should().recover(message, ex);
RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, "retryOperations"); RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice, "retryOperations");
assertThat(retryTemplate).isNotNull(); assertThat(retryTemplate).isNotNull();
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, "retryPolicy"); SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, "retryPolicy");
@ -843,8 +845,8 @@ class RabbitAutoConfigurationTests {
ConnectionFactoryCustomizer.class); ConnectionFactoryCustomizer.class);
InOrder inOrder = inOrder(firstCustomizer, secondCustomizer); InOrder inOrder = inOrder(firstCustomizer, secondCustomizer);
com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context); com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context);
inOrder.verify(firstCustomizer).customize(targetConnectionFactory); then(firstCustomizer).should(inOrder).customize(targetConnectionFactory);
inOrder.verify(secondCustomizer).customize(targetConnectionFactory); then(secondCustomizer).should(inOrder).customize(targetConnectionFactory);
inOrder.verifyNoMoreInteractions(); inOrder.verifyNoMoreInteractions();
}); });
} }

@ -23,13 +23,14 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link BatchDataSourceInitializer}. * Tests for {@link BatchDataSourceInitializer}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class BatchDataSourceInitializerTests { class BatchDataSourceInitializerTests {
@ -41,7 +42,7 @@ class BatchDataSourceInitializerTests {
BatchDataSourceInitializer initializer = new BatchDataSourceInitializer(dataSource, new DefaultResourceLoader(), BatchDataSourceInitializer initializer = new BatchDataSourceInitializer(dataSource, new DefaultResourceLoader(),
properties); properties);
assertThat(initializer.getDatabaseName()).isEqualTo("test"); assertThat(initializer.getDatabaseName()).isEqualTo("test");
verifyNoInteractions(dataSource); then(dataSource).shouldHaveNoInteractions();
} }
} }

@ -31,13 +31,14 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** /**
* Integration tests for {@link CassandraAutoConfiguration}. * Integration tests for {@link CassandraAutoConfiguration}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@Testcontainers(disabledWithoutDocker = true) @Testcontainers(disabledWithoutDocker = true)
class CassandraAutoConfigurationIntegrationTests { class CassandraAutoConfigurationIntegrationTests {
@ -61,7 +62,7 @@ class CassandraAutoConfigurationIntegrationTests {
context.getBean(CqlSession.class); context.getBean(CqlSession.class);
DriverConfigLoader driverConfigLoader = context.getBean(DriverConfigLoader.class); DriverConfigLoader driverConfigLoader = context.getBean(DriverConfigLoader.class);
context.close(); context.close();
verify(driverConfigLoader).close(); then(driverConfigLoader).should().close();
}); });
} }

@ -41,14 +41,14 @@ import org.springframework.core.type.filter.AnnotationTypeFilter;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Tests for {@link EntityScanner}. * Tests for {@link EntityScanner}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class EntityScannerTests { class EntityScannerTests {
@ -112,10 +112,10 @@ class EntityScannerTests {
TestEntityScanner scanner = new TestEntityScanner(context, candidateComponentProvider); TestEntityScanner scanner = new TestEntityScanner(context, candidateComponentProvider);
scanner.scan(Entity.class); scanner.scan(Entity.class);
ArgumentCaptor<AnnotationTypeFilter> annotationTypeFilter = ArgumentCaptor.forClass(AnnotationTypeFilter.class); ArgumentCaptor<AnnotationTypeFilter> annotationTypeFilter = ArgumentCaptor.forClass(AnnotationTypeFilter.class);
verify(candidateComponentProvider).addIncludeFilter(annotationTypeFilter.capture()); then(candidateComponentProvider).should().addIncludeFilter(annotationTypeFilter.capture());
verify(candidateComponentProvider) then(candidateComponentProvider).should()
.findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan"); .findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan");
verifyNoMoreInteractions(candidateComponentProvider); then(candidateComponentProvider).shouldHaveNoMoreInteractions();
assertThat(annotationTypeFilter.getValue().getAnnotationType()).isEqualTo(Entity.class); assertThat(annotationTypeFilter.getValue().getAnnotationType()).isEqualTo(Entity.class);
} }

@ -40,8 +40,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link ElasticsearchRestClientAutoConfiguration}. * Tests for {@link ElasticsearchRestClientAutoConfiguration}.
@ -223,7 +223,7 @@ class ElasticsearchRestClientAutoConfigurationTests {
assertThat(context).hasSingleBean(Sniffer.class); assertThat(context).hasSingleBean(Sniffer.class);
Sniffer sniffer = context.getBean(Sniffer.class); Sniffer sniffer = context.getBean(Sniffer.class);
assertThat(sniffer).isSameAs(customSniffer); assertThat(sniffer).isSameAs(customSniffer);
verifyNoInteractions(customSniffer); then(customSniffer).shouldHaveNoInteractions();
}); });
} }

@ -23,8 +23,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link IntegrationDataSourceInitializer}. * Tests for {@link IntegrationDataSourceInitializer}.
@ -41,7 +41,7 @@ class IntegrationDataSourceInitializerTests {
IntegrationDataSourceInitializer initializer = new IntegrationDataSourceInitializer(dataSource, IntegrationDataSourceInitializer initializer = new IntegrationDataSourceInitializer(dataSource,
new DefaultResourceLoader(), properties); new DefaultResourceLoader(), properties);
assertThat(initializer.getDatabaseName()).isEqualTo("test"); assertThat(initializer.getDatabaseName()).isEqualTo("test");
verifyNoInteractions(dataSource); then(dataSource).shouldHaveNoInteractions();
} }
} }

@ -31,14 +31,15 @@ import org.springframework.jdbc.BadSqlGrammarException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JooqExceptionTranslator} * Tests for {@link JooqExceptionTranslator}
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class JooqExceptionTranslatorTests { class JooqExceptionTranslatorTests {
@ -54,7 +55,7 @@ class JooqExceptionTranslatorTests {
given(context.sqlException()).willReturn(sqlException); given(context.sqlException()).willReturn(sqlException);
this.exceptionTranslator.exception(context); this.exceptionTranslator.exception(context);
ArgumentCaptor<RuntimeException> captor = ArgumentCaptor.forClass(RuntimeException.class); ArgumentCaptor<RuntimeException> captor = ArgumentCaptor.forClass(RuntimeException.class);
verify(context).exception(captor.capture()); then(context).should().exception(captor.capture());
assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class); assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class);
} }
@ -66,7 +67,7 @@ class JooqExceptionTranslatorTests {
given(configuration.dialect()).willReturn(SQLDialect.POSTGRES); given(configuration.dialect()).willReturn(SQLDialect.POSTGRES);
given(context.sqlException()).willReturn(new SQLException(null, null, 123456789)); given(context.sqlException()).willReturn(new SQLException(null, null, 123456789));
this.exceptionTranslator.exception(context); this.exceptionTranslator.exception(context);
verify(context, times(0)).exception(any()); then(context).should(never()).exception(any());
} }
static Object[] exceptionTranslation() { static Object[] exceptionTranslation() {

@ -33,14 +33,15 @@ import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JooqProperties}. * Tests for {@link JooqProperties}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class JooqPropertiesTests { class JooqPropertiesTests {
@ -59,7 +60,7 @@ class JooqPropertiesTests {
DataSource dataSource = mockStandaloneDataSource(); DataSource dataSource = mockStandaloneDataSource();
SQLDialect sqlDialect = properties.determineSqlDialect(dataSource); SQLDialect sqlDialect = properties.determineSqlDialect(dataSource);
assertThat(sqlDialect).isEqualTo(SQLDialect.POSTGRES); assertThat(sqlDialect).isEqualTo(SQLDialect.POSTGRES);
verify(dataSource, never()).getConnection(); then(dataSource).should(never()).getConnection();
} }
@Test @Test

@ -75,9 +75,9 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link KafkaAutoConfiguration}. * Tests for {@link KafkaAutoConfiguration}.
@ -86,6 +86,7 @@ import static org.mockito.Mockito.verify;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Nakul Mishra * @author Nakul Mishra
* @author Yanming Zhou
*/ */
class KafkaAutoConfigurationTests { class KafkaAutoConfigurationTests {
@ -332,10 +333,10 @@ class KafkaAutoConfigurationTests {
.asProperties(); .asProperties();
assertThat((List<String>) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) assertThat((List<String>) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG))
.containsExactly("localhost:9092", "localhost:9093"); .containsExactly("localhost:9092", "localhost:9093");
verify(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class), never()) then(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class))
.setAutoStartup(false); .should(never()).setAutoStartup(false);
verify(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class), then(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class))
never()).setAutoStartup(false); .should(never()).setAutoStartup(false);
}); });
} }

@ -37,16 +37,16 @@ import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.JavaMailSenderImpl;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link MailSenderAutoConfiguration}. * Tests for {@link MailSenderAutoConfiguration}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Yanming Zhou
*/ */
class MailSenderAutoConfigurationTests { class MailSenderAutoConfigurationTests {
@ -223,7 +223,7 @@ class MailSenderAutoConfigurationTests {
.withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> { .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> {
assertThat(context).hasSingleBean(JavaMailSenderImpl.class); assertThat(context).hasSingleBean(JavaMailSenderImpl.class);
JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class);
verify(mailSender, times(1)).testConnection(); then(mailSender).should().testConnection();
}); });
} }
@ -234,7 +234,7 @@ class MailSenderAutoConfigurationTests {
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(JavaMailSenderImpl.class); assertThat(context).hasSingleBean(JavaMailSenderImpl.class);
JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class);
verify(mailSender, never()).testConnection(); then(mailSender).should(never()).testConnection();
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,8 +30,8 @@ import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link MongoClientFactorySupport}. * Tests for {@link MongoClientFactorySupport}.
@ -43,6 +43,7 @@ import static org.mockito.Mockito.verify;
* @author Mark Paluch * @author Mark Paluch
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Scott Frederick * @author Scott Frederick
* @author Yanming Zhou
*/ */
abstract class MongoClientFactorySupportTests<T> { abstract class MongoClientFactorySupportTests<T> {
@ -97,7 +98,7 @@ abstract class MongoClientFactorySupportTests<T> {
void customizerIsInvoked() { void customizerIsInvoked() {
MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class); MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.class);
createMongoClient(customizer); createMongoClient(customizer);
verify(customizer).customize(any(MongoClientSettings.Builder.class)); then(customizer).should().customize(any(MongoClientSettings.Builder.class));
} }
@Test @Test

@ -36,8 +36,8 @@ import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link HibernateProperties}. * Tests for {@link HibernateProperties}.
@ -45,6 +45,7 @@ import static org.mockito.Mockito.verify;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Chris Bono * @author Chris Bono
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class HibernatePropertiesTests { class HibernatePropertiesTests {
@ -141,14 +142,14 @@ class HibernatePropertiesTests {
assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO); assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO);
assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_DATABASE_ACTION, assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_DATABASE_ACTION,
"drop-and-create"); "drop-and-create");
verify(this.ddlAutoSupplier, never()).get(); then(this.ddlAutoSupplier).should(never()).get();
})); }));
} }
private ContextConsumer<AssertableApplicationContext> assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) { private ContextConsumer<AssertableApplicationContext> assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) {
return assertHibernateProperties((hibernateProperties) -> { return assertHibernateProperties((hibernateProperties) -> {
assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, expectedDdlAuto); assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, expectedDdlAuto);
verify(this.ddlAutoSupplier, never()).get(); then(this.ddlAutoSupplier).should(never()).get();
}); });
} }

@ -70,8 +70,8 @@ import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link QuartzAutoConfiguration}. * Tests for {@link QuartzAutoConfiguration}.
@ -172,7 +172,7 @@ class QuartzAutoConfigurationTests {
Scheduler scheduler = context.getBean(Scheduler.class); Scheduler scheduler = context.getBean(Scheduler.class);
assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50);
Executor executor = context.getBean(Executor.class); Executor executor = context.getBean(Executor.class);
verifyNoInteractions(executor); then(executor).shouldHaveNoInteractions();
}); });
} }

@ -23,13 +23,14 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link JdbcSessionDataSourceInitializer}. * Tests for {@link JdbcSessionDataSourceInitializer}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class JdbcSessionDataSourceInitializerTests { class JdbcSessionDataSourceInitializerTests {
@ -41,7 +42,7 @@ class JdbcSessionDataSourceInitializerTests {
JdbcSessionDataSourceInitializer initializer = new JdbcSessionDataSourceInitializer(dataSource, JdbcSessionDataSourceInitializer initializer = new JdbcSessionDataSourceInitializer(dataSource,
new DefaultResourceLoader(), properties); new DefaultResourceLoader(), properties);
assertThat(initializer.getDatabaseName()).isEqualTo("test"); assertThat(initializer.getDatabaseName()).isEqualTo("test");
verifyNoInteractions(dataSource); then(dataSource).shouldHaveNoInteractions();
} }
} }

@ -36,14 +36,14 @@ import org.springframework.session.jdbc.JdbcIndexedSessionRepository;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Hazelcast specific tests for {@link SessionAutoConfiguration}. * Hazelcast specific tests for {@link SessionAutoConfiguration}.
* *
* @author Vedran Pavic * @author Vedran Pavic
* @author Yanming Zhou
*/ */
class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests {
@ -80,7 +80,7 @@ class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigur
assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval",
(int) new ServerProperties().getServlet().getSession().getTimeout().getSeconds()); (int) new ServerProperties().getServlet().getSession().getTimeout().getSeconds());
HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class);
verify(hazelcastInstance, times(1)).getMap("spring:session:sessions"); then(hazelcastInstance).should().getMap("spring:session:sessions");
} }
@Test @Test
@ -89,7 +89,7 @@ class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigur
"spring.session.hazelcast.map-name=foo:bar:biz").run((context) -> { "spring.session.hazelcast.map-name=foo:bar:biz").run((context) -> {
validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class); validateSessionRepository(context, Hazelcast4IndexedSessionRepository.class);
HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class);
verify(hazelcastInstance, times(1)).getMap("foo:bar:biz"); then(hazelcastInstance).should().getMap("foo:bar:biz");
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -22,13 +22,14 @@ import java.util.function.Supplier;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link SessionProperties}. * Tests for {@link SessionProperties}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class SessionPropertiesTests { class SessionPropertiesTests {
@ -39,7 +40,7 @@ class SessionPropertiesTests {
properties.setTimeout(Duration.ofMinutes(1)); properties.setTimeout(Duration.ofMinutes(1));
Supplier<Duration> fallback = mock(Supplier.class); Supplier<Duration> fallback = mock(Supplier.class);
assertThat(properties.determineTimeout(fallback)).isEqualTo(Duration.ofMinutes(1)); assertThat(properties.determineTimeout(fallback)).isEqualTo(Duration.ofMinutes(1));
verifyNoInteractions(fallback); then(fallback).shouldHaveNoInteractions();
} }
@Test @Test

@ -43,14 +43,15 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link TaskExecutionAutoConfiguration}. * Tests for {@link TaskExecutionAutoConfiguration}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Camille Vienot * @author Camille Vienot
* @author Yanming Zhou
*/ */
@ExtendWith(OutputCaptureExtension.class) @ExtendWith(OutputCaptureExtension.class)
class TaskExecutionAutoConfigurationTests { class TaskExecutionAutoConfigurationTests {
@ -119,7 +120,7 @@ class TaskExecutionAutoConfigurationTests {
this.contextRunner.withUserConfiguration(TaskExecutorCustomizerConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(TaskExecutorCustomizerConfig.class).run((context) -> {
TaskExecutorCustomizer customizer = context.getBean(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer = context.getBean(TaskExecutorCustomizer.class);
ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build(); ThreadPoolTaskExecutor executor = context.getBean(TaskExecutorBuilder.class).build();
verify(customizer).customize(executor); then(customizer).should().customize(executor);
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,14 +32,15 @@ import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link TemplateAvailabilityProviders}. * Tests for {@link TemplateAvailabilityProviders}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class TemplateAvailabilityProvidersTests { class TemplateAvailabilityProvidersTests {
@ -76,7 +77,7 @@ class TemplateAvailabilityProvidersTests {
given(applicationContext.getClassLoader()).willReturn(this.classLoader); given(applicationContext.getClassLoader()).willReturn(this.classLoader);
TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext); TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(applicationContext);
assertThat(providers.getProviders()).isNotEmpty(); assertThat(providers.getProviders()).isNotEmpty();
verify(applicationContext).getClassLoader(); then(applicationContext).should().getClassLoader();
} }
@Test @Test
@ -145,7 +146,8 @@ class TemplateAvailabilityProvidersTests {
TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader,
this.resourceLoader); this.resourceLoader);
assertThat(found).isNull(); assertThat(found).isNull();
verify(this.provider).isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader,
this.resourceLoader);
} }
@Test @Test
@ -164,7 +166,7 @@ class TemplateAvailabilityProvidersTests {
.willReturn(true); .willReturn(true);
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader,
this.resourceLoader); this.resourceLoader);
} }
@ -172,7 +174,7 @@ class TemplateAvailabilityProvidersTests {
void getProviderShouldCacheNoMatchResult() { void getProviderShouldCacheNoMatchResult() {
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
verify(this.provider, times(1)).isTemplateAvailable(this.view, this.environment, this.classLoader, then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader,
this.resourceLoader); this.resourceLoader);
} }
@ -183,7 +185,7 @@ class TemplateAvailabilityProvidersTests {
this.environment.setProperty("spring.template.provider.cache", "false"); this.environment.setProperty("spring.template.provider.cache", "false");
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader);
verify(this.provider, times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader, then(this.provider).should(times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader,
this.resourceLoader); this.resourceLoader);
} }

@ -33,16 +33,16 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ValidatorAdapter}. * Tests for {@link ValidatorAdapter}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
class ValidatorAdapterTests { class ValidatorAdapterTests {
@ -63,11 +63,11 @@ class ValidatorAdapterTests {
void wrapperInvokesCallbackOnNonManagedBean() { void wrapperInvokesCallbackOnNonManagedBean() {
this.contextRunner.withUserConfiguration(NonManagedBeanConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(NonManagedBeanConfig.class).run((context) -> {
LocalValidatorFactoryBean validator = context.getBean(NonManagedBeanConfig.class).validator; LocalValidatorFactoryBean validator = context.getBean(NonManagedBeanConfig.class).validator;
verify(validator, times(1)).setApplicationContext(any(ApplicationContext.class)); then(validator).should().setApplicationContext(any(ApplicationContext.class));
verify(validator, times(1)).afterPropertiesSet(); then(validator).should().afterPropertiesSet();
verify(validator, never()).destroy(); then(validator).should(never()).destroy();
context.close(); context.close();
verify(validator, times(1)).destroy(); then(validator).should().destroy();
}); });
} }
@ -75,11 +75,11 @@ class ValidatorAdapterTests {
void wrapperDoesNotInvokeCallbackOnManagedBean() { void wrapperDoesNotInvokeCallbackOnManagedBean() {
this.contextRunner.withUserConfiguration(ManagedBeanConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(ManagedBeanConfig.class).run((context) -> {
LocalValidatorFactoryBean validator = context.getBean(ManagedBeanConfig.class).validator; LocalValidatorFactoryBean validator = context.getBean(ManagedBeanConfig.class).validator;
verify(validator, never()).setApplicationContext(any(ApplicationContext.class)); then(validator).should(never()).setApplicationContext(any(ApplicationContext.class));
verify(validator, never()).afterPropertiesSet(); then(validator).should(never()).afterPropertiesSet();
verify(validator, never()).destroy(); then(validator).should(never()).destroy();
context.close(); context.close();
verify(validator, never()).destroy(); then(validator).should(never()).destroy();
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,15 +44,15 @@ import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link RestTemplateAutoConfiguration} * Tests for {@link RestTemplateAutoConfiguration}
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
* @author Yaming Zhou
*/ */
class RestTemplateAutoConfigurationTests { class RestTemplateAutoConfigurationTests {
@ -115,7 +115,7 @@ class RestTemplateAutoConfigurationTests {
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
RestTemplate restTemplate = context.getBean(RestTemplate.class); RestTemplate restTemplate = context.getBean(RestTemplate.class);
RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class);
verify(customizer).customize(restTemplate); then(customizer).should().customize(restTemplate);
}); });
} }
@ -128,7 +128,7 @@ class RestTemplateAutoConfigurationTests {
assertThat(restTemplate.getMessageConverters()).hasSize(1); assertThat(restTemplate.getMessageConverters()).hasSize(1);
assertThat(restTemplate.getMessageConverters().get(0)) assertThat(restTemplate.getMessageConverters().get(0))
.isInstanceOf(CustomHttpMessageConverter.class); .isInstanceOf(CustomHttpMessageConverter.class);
verifyNoInteractions(context.getBean(RestTemplateCustomizer.class)); then(context.getBean(RestTemplateCustomizer.class)).shouldHaveNoInteractions();
}); });
} }
@ -143,7 +143,7 @@ class RestTemplateAutoConfigurationTests {
assertThat(restTemplate.getMessageConverters().get(0)) assertThat(restTemplate.getMessageConverters().get(0))
.isInstanceOf(CustomHttpMessageConverter.class); .isInstanceOf(CustomHttpMessageConverter.class);
RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class);
verify(customizer).customize(restTemplate); then(customizer).should().customize(restTemplate);
}); });
} }

@ -54,8 +54,8 @@ import org.springframework.test.context.support.TestPropertySourceUtils;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link JettyWebServerFactoryCustomizer}. * Tests for {@link JettyWebServerFactoryCustomizer}.
@ -63,6 +63,7 @@ import static org.mockito.Mockito.verify;
* @author Brian Clozel * @author Brian Clozel
* @author Phillip Webb * @author Phillip Webb
* @author HaiTao Zhang * @author HaiTao Zhang
* @author Yanming Zhou
*/ */
class JettyWebServerFactoryCustomizerTests { class JettyWebServerFactoryCustomizerTests {
@ -85,14 +86,14 @@ class JettyWebServerFactoryCustomizerTests {
this.environment.setProperty("DYNO", "-"); this.environment.setProperty("DYNO", "-");
ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
void defaultUseForwardHeaders() { void defaultUseForwardHeaders() {
ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
@Test @Test
@ -100,7 +101,7 @@ class JettyWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE);
ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
@ -109,7 +110,7 @@ class JettyWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE);
ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
@Test @Test
@ -256,7 +257,7 @@ class JettyWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ForwardHeadersStrategy.NATIVE); this.serverProperties.setForwardHeadersStrategy(ForwardHeadersStrategy.NATIVE);
ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class); ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test

@ -39,10 +39,10 @@ import org.springframework.util.unit.DataSize;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link NettyWebServerFactoryCustomizer}. * Tests for {@link NettyWebServerFactoryCustomizer}.
@ -75,14 +75,14 @@ class NettyWebServerFactoryCustomizerTests {
this.environment.setProperty("DYNO", "-"); this.environment.setProperty("DYNO", "-");
NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
void defaultUseForwardHeaders() { void defaultUseForwardHeaders() {
NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
@Test @Test
@ -90,7 +90,7 @@ class NettyWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE);
NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
@ -99,7 +99,7 @@ class NettyWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE);
NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
@Test @Test
@ -120,7 +120,7 @@ class NettyWebServerFactoryCustomizerTests {
nettyProperties.setMaxInitialLineLength(DataSize.ofKilobytes(32)); nettyProperties.setMaxInitialLineLength(DataSize.ofKilobytes(32));
NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory, times(1)).addServerCustomizers(this.customizerCaptor.capture()); then(factory).should().addServerCustomizers(this.customizerCaptor.capture());
NettyServerCustomizer serverCustomizer = this.customizerCaptor.getValue(); NettyServerCustomizer serverCustomizer = this.customizerCaptor.getValue();
HttpServer httpServer = serverCustomizer.apply(HttpServer.create()); HttpServer httpServer = serverCustomizer.apply(HttpServer.create());
HttpRequestDecoderSpec decoder = httpServer.configuration().decoder(); HttpRequestDecoderSpec decoder = httpServer.configuration().decoder();
@ -133,10 +133,10 @@ class NettyWebServerFactoryCustomizerTests {
private void verifyConnectionTimeout(NettyReactiveWebServerFactory factory, Integer expected) { private void verifyConnectionTimeout(NettyReactiveWebServerFactory factory, Integer expected) {
if (expected == null) { if (expected == null) {
verify(factory, never()).addServerCustomizers(any(NettyServerCustomizer.class)); then(factory).should(never()).addServerCustomizers(any(NettyServerCustomizer.class));
return; return;
} }
verify(factory, times(2)).addServerCustomizers(this.customizerCaptor.capture()); then(factory).should(times(2)).addServerCustomizers(this.customizerCaptor.capture());
NettyServerCustomizer serverCustomizer = this.customizerCaptor.getAllValues().get(0); NettyServerCustomizer serverCustomizer = this.customizerCaptor.getAllValues().get(0);
HttpServer httpServer = serverCustomizer.apply(HttpServer.create()); HttpServer httpServer = serverCustomizer.apply(HttpServer.create());
Map<ChannelOption<?>, ?> options = httpServer.configuration().options(); Map<ChannelOption<?>, ?> options = httpServer.configuration().options();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,9 +41,9 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link UndertowWebServerFactoryCustomizer}. * Tests for {@link UndertowWebServerFactoryCustomizer}.
@ -53,6 +53,7 @@ import static org.mockito.Mockito.verify;
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Rafiullah Hamedy * @author Rafiullah Hamedy
* @author HaiTao Zhang * @author HaiTao Zhang
* @author Yanming Zhou
*/ */
class UndertowWebServerFactoryCustomizerTests { class UndertowWebServerFactoryCustomizerTests {
@ -77,12 +78,12 @@ class UndertowWebServerFactoryCustomizerTests {
"server.undertow.accesslog.dir=test-logs", "server.undertow.accesslog.rotate=false"); "server.undertow.accesslog.dir=test-logs", "server.undertow.accesslog.rotate=false");
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setAccessLogEnabled(true); then(factory).should().setAccessLogEnabled(true);
verify(factory).setAccessLogPattern("foo"); then(factory).should().setAccessLogPattern("foo");
verify(factory).setAccessLogPrefix("test_log"); then(factory).should().setAccessLogPrefix("test_log");
verify(factory).setAccessLogSuffix("txt"); then(factory).should().setAccessLogSuffix("txt");
verify(factory).setAccessLogDirectory(new File("test-logs")); then(factory).should().setAccessLogDirectory(new File("test-logs"));
verify(factory).setAccessLogRotate(false); then(factory).should().setAccessLogRotate(false);
} }
@Test @Test
@ -138,7 +139,7 @@ class UndertowWebServerFactoryCustomizerTests {
bind("server.undertow.threads.io=4"); bind("server.undertow.threads.io=4");
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setIoThreads(4); then(factory).should().setIoThreads(4);
} }
@Test @Test
@ -146,7 +147,7 @@ class UndertowWebServerFactoryCustomizerTests {
bind("server.undertow.threads.worker=10"); bind("server.undertow.threads.worker=10");
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setWorkerThreads(10); then(factory).should().setWorkerThreads(10);
} }
@Test @Test
@ -202,14 +203,14 @@ class UndertowWebServerFactoryCustomizerTests {
this.environment.setProperty("DYNO", "-"); this.environment.setProperty("DYNO", "-");
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
void defaultUseForwardHeaders() { void defaultUseForwardHeaders() {
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
@Test @Test
@ -217,7 +218,7 @@ class UndertowWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NATIVE);
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); then(factory).should().setUseForwardHeaders(true);
} }
@Test @Test
@ -226,7 +227,7 @@ class UndertowWebServerFactoryCustomizerTests {
this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE); this.serverProperties.setForwardHeadersStrategy(ServerProperties.ForwardHeadersStrategy.NONE);
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class); ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(false); then(factory).should().setUseForwardHeaders(false);
} }
private <T> T boundServerOption(Option<T> option) { private <T> T boundServerOption(Option<T> option) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,9 +53,8 @@ import org.springframework.web.server.adapter.ForwardedHeaderTransformer;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ReactiveWebServerFactoryAutoConfiguration}. * Tests for {@link ReactiveWebServerFactoryAutoConfiguration}.
@ -63,6 +62,7 @@ import static org.mockito.Mockito.verify;
* @author Brian Clozel * @author Brian Clozel
* @author Raheela Aslam * @author Raheela Aslam
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
class ReactiveWebServerFactoryAutoConfigurationTests { class ReactiveWebServerFactoryAutoConfigurationTests {
@ -128,7 +128,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class); TomcatConnectorCustomizer.class);
assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer); assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Connector.class)); then(customizer).should().customize(any(Connector.class));
}); });
} }
@ -145,7 +145,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class); TomcatConnectorCustomizer.class);
assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer); assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Connector.class)); then(customizer).should().customize(any(Connector.class));
}); });
} }
@ -161,7 +161,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class);
assertThat(factory.getTomcatContextCustomizers()).contains(customizer); assertThat(factory.getTomcatContextCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Context.class)); then(customizer).should().customize(any(Context.class));
}); });
} }
@ -177,7 +177,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class);
assertThat(factory.getTomcatContextCustomizers()).contains(customizer); assertThat(factory.getTomcatContextCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Context.class)); then(customizer).should().customize(any(Context.class));
}); });
} }
@ -194,7 +194,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer", TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class); TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer); assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any()); then(customizer).should().customize(any());
}); });
} }
@ -211,7 +211,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer", TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class); TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer); assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any()); then(customizer).should().customize(any());
}); });
} }
@ -238,7 +238,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class);
JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class);
assertThat(factory.getServerCustomizers()).contains(customizer); assertThat(factory.getServerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Server.class)); then(customizer).should().customize(any(Server.class));
}); });
} }
@ -266,7 +266,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer",
UndertowBuilderCustomizer.class); UndertowBuilderCustomizer.class);
assertThat(factory.getBuilderCustomizers()).contains(customizer); assertThat(factory.getBuilderCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Builder.class)); then(customizer).should().customize(any(Builder.class));
}); });
} }
@ -293,7 +293,7 @@ class ReactiveWebServerFactoryAutoConfigurationTests {
NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class);
NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class); NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class);
assertThat(factory.getServerCustomizers()).contains(customizer); assertThat(factory.getServerCustomizers()).contains(customizer);
verify(customizer, times(1)).apply(any(HttpServer.class)); then(customizer).should().apply(any(HttpServer.class));
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -28,14 +28,15 @@ import org.springframework.boot.web.server.Shutdown;
import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.Ssl;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ReactiveWebServerFactoryCustomizer}. * Tests for {@link ReactiveWebServerFactoryCustomizer}.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Yunkun Huang * @author Yunkun Huang
* @author Yanming Zhou
*/ */
class ReactiveWebServerFactoryCustomizerTests { class ReactiveWebServerFactoryCustomizerTests {
@ -53,7 +54,7 @@ class ReactiveWebServerFactoryCustomizerTests {
ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class);
this.properties.setPort(9000); this.properties.setPort(9000);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setPort(9000); then(factory).should().setPort(9000);
} }
@Test @Test
@ -62,7 +63,7 @@ class ReactiveWebServerFactoryCustomizerTests {
InetAddress address = mock(InetAddress.class); InetAddress address = mock(InetAddress.class);
this.properties.setAddress(address); this.properties.setAddress(address);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setAddress(address); then(factory).should().setAddress(address);
} }
@Test @Test
@ -71,7 +72,7 @@ class ReactiveWebServerFactoryCustomizerTests {
Ssl ssl = mock(Ssl.class); Ssl ssl = mock(Ssl.class);
this.properties.setSsl(ssl); this.properties.setSsl(ssl);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setSsl(ssl); then(factory).should().setSsl(ssl);
} }
@Test @Test
@ -80,7 +81,7 @@ class ReactiveWebServerFactoryCustomizerTests {
ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class); ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class); ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class);
verify(factory).setShutdown(shutdownCaptor.capture()); then(factory).should().setShutdown(shutdownCaptor.capture());
assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL); assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL);
} }

@ -92,8 +92,8 @@ import org.springframework.web.util.pattern.PathPattern;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link WebFluxAutoConfiguration}. * Tests for {@link WebFluxAutoConfiguration}.
@ -101,6 +101,7 @@ import static org.mockito.Mockito.verify;
* @author Brian Clozel * @author Brian Clozel
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Yanming Zhou
*/ */
class WebFluxAutoConfigurationTests { class WebFluxAutoConfigurationTests {
@ -148,7 +149,7 @@ class WebFluxAutoConfigurationTests {
this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class).run((context) -> { this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class).run((context) -> {
CodecCustomizer codecCustomizer = context.getBean("firstCodecCustomizer", CodecCustomizer.class); CodecCustomizer codecCustomizer = context.getBean("firstCodecCustomizer", CodecCustomizer.class);
assertThat(codecCustomizer).isNotNull(); assertThat(codecCustomizer).isNotNull();
verify(codecCustomizer).customize(any(ServerCodecConfigurer.class)); then(codecCustomizer).should().customize(any(ServerCodecConfigurer.class));
}); });
} }

@ -34,14 +34,14 @@ import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ClientHttpConnectorAutoConfiguration} * Tests for {@link ClientHttpConnectorAutoConfiguration}
* *
* @author Brian Clozel * @author Brian Clozel
* @author Yanming Zhou
*/ */
class ClientHttpConnectorAutoConfigurationTests { class ClientHttpConnectorAutoConfigurationTests {
@ -94,7 +94,7 @@ class ClientHttpConnectorAutoConfigurationTests {
WebClientCustomizer clientCustomizer = context.getBean(WebClientCustomizer.class); WebClientCustomizer clientCustomizer = context.getBean(WebClientCustomizer.class);
WebClient.Builder builder = mock(WebClient.Builder.class); WebClient.Builder builder = mock(WebClient.Builder.class);
clientCustomizer.customize(builder); clientCustomizer.customize(builder);
verify(builder, times(1)).clientConnector(any(ReactorClientHttpConnector.class)); then(builder).should().clientConnector(any(ReactorClientHttpConnector.class));
}); });
} }
@ -106,7 +106,7 @@ class ClientHttpConnectorAutoConfigurationTests {
WebClientCustomizer clientCustomizer = context.getBean(WebClientCustomizer.class); WebClientCustomizer clientCustomizer = context.getBean(WebClientCustomizer.class);
WebClient.Builder builder = mock(WebClient.Builder.class); WebClient.Builder builder = mock(WebClient.Builder.class);
clientCustomizer.customize(builder); clientCustomizer.customize(builder);
verify(builder, times(1)).clientConnector(any(ClientHttpConnector.class)); then(builder).should().clientConnector(any(ClientHttpConnector.class));
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -40,14 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link WebClientAutoConfiguration} * Tests for {@link WebClientAutoConfiguration}
* *
* @author Brian Clozel * @author Brian Clozel
* @author Yanming Zhou
*/ */
class WebClientAutoConfigurationTests { class WebClientAutoConfigurationTests {
@ -71,7 +72,7 @@ class WebClientAutoConfigurationTests {
WebClientCodecCustomizer clientCustomizer = context.getBean(WebClientCodecCustomizer.class); WebClientCodecCustomizer clientCustomizer = context.getBean(WebClientCodecCustomizer.class);
builder.build(); builder.build();
assertThat(clientCustomizer).isNotNull(); assertThat(clientCustomizer).isNotNull();
verify(codecCustomizer).customize(any(CodecConfigurer.class)); then(codecCustomizer).should().customize(any(CodecConfigurer.class));
}); });
} }
@ -81,7 +82,7 @@ class WebClientAutoConfigurationTests {
WebClient.Builder builder = context.getBean(WebClient.Builder.class); WebClient.Builder builder = context.getBean(WebClient.Builder.class);
WebClientCustomizer customizer = context.getBean("webClientCustomizer", WebClientCustomizer.class); WebClientCustomizer customizer = context.getBean("webClientCustomizer", WebClientCustomizer.class);
builder.build(); builder.build();
verify(customizer).customize(any(WebClient.Builder.class)); then(customizer).should().customize(any(WebClient.Builder.class));
}); });
} }
@ -102,11 +103,12 @@ class WebClientAutoConfigurationTests {
assertThat(firstBuilder).isNotEqualTo(secondBuilder); assertThat(firstBuilder).isNotEqualTo(secondBuilder);
firstBuilder.build().get().uri("/foo").retrieve().toBodilessEntity().block(Duration.ofSeconds(30)); firstBuilder.build().get().uri("/foo").retrieve().toBodilessEntity().block(Duration.ofSeconds(30));
secondBuilder.build().get().uri("/foo").retrieve().toBodilessEntity().block(Duration.ofSeconds(30)); secondBuilder.build().get().uri("/foo").retrieve().toBodilessEntity().block(Duration.ofSeconds(30));
verify(firstConnector).connect(eq(HttpMethod.GET), eq(URI.create("https://first.example.org/foo")), any()); then(firstConnector).should().connect(eq(HttpMethod.GET), eq(URI.create("https://first.example.org/foo")),
verify(secondConnector).connect(eq(HttpMethod.GET), eq(URI.create("https://second.example.org/foo")), any());
then(secondConnector).should().connect(eq(HttpMethod.GET), eq(URI.create("https://second.example.org/foo")),
any()); any());
WebClientCustomizer customizer = context.getBean("webClientCustomizer", WebClientCustomizer.class); WebClientCustomizer customizer = context.getBean("webClientCustomizer", WebClientCustomizer.class);
verify(customizer, times(2)).customize(any(WebClient.Builder.class)); then(customizer).should(times(2)).customize(any(WebClient.Builder.class));
}); });
} }

@ -63,9 +63,8 @@ import org.springframework.web.servlet.FrameworkServlet;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ServletWebServerFactoryAutoConfiguration}. * Tests for {@link ServletWebServerFactoryAutoConfiguration}.
@ -75,6 +74,7 @@ import static org.mockito.Mockito.verify;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Raheela Aslam * @author Raheela Aslam
* @author Madhura Bhave * @author Madhura Bhave
* @author Yanming Zhou
*/ */
class ServletWebServerFactoryAutoConfigurationTests { class ServletWebServerFactoryAutoConfigurationTests {
@ -176,7 +176,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
JettyServletWebServerFactory factory = context.getBean(JettyServletWebServerFactory.class); JettyServletWebServerFactory factory = context.getBean(JettyServletWebServerFactory.class);
JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class);
assertThat(factory.getServerCustomizers()).contains(customizer); assertThat(factory.getServerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Server.class)); then(customizer).should().customize(any(Server.class));
}); });
} }
@ -207,7 +207,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
UndertowDeploymentInfoCustomizer customizer = context.getBean("deploymentInfoCustomizer", UndertowDeploymentInfoCustomizer customizer = context.getBean("deploymentInfoCustomizer",
UndertowDeploymentInfoCustomizer.class); UndertowDeploymentInfoCustomizer.class);
assertThat(factory.getDeploymentInfoCustomizers()).contains(customizer); assertThat(factory.getDeploymentInfoCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(DeploymentInfo.class)); then(customizer).should().customize(any(DeploymentInfo.class));
}); });
} }
@ -224,7 +224,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer",
UndertowBuilderCustomizer.class); UndertowBuilderCustomizer.class);
assertThat(factory.getBuilderCustomizers()).contains(customizer); assertThat(factory.getBuilderCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Builder.class)); then(customizer).should().customize(any(Builder.class));
}); });
} }
@ -265,7 +265,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class); TomcatConnectorCustomizer.class);
assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer); assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Connector.class)); then(customizer).should().customize(any(Connector.class));
}); });
} }
@ -281,7 +281,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class); TomcatConnectorCustomizer.class);
assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer); assertThat(factory.getTomcatConnectorCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Connector.class)); then(customizer).should().customize(any(Connector.class));
}); });
} }
@ -296,7 +296,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatServletWebServerFactory factory = context.getBean(TomcatServletWebServerFactory.class); TomcatServletWebServerFactory factory = context.getBean(TomcatServletWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class);
assertThat(factory.getTomcatContextCustomizers()).contains(customizer); assertThat(factory.getTomcatContextCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Context.class)); then(customizer).should().customize(any(Context.class));
}); });
} }
@ -311,7 +311,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatServletWebServerFactory factory = context.getBean(TomcatServletWebServerFactory.class); TomcatServletWebServerFactory factory = context.getBean(TomcatServletWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class);
assertThat(factory.getTomcatContextCustomizers()).contains(customizer); assertThat(factory.getTomcatContextCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any(Context.class)); then(customizer).should().customize(any(Context.class));
}); });
} }
@ -327,7 +327,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer", TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class); TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer); assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any()); then(customizer).should().customize(any());
}); });
} }
@ -343,7 +343,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer", TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class); TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer); assertThat(factory.getTomcatProtocolHandlerCustomizers()).contains(customizer);
verify(customizer, times(1)).customize(any()); then(customizer).should().customize(any());
}); });
} }
@ -377,7 +377,7 @@ class ServletWebServerFactoryAutoConfigurationTests {
MockServletWebServerFactory factory = context.getBean(MockServletWebServerFactory.class); MockServletWebServerFactory factory = context.getBean(MockServletWebServerFactory.class);
Servlet servlet = context.getBean(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME, Servlet servlet = context.getBean(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME,
Servlet.class); Servlet.class);
verify(factory.getServletContext()).addServlet("dispatcherServlet", servlet); then(factory.getServletContext()).should().addServlet("dispatcherServlet", servlet);
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

@ -38,14 +38,15 @@ import org.springframework.boot.web.servlet.server.Session.Cookie;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ServletWebServerFactoryCustomizer}. * Tests for {@link ServletWebServerFactoryCustomizer}.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Yunkun Huang * @author Yunkun Huang
* @author Yanming Zhou
*/ */
class ServletWebServerFactoryCustomizerTests { class ServletWebServerFactoryCustomizerTests {
@ -62,7 +63,7 @@ class ServletWebServerFactoryCustomizerTests {
void testDefaultDisplayName() { void testDefaultDisplayName() {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setDisplayName("application"); then(factory).should().setDisplayName("application");
} }
@Test @Test
@ -70,7 +71,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.properties.getServlet().setApplicationDisplayName("TestName"); this.properties.getServlet().setApplicationDisplayName("TestName");
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setDisplayName("TestName"); then(factory).should().setDisplayName("TestName");
} }
@Test @Test
@ -78,7 +79,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.properties.getServlet().setRegisterDefaultServlet(false); this.properties.getServlet().setRegisterDefaultServlet(false);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setRegisterDefaultServlet(false); then(factory).should().setRegisterDefaultServlet(false);
} }
@Test @Test
@ -87,14 +88,14 @@ class ServletWebServerFactoryCustomizerTests {
Ssl ssl = mock(Ssl.class); Ssl ssl = mock(Ssl.class);
this.properties.setSsl(ssl); this.properties.setSsl(ssl);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setSsl(ssl); then(factory).should().setSsl(ssl);
} }
@Test @Test
void testCustomizeJsp() { void testCustomizeJsp() {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setJsp(any(Jsp.class)); then(factory).should().setJsp(any(Jsp.class));
} }
@Test @Test
@ -113,7 +114,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class); ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class);
verify(factory).setSession(sessionCaptor.capture()); then(factory).should().setSession(sessionCaptor.capture());
assertThat(sessionCaptor.getValue().getTimeout()).hasSeconds(123); assertThat(sessionCaptor.getValue().getTimeout()).hasSeconds(123);
Cookie cookie = sessionCaptor.getValue().getCookie(); Cookie cookie = sessionCaptor.getValue().getCookie();
assertThat(cookie.getName()).isEqualTo("testname"); assertThat(cookie.getName()).isEqualTo("testname");
@ -130,7 +131,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.properties.setPort(8080); this.properties.setPort(8080);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setPort(8080); then(factory).should().setPort(8080);
} }
@Test @Test
@ -140,7 +141,7 @@ class ServletWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setDisplayName("MyBootApp"); then(factory).should().setDisplayName("MyBootApp");
} }
@Test @Test
@ -159,7 +160,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class); ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class);
verify(factory).setSession(sessionCaptor.capture()); then(factory).should().setSession(sessionCaptor.capture());
assertThat(sessionCaptor.getValue().getStoreDir()).isEqualTo(new File("mydirectory")); assertThat(sessionCaptor.getValue().getStoreDir()).isEqualTo(new File("mydirectory"));
} }
@ -171,7 +172,7 @@ class ServletWebServerFactoryCustomizerTests {
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory); this.customizer.customize(factory);
ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class); ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class);
verify(factory).setShutdown(shutdownCaptor.capture()); then(factory).should().setShutdown(shutdownCaptor.capture());
assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL); assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL);
} }

@ -32,13 +32,14 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link WebServer}s driving {@link ServletContextListener}s correctly * Tests for {@link WebServer}s driving {@link ServletContextListener}s correctly
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class ServletWebServerServletContextListenerTests { class ServletWebServerServletContextListenerTests {
@ -77,7 +78,7 @@ class ServletWebServerServletContextListenerTests {
ServletContextListenerBeanConfiguration.class, configuration); ServletContextListenerBeanConfiguration.class, configuration);
ServletContextListener servletContextListener = context.getBean("servletContextListener", ServletContextListener servletContextListener = context.getBean("servletContextListener",
ServletContextListener.class); ServletContextListener.class);
verify(servletContextListener).contextInitialized(any(ServletContextEvent.class)); then(servletContextListener).should().contextInitialized(any(ServletContextEvent.class));
context.close(); context.close();
} }
@ -86,7 +87,7 @@ class ServletWebServerServletContextListenerTests {
ServletListenerRegistrationBeanConfiguration.class, configuration); ServletListenerRegistrationBeanConfiguration.class, configuration);
ServletContextListener servletContextListener = (ServletContextListener) context ServletContextListener servletContextListener = (ServletContextListener) context
.getBean("registration", ServletListenerRegistrationBean.class).getListener(); .getBean("registration", ServletListenerRegistrationBean.class).getListener();
verify(servletContextListener).contextInitialized(any(ServletContextEvent.class)); then(servletContextListener).should().contextInitialized(any(ServletContextEvent.class));
context.close(); context.close();
} }

@ -47,15 +47,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/** /**
* Tests for {@link DefaultErrorViewResolver}. * Tests for {@link DefaultErrorViewResolver}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class DefaultErrorViewResolverTests { class DefaultErrorViewResolverTests {
@ -108,9 +108,9 @@ class DefaultErrorViewResolverTests {
ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model);
assertThat(resolved).isNotNull(); assertThat(resolved).isNotNull();
assertThat(resolved.getViewName()).isEqualTo("error/404"); assertThat(resolved.getViewName()).isEqualTo("error/404");
verify(this.templateAvailabilityProvider).isTemplateAvailable(eq("error/404"), any(Environment.class), then(this.templateAvailabilityProvider).should().isTemplateAvailable(eq("error/404"), any(Environment.class),
any(ClassLoader.class), any(ResourceLoader.class)); any(ClassLoader.class), any(ResourceLoader.class));
verifyNoMoreInteractions(this.templateAvailabilityProvider); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions();
} }
@Test @Test
@ -177,7 +177,7 @@ class DefaultErrorViewResolverTests {
given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class),
any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false);
ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model);
verifyNoMoreInteractions(this.templateAvailabilityProvider); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions();
MockHttpServletResponse response = render(resolved); MockHttpServletResponse response = render(resolved);
assertThat(response.getContentAsString().trim()).isEqualTo("exact/404"); assertThat(response.getContentAsString().trim()).isEqualTo("exact/404");
assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE); assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_HTML_VALUE);

@ -31,15 +31,16 @@ import org.springframework.boot.cli.command.core.HintCommand;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link CommandRunner}. * Tests for {@link CommandRunner}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Dave Syer * @author Dave Syer
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class CommandRunnerTests { class CommandRunnerTests {
@ -101,7 +102,7 @@ class CommandRunnerTests {
@Test @Test
void runCommand() throws Exception { void runCommand() throws Exception {
this.commandRunner.run("command", "--arg1", "arg2"); this.commandRunner.run("command", "--arg1", "arg2");
verify(this.regularCommand).run("--arg1", "arg2"); then(this.regularCommand).should().run("--arg1", "arg2");
} }
@Test @Test
@ -112,7 +113,7 @@ class CommandRunnerTests {
@Test @Test
void appArguments() throws Exception { void appArguments() throws Exception {
this.commandRunner.runAndHandleErrors("command", "--", "--debug", "bar"); this.commandRunner.runAndHandleErrors("command", "--", "--debug", "bar");
verify(this.regularCommand).run("--", "--debug", "bar"); then(this.regularCommand).should().run("--", "--debug", "bar");
// When handled by the command itself it shouldn't cause the system property to be // When handled by the command itself it shouldn't cause the system property to be
// set // set
assertThat(System.getProperty("debug")).isNull(); assertThat(System.getProperty("debug")).isNull();
@ -166,7 +167,7 @@ class CommandRunnerTests {
@Test @Test
void help() throws Exception { void help() throws Exception {
this.commandRunner.run("help", "command"); this.commandRunner.run("help", "command");
verify(this.regularCommand).getHelp(); then(this.regularCommand).should().getHelp();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -31,12 +31,13 @@ import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder; import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Tests for {@link EncodePasswordCommand}. * Tests for {@link EncodePasswordCommand}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class EncodePasswordCommandTests { class EncodePasswordCommandTests {
@ -60,7 +61,7 @@ class EncodePasswordCommandTests {
void encodeWithNoAlgorithmShouldUseBcrypt() throws Exception { void encodeWithNoAlgorithmShouldUseBcrypt() throws Exception {
EncodePasswordCommand command = new EncodePasswordCommand(); EncodePasswordCommand command = new EncodePasswordCommand();
ExitStatus status = command.run("boot"); ExitStatus status = command.run("boot");
verify(this.log).info(this.message.capture()); then(this.log).should().info(this.message.capture());
assertThat(this.message.getValue()).startsWith("{bcrypt}"); assertThat(this.message.getValue()).startsWith("{bcrypt}");
assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder().matches("boot", this.message.getValue())) assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder().matches("boot", this.message.getValue()))
.isTrue(); .isTrue();
@ -71,7 +72,7 @@ class EncodePasswordCommandTests {
void encodeWithBCryptShouldUseBCrypt() throws Exception { void encodeWithBCryptShouldUseBCrypt() throws Exception {
EncodePasswordCommand command = new EncodePasswordCommand(); EncodePasswordCommand command = new EncodePasswordCommand();
ExitStatus status = command.run("-a", "bcrypt", "boot"); ExitStatus status = command.run("-a", "bcrypt", "boot");
verify(this.log).info(this.message.capture()); then(this.log).should().info(this.message.capture());
assertThat(this.message.getValue()).doesNotStartWith("{"); assertThat(this.message.getValue()).doesNotStartWith("{");
assertThat(new BCryptPasswordEncoder().matches("boot", this.message.getValue())).isTrue(); assertThat(new BCryptPasswordEncoder().matches("boot", this.message.getValue())).isTrue();
assertThat(status).isEqualTo(ExitStatus.OK); assertThat(status).isEqualTo(ExitStatus.OK);
@ -81,7 +82,7 @@ class EncodePasswordCommandTests {
void encodeWithPbkdf2ShouldUsePbkdf2() throws Exception { void encodeWithPbkdf2ShouldUsePbkdf2() throws Exception {
EncodePasswordCommand command = new EncodePasswordCommand(); EncodePasswordCommand command = new EncodePasswordCommand();
ExitStatus status = command.run("-a", "pbkdf2", "boot"); ExitStatus status = command.run("-a", "pbkdf2", "boot");
verify(this.log).info(this.message.capture()); then(this.log).should().info(this.message.capture());
assertThat(this.message.getValue()).doesNotStartWith("{"); assertThat(this.message.getValue()).doesNotStartWith("{");
assertThat(new Pbkdf2PasswordEncoder().matches("boot", this.message.getValue())).isTrue(); assertThat(new Pbkdf2PasswordEncoder().matches("boot", this.message.getValue())).isTrue();
assertThat(status).isEqualTo(ExitStatus.OK); assertThat(status).isEqualTo(ExitStatus.OK);
@ -91,7 +92,7 @@ class EncodePasswordCommandTests {
void encodeWithUnknownAlgorithmShouldExitWithError() throws Exception { void encodeWithUnknownAlgorithmShouldExitWithError() throws Exception {
EncodePasswordCommand command = new EncodePasswordCommand(); EncodePasswordCommand command = new EncodePasswordCommand();
ExitStatus status = command.run("--algorithm", "bad", "boot"); ExitStatus status = command.run("--algorithm", "bad", "boot");
verify(this.log).error("Unknown algorithm, valid options are: default,bcrypt,pbkdf2"); then(this.log).should().error("Unknown algorithm, valid options are: default,bcrypt,pbkdf2");
assertThat(status).isEqualTo(ExitStatus.ERROR); assertThat(status).isEqualTo(ExitStatus.ERROR);
} }

@ -37,7 +37,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.cli.command.status.ExitStatus; import org.springframework.boot.cli.command.status.ExitStatus;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Tests for {@link InitCommand} * Tests for {@link InitCommand}
@ -340,7 +340,7 @@ class InitCommandTests extends AbstractHttpClientMockTests {
@Test @Test
void userAgent() throws Exception { void userAgent() throws Exception {
this.command.run("--list", "--target=https://fake-service"); this.command.run("--list", "--target=https://fake-service");
verify(this.http).execute(this.requestCaptor.capture()); then(this.http).should().execute(this.requestCaptor.capture());
Header agent = this.requestCaptor.getValue().getHeaders("User-Agent")[0]; Header agent = this.requestCaptor.getValue().getHeaders("User-Agent")[0];
assertThat(agent.getValue()).startsWith("SpringBootCli/"); assertThat(agent.getValue()).startsWith("SpringBootCli/");
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -22,15 +22,16 @@ import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link DependencyManagementArtifactCoordinatesResolver}. * Tests for {@link DependencyManagementArtifactCoordinatesResolver}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class DependencyManagementArtifactCoordinatesResolverTests { class DependencyManagementArtifactCoordinatesResolverTests {
@ -49,7 +50,7 @@ class DependencyManagementArtifactCoordinatesResolverTests {
@Test @Test
void getGroupIdForBootArtifact() { void getGroupIdForBootArtifact() {
assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot"); assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot");
verify(this.dependencyManagement, never()).find(anyString()); then(this.dependencyManagement).should(never()).find(anyString());
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,14 +35,14 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link GrapeRootRepositorySystemSessionAutoConfiguration} * Tests for {@link GrapeRootRepositorySystemSessionAutoConfiguration}
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class GrapeRootRepositorySystemSessionAutoConfigurationTests { class GrapeRootRepositorySystemSessionAutoConfigurationTests {
@ -55,7 +55,8 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests {
@Test @Test
void noLocalRepositoryWhenNoGrapeRoot() { void noLocalRepositoryWhenNoGrapeRoot() {
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem);
verify(this.repositorySystem, never()).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); then(this.repositorySystem).should(never()).newLocalRepositoryManager(eq(this.session),
any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNull(); assertThat(this.session.getLocalRepository()).isNull();
} }
@ -72,7 +73,7 @@ class GrapeRootRepositorySystemSessionAutoConfigurationTests {
System.clearProperty("grape.root"); System.clearProperty("grape.root");
} }
verify(this.repositorySystem, times(1)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); then(this.repositorySystem).should().newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNotNull(); assertThat(this.session.getLocalRepository()).isNotNull();
assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath()) assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath())

@ -36,16 +36,17 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn; import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** /**
* Base class for tests for {@link DevToolsDataSourceAutoConfiguration}. * Base class for tests for {@link DevToolsDataSourceAutoConfiguration}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
abstract class AbstractDevToolsDataSourceAutoConfigurationTests { abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
@ -54,7 +55,7 @@ abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
ConfigurableApplicationContext context = getContext(() -> createContext(SingleDataSourceConfiguration.class)); ConfigurableApplicationContext context = getContext(() -> createContext(SingleDataSourceConfiguration.class));
DataSource dataSource = context.getBean(DataSource.class); DataSource dataSource = context.getBean(DataSource.class);
Statement statement = configureDataSourceBehavior(dataSource); Statement statement = configureDataSourceBehavior(dataSource);
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
@Test @Test
@ -64,7 +65,7 @@ abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
Collection<DataSource> dataSources = context.getBeansOfType(DataSource.class).values(); Collection<DataSource> dataSources = context.getBeansOfType(DataSource.class).values();
for (DataSource dataSource : dataSources) { for (DataSource dataSource : dataSources) {
Statement statement = configureDataSourceBehavior(dataSource); Statement statement = configureDataSourceBehavior(dataSource);
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
} }
@ -82,7 +83,7 @@ abstract class AbstractDevToolsDataSourceAutoConfigurationTests {
protected final Statement configureDataSourceBehavior(DataSource dataSource) throws SQLException { protected final Statement configureDataSourceBehavior(DataSource dataSource) throws SQLException {
Connection connection = mock(Connection.class); Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class); Statement statement = mock(Statement.class);
doReturn(connection).when(dataSource).getConnection(); willReturn(connection).given(dataSource).getConnection();
given(connection.createStatement()).willReturn(statement); given(connection.createStatement()).willReturn(statement);
return statement; return statement;
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -27,13 +27,14 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.testsupport.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.classpath.ClassPathExclusions;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link DevToolsDataSourceAutoConfiguration} with an embedded data source. * Tests for {@link DevToolsDataSourceAutoConfiguration} with an embedded data source.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ClassPathExclusions("HikariCP-*.jar") @ClassPathExclusions("HikariCP-*.jar")
class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests {
@ -44,7 +45,7 @@ class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsD
DataSourceSpyConfiguration.class); DataSourceSpyConfiguration.class);
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
} }

@ -39,14 +39,14 @@ import org.springframework.jdbc.core.JdbcTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link DevToolsDataSourceAutoConfiguration} with a pooled data source. * Tests for {@link DevToolsDataSourceAutoConfiguration} with a pooled data source.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests {
@ -66,7 +66,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
() -> createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); () -> createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement).execute("SHUTDOWN"); then(statement).should().execute("SHUTDOWN");
} }
@Test @Test
@ -75,7 +75,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
@Test @Test
@ -84,7 +84,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
"jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); "jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
@Test @Test
@ -93,7 +93,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, times(1)).execute("SHUTDOWN"); then(statement).should().execute("SHUTDOWN");
} }
@Test @Test
@ -102,7 +102,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
"jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); "jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
@Test @Test
@ -111,7 +111,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
"jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); "jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, times(1)).execute("SHUTDOWN"); then(statement).should().execute("SHUTDOWN");
} }
@Test @Test
@ -120,7 +120,7 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat
"jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class)); "jdbc:derby://localhost", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class));
Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class));
context.close(); context.close();
verify(statement, never()).execute("SHUTDOWN"); then(statement).should(never()).execute("SHUTDOWN");
} }
@Test @Test

@ -59,10 +59,10 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset; import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link LocalDevToolsAutoConfiguration}. * Tests for {@link LocalDevToolsAutoConfiguration}.
@ -70,6 +70,7 @@ import static org.mockito.Mockito.verify;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Vladimir Tsanev * @author Vladimir Tsanev
* @author Yanming Zhou
*/ */
@ExtendWith(MockRestarter.class) @ExtendWith(MockRestarter.class)
class LocalDevToolsAutoConfigurationTests { class LocalDevToolsAutoConfigurationTests {
@ -134,7 +135,7 @@ class LocalDevToolsAutoConfigurationTests {
LiveReloadServer server = this.context.getBean(LiveReloadServer.class); LiveReloadServer server = this.context.getBean(LiveReloadServer.class);
reset(server); reset(server);
this.context.publishEvent(new ContextRefreshedEvent(this.context)); this.context.publishEvent(new ContextRefreshedEvent(this.context));
verify(server).triggerReload(); then(server).should().triggerReload();
} }
@Test @Test
@ -144,7 +145,7 @@ class LocalDevToolsAutoConfigurationTests {
reset(server); reset(server);
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false);
this.context.publishEvent(event); this.context.publishEvent(event);
verify(server).triggerReload(); then(server).should().triggerReload();
} }
@Test @Test
@ -154,7 +155,7 @@ class LocalDevToolsAutoConfigurationTests {
reset(server); reset(server);
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true);
this.context.publishEvent(event); this.context.publishEvent(event);
verify(server, never()).triggerReload(); then(server).should(never()).triggerReload();
} }
@Test @Test
@ -171,7 +172,7 @@ class LocalDevToolsAutoConfigurationTests {
this.context = getContext(() -> initializeAndRun(Config.class)); this.context = getContext(() -> initializeAndRun(Config.class));
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), true);
this.context.publishEvent(event); this.context.publishEvent(event);
verify(restarter).restart(any(FailureHandler.class)); then(restarter).should().restart(any(FailureHandler.class));
} }
@Test @Test
@ -179,7 +180,7 @@ class LocalDevToolsAutoConfigurationTests {
this.context = getContext(() -> initializeAndRun(Config.class)); this.context = getContext(() -> initializeAndRun(Config.class));
ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false); ClassPathChangedEvent event = new ClassPathChangedEvent(this.context, Collections.emptySet(), false);
this.context.publishEvent(event); this.context.publishEvent(event);
verify(restarter, never()).restart(); then(restarter).should(never()).restart();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,15 +20,16 @@ import org.junit.jupiter.api.Test;
import org.springframework.boot.devtools.livereload.LiveReloadServer; import org.springframework.boot.devtools.livereload.LiveReloadServer;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link OptionalLiveReloadServer}. * Tests for {@link OptionalLiveReloadServer}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class OptionalLiveReloadServerTests { class OptionalLiveReloadServerTests {
@ -46,7 +47,7 @@ class OptionalLiveReloadServerTests {
willThrow(new RuntimeException("Error")).given(delegate).start(); willThrow(new RuntimeException("Error")).given(delegate).start();
server.startServer(); server.startServer();
server.triggerReload(); server.triggerReload();
verify(delegate, never()).triggerReload(); then(delegate).should(never()).triggerReload();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -37,13 +37,14 @@ import org.springframework.context.ApplicationEventPublisher;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ClassPathFileChangeListener}. * Tests for {@link ClassPathFileChangeListener}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class ClassPathFileChangeListenerTests { class ClassPathFileChangeListenerTests {
@ -77,13 +78,13 @@ class ClassPathFileChangeListenerTests {
@Test @Test
void sendsEventWithoutRestart() { void sendsEventWithoutRestart() {
testSendsEvent(false); testSendsEvent(false);
verify(this.fileSystemWatcher, never()).stop(); then(this.fileSystemWatcher).should(never()).stop();
} }
@Test @Test
void sendsEventWithRestart() { void sendsEventWithRestart() {
testSendsEvent(true); testSendsEvent(true);
verify(this.fileSystemWatcher).stop(); then(this.fileSystemWatcher).should().stop();
} }
private void testSendsEvent(boolean restart) { private void testSendsEvent(boolean restart) {
@ -102,7 +103,7 @@ class ClassPathFileChangeListenerTests {
given(this.restartStrategy.isRestartRequired(file2)).willReturn(true); given(this.restartStrategy.isRestartRequired(file2)).willReturn(true);
} }
listener.onChange(changeSet); listener.onChange(changeSet);
verify(this.eventPublisher).publishEvent(this.eventCaptor.capture()); then(this.eventPublisher).should().publishEvent(this.eventCaptor.capture());
ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor.getValue(); ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor.getValue();
assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet); assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet);
assertThat(actualEvent.isRestartRequired()).isEqualTo(restart); assertThat(actualEvent.isRestartRequired()).isEqualTo(restart);

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,13 +23,14 @@ import java.io.OutputStream;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ConnectionOutputStream}. * Tests for {@link ConnectionOutputStream}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
class ConnectionOutputStreamTests { class ConnectionOutputStreamTests {
@ -40,7 +41,7 @@ class ConnectionOutputStreamTests {
ConnectionOutputStream outputStream = new ConnectionOutputStream(out); ConnectionOutputStream outputStream = new ConnectionOutputStream(out);
byte[] b = new byte[100]; byte[] b = new byte[100];
outputStream.write(b, 1, 2); outputStream.write(b, 1, 2);
verify(out).write(b, 1, 2); then(out).should().write(b, 1, 2);
} }
@Test @Test

@ -35,13 +35,14 @@ import org.springframework.http.client.ClientHttpResponse;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link DelayedLiveReloadTrigger}. * Tests for {@link DelayedLiveReloadTrigger}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class DelayedLiveReloadTriggerTests { class DelayedLiveReloadTriggerTests {
@ -113,7 +114,7 @@ class DelayedLiveReloadTriggerTests {
this.trigger.setTimings(10, 200, 30000); this.trigger.setTimings(10, 200, 30000);
this.trigger.run(); this.trigger.run();
assertThat(System.currentTimeMillis() - startTime).isGreaterThan(300L); assertThat(System.currentTimeMillis() - startTime).isGreaterThan(300L);
verify(this.liveReloadServer).triggerReload(); then(this.liveReloadServer).should().triggerReload();
} }
@Test @Test
@ -121,7 +122,7 @@ class DelayedLiveReloadTriggerTests {
given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()); given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException());
this.trigger.setTimings(10, 0, 10); this.trigger.setTimings(10, 0, 10);
this.trigger.run(); this.trigger.run();
verify(this.liveReloadServer, never()).triggerReload(); then(this.liveReloadServer).should(never()).triggerReload();
} }
} }

@ -52,13 +52,14 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link RemoteClientConfiguration}. * Tests for {@link RemoteClientConfiguration}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith({ OutputCaptureExtension.class, MockRestarter.class }) @ExtendWith({ OutputCaptureExtension.class, MockRestarter.class })
class RemoteClientConfigurationTests { class RemoteClientConfigurationTests {
@ -108,7 +109,7 @@ class RemoteClientConfigurationTests {
ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false); ClassPathChangedEvent event = new ClassPathChangedEvent(this, changeSet, false);
this.clientContext.publishEvent(event); this.clientContext.publishEvent(event);
LiveReloadServer server = this.clientContext.getBean(LiveReloadServer.class); LiveReloadServer server = this.clientContext.getBean(LiveReloadServer.class);
Awaitility.await().atMost(Duration.ofMinutes(1)).untilAsserted(() -> verify(server).triggerReload()); Awaitility.await().atMost(Duration.ofMinutes(1)).untilAsserted(() -> then(server).should().triggerReload());
} }
@Test @Test

@ -40,10 +40,9 @@ import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willReturn; import static org.mockito.BDDMockito.willReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link DispatcherFilter}. * Tests for {@link DispatcherFilter}.
@ -83,8 +82,8 @@ class DispatcherFilterTests {
ServletRequest request = mock(ServletRequest.class); ServletRequest request = mock(ServletRequest.class);
ServletResponse response = mock(ServletResponse.class); ServletResponse response = mock(ServletResponse.class);
this.filter.doFilter(request, response, this.chain); this.filter.doFilter(request, response, this.chain);
verifyNoInteractions(this.dispatcher); then(this.dispatcher).shouldHaveNoInteractions();
verify(this.chain).doFilter(request, response); then(this.chain).should().doFilter(request, response);
} }
@Test @Test
@ -92,7 +91,7 @@ class DispatcherFilterTests {
HttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
HttpServletResponse response = new MockHttpServletResponse(); HttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, this.chain); this.filter.doFilter(request, response, this.chain);
verify(this.chain).doFilter(request, response); then(this.chain).should().doFilter(request, response);
} }
@Test @Test
@ -101,8 +100,8 @@ class DispatcherFilterTests {
HttpServletResponse response = new MockHttpServletResponse(); HttpServletResponse response = new MockHttpServletResponse();
willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class)); willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class));
this.filter.doFilter(request, response, this.chain); this.filter.doFilter(request, response, this.chain);
verifyNoInteractions(this.chain); then(this.chain).shouldHaveNoInteractions();
verify(this.dispatcher).handle(this.serverRequestCaptor.capture(), this.serverResponseCaptor.capture()); then(this.dispatcher).should().handle(this.serverRequestCaptor.capture(), this.serverResponseCaptor.capture());
ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue(); ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest; ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue(); ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,16 +38,16 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.withSettings; import static org.mockito.Mockito.withSettings;
/** /**
* Tests for {@link Dispatcher}. * Tests for {@link Dispatcher}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class DispatcherTests { class DispatcherTests {
@ -81,7 +81,7 @@ class DispatcherTests {
given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler);
Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper));
dispatcher.handle(this.serverRequest, this.serverResponse); dispatcher.handle(this.serverRequest, this.serverResponse);
verifyNoInteractions(handler); then(handler).shouldHaveNoInteractions();
assertThat(this.response.getStatus()).isEqualTo(403); assertThat(this.response.getStatus()).isEqualTo(403);
} }
@ -93,7 +93,7 @@ class DispatcherTests {
given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler); given(mapper.getHandler(any(ServerHttpRequest.class))).willReturn(handler);
Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper)); Dispatcher dispatcher = new Dispatcher(this.accessManager, Collections.singleton(mapper));
dispatcher.handle(this.serverRequest, this.serverResponse); dispatcher.handle(this.serverRequest, this.serverResponse);
verify(handler).handle(this.serverRequest, this.serverResponse); then(handler).should().handle(this.serverRequest, this.serverResponse);
} }
@Test @Test
@ -106,8 +106,8 @@ class DispatcherTests {
Dispatcher dispatcher = new Dispatcher(AccessManager.PERMIT_ALL, mappers); Dispatcher dispatcher = new Dispatcher(AccessManager.PERMIT_ALL, mappers);
dispatcher.handle(this.serverRequest, this.serverResponse); dispatcher.handle(this.serverRequest, this.serverResponse);
InOrder inOrder = inOrder(mapper1, mapper2); InOrder inOrder = inOrder(mapper1, mapper2);
inOrder.verify(mapper1).getHandler(this.serverRequest); then(mapper1).should(inOrder).getHandler(this.serverRequest);
inOrder.verify(mapper2).getHandler(this.serverRequest); then(mapper2).should(inOrder).getHandler(this.serverRequest);
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,8 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link ClassLoaderFilesResourcePatternResolver}. * Tests for {@link ClassLoaderFilesResourcePatternResolver}.
@ -50,6 +50,7 @@ import static org.mockito.Mockito.verify;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class ClassLoaderFilesResourcePatternResolverTests { class ClassLoaderFilesResourcePatternResolverTests {
@ -112,7 +113,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
context.setResourceLoader(resourceLoader); context.setResourceLoader(resourceLoader);
this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files);
this.resolver.getResource("foo.txt"); this.resolver.getResource("foo.txt");
verify(resourceLoader).getResource("foo.txt"); then(resourceLoader).should().getResource("foo.txt");
} }
@Test @Test
@ -124,7 +125,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files);
Resource actual = this.resolver.getResource("foo:some-file.txt"); Resource actual = this.resolver.getResource("foo:some-file.txt");
assertThat(actual).isSameAs(resource); assertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.class)); then(resolver).should().resolve(eq("foo:some-file.txt"), any(ResourceLoader.class));
} }
@Test @Test
@ -136,7 +137,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
context.addProtocolResolver(resolver); context.addProtocolResolver(resolver);
Resource actual = this.resolver.getResource("foo:some-file.txt"); Resource actual = this.resolver.getResource("foo:some-file.txt");
assertThat(actual).isSameAs(resource); assertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.class)); then(resolver).should().resolve(eq("foo:some-file.txt"), any(ResourceLoader.class));
} }
@Test @Test
@ -146,7 +147,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
context.setResourceLoader(resourceLoader); context.setResourceLoader(resourceLoader);
this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files);
this.resolver.getResource("foo.txt"); this.resolver.getResource("foo.txt");
verify(resourceLoader).getResource("foo.txt"); then(resourceLoader).should().getResource("foo.txt");
} }
@Test @Test
@ -158,7 +159,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files); this.resolver = new ClassLoaderFilesResourcePatternResolver(context, this.files);
Resource actual = this.resolver.getResource("foo:some-file.txt"); Resource actual = this.resolver.getResource("foo:some-file.txt");
assertThat(actual).isSameAs(resource); assertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.class)); then(resolver).should().resolve(eq("foo:some-file.txt"), any(ResourceLoader.class));
} }
@Test @Test
@ -170,7 +171,7 @@ class ClassLoaderFilesResourcePatternResolverTests {
context.addProtocolResolver(resolver); context.addProtocolResolver(resolver);
Resource actual = this.resolver.getResource("foo:some-file.txt"); Resource actual = this.resolver.getResource("foo:some-file.txt");
assertThat(actual).isSameAs(resource); assertThat(actual).isSameAs(resource);
verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.class)); then(resolver).should().resolve(eq("foo:some-file.txt"), any(ResourceLoader.class));
} }
private ProtocolResolver mockProtocolResolver(String path, Resource resource) { private ProtocolResolver mockProtocolResolver(String path, Resource resource) {

@ -49,14 +49,15 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link Restarter}. * Tests for {@link Restarter}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ExtendWith(OutputCaptureExtension.class) @ExtendWith(OutputCaptureExtension.class)
class RestarterTests { class RestarterTests {
@ -140,7 +141,7 @@ class RestarterTests {
ObjectFactory objectFactory = mock(ObjectFactory.class); ObjectFactory objectFactory = mock(ObjectFactory.class);
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
assertThat(attribute).isEqualTo("abc"); assertThat(attribute).isEqualTo("abc");
verifyNoInteractions(objectFactory); then(objectFactory).shouldHaveNoInteractions();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -22,13 +22,14 @@ import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServerHttpResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link HttpRestartServerHandler}. * Tests for {@link HttpRestartServerHandler}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class HttpRestartServerHandlerTests { class HttpRestartServerHandlerTests {
@ -45,7 +46,7 @@ class HttpRestartServerHandlerTests {
ServerHttpRequest request = mock(ServerHttpRequest.class); ServerHttpRequest request = mock(ServerHttpRequest.class);
ServerHttpResponse response = mock(ServerHttpResponse.class); ServerHttpResponse response = mock(ServerHttpResponse.class);
handler.handle(request, response); handler.handle(request, response);
verify(server).handle(request, response); then(server).should().handle(request, response);
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,13 +38,13 @@ import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link HttpRestartServer}. * Tests for {@link HttpRestartServer}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class HttpRestartServerTests { class HttpRestartServerTests {
@ -83,7 +83,7 @@ class HttpRestartServerTests {
byte[] bytes = serialize(files); byte[] bytes = serialize(files);
request.setContent(bytes); request.setContent(bytes);
this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
verify(this.delegate).updateAndRestart(this.filesCaptor.capture()); then(this.delegate).should().updateAndRestart(this.filesCaptor.capture());
assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull(); assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull();
assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getStatus()).isEqualTo(200);
} }
@ -93,7 +93,7 @@ class HttpRestartServerTests {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
verifyNoInteractions(this.delegate); then(this.delegate).shouldHaveNoInteractions();
assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getStatus()).isEqualTo(500);
} }
@ -104,7 +104,7 @@ class HttpRestartServerTests {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(new byte[] { 0, 0, 0 }); request.setContent(new byte[] { 0, 0, 0 });
this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
verifyNoInteractions(this.delegate); then(this.delegate).shouldHaveNoInteractions();
assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getStatus()).isEqualTo(500);
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -39,9 +39,8 @@ import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link HttpTunnelConnection}. * Tests for {@link HttpTunnelConnection}.
@ -49,6 +48,7 @@ import static org.mockito.Mockito.verify;
* @author Phillip Webb * @author Phillip Webb
* @author Rob Winch * @author Rob Winch
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Yanming Zhou
*/ */
@ExtendWith({ OutputCaptureExtension.class, MockitoExtension.class }) @ExtendWith({ OutputCaptureExtension.class, MockitoExtension.class })
class HttpTunnelConnectionTests { class HttpTunnelConnectionTests {
@ -109,10 +109,10 @@ class HttpTunnelConnectionTests {
void closeTunnelCallsCloseableOnce() throws Exception { void closeTunnelCallsCloseableOnce() throws Exception {
this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE); this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE);
WritableByteChannel channel = openTunnel(false); WritableByteChannel channel = openTunnel(false);
verify(this.closeable, never()).close(); then(this.closeable).should(never()).close();
channel.close(); channel.close();
channel.close(); channel.close();
verify(this.closeable, times(1)).close(); then(this.closeable).should().close();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -22,13 +22,14 @@ import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServerHttpResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link HttpTunnelServerHandler}. * Tests for {@link HttpTunnelServerHandler}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class HttpTunnelServerHandlerTests { class HttpTunnelServerHandlerTests {
@ -45,7 +46,7 @@ class HttpTunnelServerHandlerTests {
ServerHttpRequest request = mock(ServerHttpRequest.class); ServerHttpRequest request = mock(ServerHttpRequest.class);
ServerHttpResponse response = mock(ServerHttpResponse.class); ServerHttpResponse response = mock(ServerHttpResponse.class);
handler.handle(request, response); handler.handle(request, response);
verify(server).handle(request, response); then(server).should().handle(request, response);
} }
} }

@ -50,15 +50,15 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link HttpTunnelServer}. * Tests for {@link HttpTunnelServer}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class HttpTunnelServerTests { class HttpTunnelServerTests {
@ -105,10 +105,10 @@ class HttpTunnelServerTests {
@Test @Test
void serverConnectedOnFirstRequest() throws Exception { void serverConnectedOnFirstRequest() throws Exception {
verify(this.serverConnection, never()).open(anyInt()); then(this.serverConnection).should(never()).open(anyInt());
givenServerConnectionOpenWillAnswerWithServerChannel(); givenServerConnectionOpenWillAnswerWithServerChannel();
this.server.handle(this.request, this.response); this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(DEFAULT_LONG_POLL_TIMEOUT); then(this.serverConnection).should().open(DEFAULT_LONG_POLL_TIMEOUT);
} }
@Test @Test
@ -116,7 +116,7 @@ class HttpTunnelServerTests {
givenServerConnectionOpenWillAnswerWithServerChannel(); givenServerConnectionOpenWillAnswerWithServerChannel();
this.server.setLongPollTimeout(800); this.server.setLongPollTimeout(800);
this.server.handle(this.request, this.response); this.server.handle(this.request, this.response);
verify(this.serverConnection, times(1)).open(800); then(this.serverConnection).should().open(800);
} }
@Test @Test
@ -294,9 +294,9 @@ class HttpTunnelServerTests {
given(request.getAsyncRequestControl(this.response)).willReturn(async); given(request.getAsyncRequestControl(this.response)).willReturn(async);
HttpConnection connection = new HttpConnection(request, this.response); HttpConnection connection = new HttpConnection(request, this.response);
connection.waitForResponse(); connection.waitForResponse();
verify(async).start(); then(async).should().start();
connection.respond(HttpStatus.NO_CONTENT); connection.respond(HttpStatus.NO_CONTENT);
verify(async).complete(); then(async).should().complete();
} }
@Test @Test

@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.BDDMockito.then;
/** /**
* Tests for {@link TestEntityManager}. * Tests for {@link TestEntityManager}.
@ -72,7 +72,7 @@ class TestEntityManagerTests {
given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil);
given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123);
Object result = this.testEntityManager.persistAndGetId(entity); Object result = this.testEntityManager.persistAndGetId(entity);
verify(this.entityManager).persist(entity); then(this.entityManager).should().persist(entity);
assertThat(result).isEqualTo(123); assertThat(result).isEqualTo(123);
} }
@ -83,7 +83,7 @@ class TestEntityManagerTests {
given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil);
given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123);
Integer result = this.testEntityManager.persistAndGetId(entity, Integer.class); Integer result = this.testEntityManager.persistAndGetId(entity, Integer.class);
verify(this.entityManager).persist(entity); then(this.entityManager).should().persist(entity);
assertThat(result).isEqualTo(123); assertThat(result).isEqualTo(123);
} }
@ -92,7 +92,7 @@ class TestEntityManagerTests {
bindEntityManager(); bindEntityManager();
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
TestEntity result = this.testEntityManager.persist(entity); TestEntity result = this.testEntityManager.persist(entity);
verify(this.entityManager).persist(entity); then(this.entityManager).should().persist(entity);
assertThat(result).isSameAs(entity); assertThat(result).isSameAs(entity);
} }
@ -101,8 +101,8 @@ class TestEntityManagerTests {
bindEntityManager(); bindEntityManager();
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
TestEntity result = this.testEntityManager.persistAndFlush(entity); TestEntity result = this.testEntityManager.persistAndFlush(entity);
verify(this.entityManager).persist(entity); then(this.entityManager).should().persist(entity);
verify(this.entityManager).flush(); then(this.entityManager).should().flush();
assertThat(result).isSameAs(entity); assertThat(result).isSameAs(entity);
} }
@ -115,8 +115,8 @@ class TestEntityManagerTests {
given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123);
given(this.entityManager.find(TestEntity.class, 123)).willReturn(found); given(this.entityManager.find(TestEntity.class, 123)).willReturn(found);
TestEntity result = this.testEntityManager.persistFlushFind(entity); TestEntity result = this.testEntityManager.persistFlushFind(entity);
verify(this.entityManager).persist(entity); then(this.entityManager).should().persist(entity);
verify(this.entityManager).flush(); then(this.entityManager).should().flush();
assertThat(result).isSameAs(found); assertThat(result).isSameAs(found);
} }
@ -126,7 +126,7 @@ class TestEntityManagerTests {
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
given(this.entityManager.merge(entity)).willReturn(entity); given(this.entityManager.merge(entity)).willReturn(entity);
TestEntity result = this.testEntityManager.merge(entity); TestEntity result = this.testEntityManager.merge(entity);
verify(this.entityManager).merge(entity); then(this.entityManager).should().merge(entity);
assertThat(result).isSameAs(entity); assertThat(result).isSameAs(entity);
} }
@ -135,7 +135,7 @@ class TestEntityManagerTests {
bindEntityManager(); bindEntityManager();
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
this.testEntityManager.remove(entity); this.testEntityManager.remove(entity);
verify(this.entityManager).remove(entity); then(this.entityManager).should().remove(entity);
} }
@Test @Test
@ -151,7 +151,7 @@ class TestEntityManagerTests {
void flushShouldFlush() { void flushShouldFlush() {
bindEntityManager(); bindEntityManager();
this.testEntityManager.flush(); this.testEntityManager.flush();
verify(this.entityManager).flush(); then(this.entityManager).should().flush();
} }
@Test @Test
@ -159,14 +159,14 @@ class TestEntityManagerTests {
bindEntityManager(); bindEntityManager();
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
this.testEntityManager.refresh(entity); this.testEntityManager.refresh(entity);
verify(this.entityManager).refresh(entity); then(this.entityManager).should().refresh(entity);
} }
@Test @Test
void clearShouldClear() { void clearShouldClear() {
bindEntityManager(); bindEntityManager();
this.testEntityManager.clear(); this.testEntityManager.clear();
verify(this.entityManager).clear(); then(this.entityManager).should().clear();
} }
@Test @Test
@ -174,7 +174,7 @@ class TestEntityManagerTests {
bindEntityManager(); bindEntityManager();
TestEntity entity = new TestEntity(); TestEntity entity = new TestEntity();
this.testEntityManager.detach(entity); this.testEntityManager.detach(entity);
verify(this.entityManager).detach(entity); then(this.entityManager).should().detach(entity);
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,13 +32,14 @@ import org.springframework.test.context.ContextCustomizer;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/** /**
* Tests for {@link PropertyMappingContextCustomizerFactory}. * Tests for {@link PropertyMappingContextCustomizerFactory}.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Yanming Zhou
*/ */
class PropertyMappingContextCustomizerFactoryTests { class PropertyMappingContextCustomizerFactoryTests {
@ -53,7 +54,7 @@ class PropertyMappingContextCustomizerFactoryTests {
given(context.getEnvironment()).willReturn(environment); given(context.getEnvironment()).willReturn(environment);
given(context.getBeanFactory()).willReturn(beanFactory); given(context.getBeanFactory()).willReturn(beanFactory);
customizer.customizeContext(context, null); customizer.customizeContext(context, null);
verifyNoInteractions(environment); then(environment).shouldHaveNoInteractions();
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2020 the original author or authors. * Copyright 2012-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,14 +38,15 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/** /**
* Tests for {@link WebTestClientAutoConfiguration} * Tests for {@link WebTestClientAutoConfiguration}
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Yanming Zhou
*/ */
class WebTestClientAutoConfigurationTests { class WebTestClientAutoConfigurationTests {
@ -65,7 +66,7 @@ class WebTestClientAutoConfigurationTests {
this.contextRunner.withUserConfiguration(CodecConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(CodecConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(WebTestClient.class); assertThat(context).hasSingleBean(WebTestClient.class);
assertThat(context).hasSingleBean(CodecCustomizer.class); assertThat(context).hasSingleBean(CodecCustomizer.class);
verify(context.getBean(CodecCustomizer.class)).customize(any(CodecConfigurer.class)); then(context.getBean(CodecCustomizer.class)).should().customize(any(CodecConfigurer.class));
}); });
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save