Merge pull request #35015 from Ckram

* pr/35015:
  Replace Mockito argument captors with assertArg

Closes gh-35015
pull/35333/head
Moritz Halbritter 2 years ago
commit 25ad24cf7f

@ -21,20 +21,19 @@ import java.util.Base64;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AccessLevel;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.SecurityResponse;
import org.springframework.boot.actuate.autoconfigure.cloudfoundry.Token;
import org.springframework.boot.actuate.endpoint.EndpointId;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -115,10 +114,7 @@ class CloudFoundrySecurityInterceptorTests {
this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class);
then(this.tokenValidator).should().validate(tokenArgumentCaptor.capture());
Token token = tokenArgumentCaptor.getValue();
assertThat(token).hasToString(accessToken);
then(this.tokenValidator).should().validate(assertArg((token) -> assertThat(token).hasToString(accessToken)));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL);
}
@ -129,10 +125,7 @@ class CloudFoundrySecurityInterceptorTests {
this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("info"));
ArgumentCaptor<Token> tokenArgumentCaptor = ArgumentCaptor.forClass(Token.class);
then(this.tokenValidator).should().validate(tokenArgumentCaptor.capture());
Token token = tokenArgumentCaptor.getValue();
assertThat(token).hasToString(accessToken);
then(this.tokenValidator).should().validate(assertArg((token) -> assertThat(token).hasToString(accessToken)));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.RESTRICTED);
}

@ -31,7 +31,6 @@ import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfi
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.jmx.EndpointObjectNameFactory;
import org.springframework.boot.actuate.endpoint.jmx.ExposableJmxEndpoint;
import org.springframework.boot.actuate.endpoint.jmx.JmxEndpointExporter;
import org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpointDiscoverer;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -42,6 +41,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -86,13 +86,9 @@ class JmxEndpointAutoConfigurationTests {
.withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test")
.with(mockMBeanServer())
.withBean(EndpointObjectNameFactory.class, () -> factory)
.run((context) -> {
ArgumentCaptor<ExposableJmxEndpoint> argumentCaptor = ArgumentCaptor
.forClass(ExposableJmxEndpoint.class);
then(factory).should().getObjectName(argumentCaptor.capture());
ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue();
assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test");
});
.run((context) -> then(factory).should()
.getObjectName(assertArg((jmxEndpoint) -> assertThat(jmxEndpoint.getEndpointId().toLowerCaseString())
.isEqualTo("test"))));
}
@Test

@ -28,8 +28,6 @@ import javax.management.ObjectName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ -42,6 +40,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willThrow;
@ -55,21 +54,15 @@ import static org.mockito.BDDMockito.willThrow;
@ExtendWith(MockitoExtension.class)
class JmxEndpointExporterTests {
@Mock
private MBeanServer mBeanServer;
@Spy
private EndpointObjectNameFactory objectNameFactory = new TestEndpointObjectNameFactory();
private final JmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper();
private final List<ExposableJmxEndpoint> endpoints = new ArrayList<>();
@Captor
private ArgumentCaptor<Object> objectCaptor;
@Mock
private MBeanServer mBeanServer;
@Captor
private ArgumentCaptor<ObjectName> objectNameCaptor;
@Spy
private EndpointObjectNameFactory objectNameFactory = new TestEndpointObjectNameFactory();
private JmxEndpointExporter exporter;
@ -113,9 +106,9 @@ class JmxEndpointExporterTests {
void afterPropertiesSetShouldRegisterMBeans() throws Exception {
this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation()));
this.exporter.afterPropertiesSet();
then(this.mBeanServer).should().registerMBean(this.objectCaptor.capture(), this.objectNameCaptor.capture());
assertThat(this.objectCaptor.getValue()).isInstanceOf(EndpointMBean.class);
assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test");
then(this.mBeanServer).should()
.registerMBean(assertArg((object) -> assertThat(object).isInstanceOf(EndpointMBean.class)),
assertArg((objectName) -> assertThat(objectName.getKeyProperty("name")).isEqualTo("test")));
}
@Test
@ -148,8 +141,9 @@ class JmxEndpointExporterTests {
this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation()));
this.exporter.afterPropertiesSet();
this.exporter.destroy();
then(this.mBeanServer).should().unregisterMBean(this.objectNameCaptor.capture());
assertThat(this.objectNameCaptor.getValue().getKeyProperty("name")).isEqualTo("test");
then(this.mBeanServer).should()
.unregisterMBean(
assertArg((objectName) -> assertThat(objectName.getKeyProperty("name")).isEqualTo("test")));
}
@Test

@ -27,8 +27,6 @@ import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -37,6 +35,7 @@ import org.springframework.boot.actuate.endpoint.EndpointId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -57,9 +56,6 @@ class ServletEndpointRegistrarTests {
@Mock
private Dynamic dynamic;
@Captor
private ArgumentCaptor<Servlet> servlet;
@Test
void createWhenServletEndpointsIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null))
@ -91,8 +87,9 @@ class ServletEndpointRegistrarTests {
ExposableServletEndpoint endpoint = mockEndpoint(new EndpointServlet(TestServlet.class));
ServletEndpointRegistrar registrar = new ServletEndpointRegistrar(basePath, Collections.singleton(endpoint));
registrar.onStartup(this.servletContext);
then(this.servletContext).should().addServlet(eq("test-actuator-endpoint"), this.servlet.capture());
assertThat(this.servlet.getValue()).isInstanceOf(TestServlet.class);
then(this.servletContext).should()
.addServlet(eq("test-actuator-endpoint"),
(Servlet) assertArg((servlet) -> assertThat(servlet).isInstanceOf(TestServlet.class)));
then(this.dynamic).should().addMapping(expectedMapping);
}

@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
@ -35,10 +34,10 @@ import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -83,11 +82,9 @@ class SharedMetadataReaderFactoryContextInitializerTests {
context.refresh();
ConfigurationClassPostProcessor bean = context.getBean(ConfigurationClassPostProcessor.class);
assertThat(bean).isSameAs(configurationAnnotationPostProcessor);
ArgumentCaptor<MetadataReaderFactory> metadataReaderFactory = ArgumentCaptor
.forClass(MetadataReaderFactory.class);
then(configurationAnnotationPostProcessor).should().setMetadataReaderFactory(metadataReaderFactory.capture());
assertThat(metadataReaderFactory.getValue())
.isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class);
then(configurationAnnotationPostProcessor).should()
.setMetadataReaderFactory(assertArg((metadataReaderFactory) -> assertThat(metadataReaderFactory)
.isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class)));
}
static class TestConfig {

@ -22,7 +22,6 @@ import java.util.Set;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Entity;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.autoconfigure.domain.scan.a.EmbeddableA;
import org.springframework.boot.autoconfigure.domain.scan.a.EntityA;
@ -39,6 +38,7 @@ import org.springframework.core.type.filter.AnnotationTypeFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -109,12 +109,13 @@ class EntityScannerTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class);
TestEntityScanner scanner = new TestEntityScanner(context, candidateComponentProvider);
scanner.scan(Entity.class);
ArgumentCaptor<AnnotationTypeFilter> annotationTypeFilter = ArgumentCaptor.forClass(AnnotationTypeFilter.class);
then(candidateComponentProvider).should().addIncludeFilter(annotationTypeFilter.capture());
then(candidateComponentProvider).should()
.addIncludeFilter(
assertArg((typeFilter) -> assertThat(typeFilter).isInstanceOfSatisfying(AnnotationTypeFilter.class,
(filter) -> assertThat(filter.getAnnotationType()).isEqualTo(Entity.class))));
then(candidateComponentProvider).should()
.findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan");
then(candidateComponentProvider).shouldHaveNoMoreInteractions();
assertThat(annotationTypeFilter.getValue().getAnnotationType()).isEqualTo(Entity.class);
}
@Test

@ -24,12 +24,12 @@ import org.jooq.SQLDialect;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.springframework.jdbc.BadSqlGrammarException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -53,9 +53,7 @@ class JooqExceptionTranslatorTests {
given(configuration.dialect()).willReturn(dialect);
given(context.sqlException()).willReturn(sqlException);
this.exceptionTranslator.exception(context);
ArgumentCaptor<RuntimeException> captor = ArgumentCaptor.forClass(RuntimeException.class);
then(context).should().exception(captor.capture());
assertThat(captor.getValue()).isInstanceOf(BadSqlGrammarException.class);
then(context).should().exception(assertArg((ex) -> assertThat(ex).isInstanceOf(BadSqlGrammarException.class)));
}
@Test

@ -20,7 +20,6 @@ import java.net.InetAddress;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.ssl.DefaultSslBundleRegistry;
@ -30,6 +29,7 @@ import org.springframework.boot.web.server.Shutdown;
import org.springframework.boot.web.server.Ssl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -85,9 +85,7 @@ class ReactiveWebServerFactoryCustomizerTests {
this.properties.setShutdown(Shutdown.GRACEFUL);
ConfigurableReactiveWebServerFactory factory = mock(ConfigurableReactiveWebServerFactory.class);
this.customizer.customize(factory);
ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class);
then(factory).should().setShutdown(shutdownCaptor.capture());
assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL);
then(factory).should().setShutdown(assertArg((shutdown) -> assertThat(shutdown).isEqualTo(Shutdown.GRACEFUL)));
}
}

@ -22,7 +22,6 @@ import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.bind.Bindable;
@ -33,11 +32,11 @@ import org.springframework.boot.web.server.Shutdown;
import org.springframework.boot.web.server.Ssl;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.boot.web.servlet.server.Jsp;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.boot.web.servlet.server.Session.Cookie;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -113,16 +112,16 @@ class ServletWebServerFactoryCustomizerTests {
bindProperties(map);
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory);
ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class);
then(factory).should().setSession(sessionCaptor.capture());
assertThat(sessionCaptor.getValue().getTimeout()).hasSeconds(123);
Cookie cookie = sessionCaptor.getValue().getCookie();
assertThat(cookie.getName()).isEqualTo("testname");
assertThat(cookie.getDomain()).isEqualTo("testdomain");
assertThat(cookie.getPath()).isEqualTo("/testpath");
assertThat(cookie.getComment()).isEqualTo("testcomment");
assertThat(cookie.getHttpOnly()).isTrue();
assertThat(cookie.getMaxAge()).hasSeconds(60);
then(factory).should().setSession(assertArg((session) -> {
assertThat(session.getTimeout()).hasSeconds(123);
Cookie cookie = session.getCookie();
assertThat(cookie.getName()).isEqualTo("testname");
assertThat(cookie.getDomain()).isEqualTo("testdomain");
assertThat(cookie.getPath()).isEqualTo("/testpath");
assertThat(cookie.getComment()).isEqualTo("testcomment");
assertThat(cookie.getHttpOnly()).isTrue();
assertThat(cookie.getMaxAge()).hasSeconds(60);
}));
}
@Test
@ -158,9 +157,8 @@ class ServletWebServerFactoryCustomizerTests {
bindProperties(map);
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory);
ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class);
then(factory).should().setSession(sessionCaptor.capture());
assertThat(sessionCaptor.getValue().getStoreDir()).isEqualTo(new File("mydirectory"));
then(factory).should()
.setSession(assertArg((session) -> assertThat(session.getStoreDir()).isEqualTo(new File("mydirectory"))));
}
@Test
@ -170,9 +168,7 @@ class ServletWebServerFactoryCustomizerTests {
bindProperties(map);
ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class);
this.customizer.customize(factory);
ArgumentCaptor<Shutdown> shutdownCaptor = ArgumentCaptor.forClass(Shutdown.class);
then(factory).should().setShutdown(shutdownCaptor.capture());
assertThat(shutdownCaptor.getValue()).isEqualTo(Shutdown.GRACEFUL);
then(factory).should().setShutdown(assertArg((shutdown) -> assertThat(shutdown).isEqualTo(Shutdown.GRACEFUL)));
}
private void bindProperties(Map<String, String> map) {

@ -23,19 +23,17 @@ import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.devtools.filewatch.ChangedFile;
import org.springframework.boot.devtools.filewatch.ChangedFiles;
import org.springframework.boot.devtools.filewatch.FileSystemWatcher;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
@ -57,9 +55,6 @@ class ClassPathFileChangeListenerTests {
@Mock
private FileSystemWatcher fileSystemWatcher;
@Captor
private ArgumentCaptor<ApplicationEvent> eventCaptor;
@Test
void eventPublisherMustNotBeNull() {
assertThatIllegalArgumentException()
@ -102,10 +97,12 @@ class ClassPathFileChangeListenerTests {
given(this.restartStrategy.isRestartRequired(file2)).willReturn(true);
}
listener.onChange(changeSet);
then(this.eventPublisher).should().publishEvent(this.eventCaptor.capture());
ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor.getValue();
assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet);
assertThat(actualEvent.isRestartRequired()).isEqualTo(restart);
then(this.eventPublisher).should()
.publishEvent(assertArg((applicationEvent) -> assertThat(applicationEvent)
.isInstanceOfSatisfying(ClassPathChangedEvent.class, (classPathChangedEvent) -> {
assertThat(classPathChangedEvent.getChangeSet()).isEqualTo(changeSet);
assertThat(classPathChangedEvent.isRestartRequired()).isEqualTo(restart);
})));
}
}

@ -24,8 +24,6 @@ import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -39,6 +37,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willReturn;
import static org.mockito.Mockito.mock;
@ -57,12 +56,6 @@ class DispatcherFilterTests {
@Mock
private FilterChain chain;
@Captor
private ArgumentCaptor<ServerHttpResponse> serverResponseCaptor;
@Captor
private ArgumentCaptor<ServerHttpRequest> serverRequestCaptor;
private DispatcherFilter filter;
@BeforeEach
@ -100,13 +93,15 @@ class DispatcherFilterTests {
willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class), any(ServerHttpResponse.class));
this.filter.doFilter(request, response, this.chain);
then(this.chain).shouldHaveNoInteractions();
then(this.dispatcher).should().handle(this.serverRequestCaptor.capture(), this.serverResponseCaptor.capture());
ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();
ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse;
assertThat(actualRequest.getServletRequest()).isEqualTo(request);
assertThat(actualResponse.getServletResponse()).isEqualTo(response);
then(this.dispatcher).should()
.handle(assertArg((serverHttpRequest) -> assertThat(serverHttpRequest).isInstanceOfSatisfying(
ServletServerHttpRequest.class,
(servletServerHttpRequest) -> assertThat(servletServerHttpRequest.getServletRequest())
.isEqualTo(request))),
assertArg((serverHttpResponse) -> assertThat(serverHttpResponse).isInstanceOfSatisfying(
ServletServerHttpResponse.class,
(servletServerHttpResponse) -> assertThat(servletServerHttpResponse.getServletResponse())
.isEqualTo(response))));
}
}

@ -23,8 +23,6 @@ import java.io.ObjectOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -38,6 +36,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
/**
@ -53,9 +52,6 @@ class HttpRestartServerTests {
private HttpRestartServer server;
@Captor
private ArgumentCaptor<ClassLoaderFiles> filesCaptor;
@BeforeEach
void setup() {
this.server = new HttpRestartServer(this.delegate);
@ -82,8 +78,9 @@ class HttpRestartServerTests {
byte[] bytes = serialize(files);
request.setContent(bytes);
this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
then(this.delegate).should().updateAndRestart(this.filesCaptor.capture());
assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull();
then(this.delegate).should()
.updateAndRestart(
assertArg((classLoaderFiles) -> assertThat(classLoaderFiles.getFile("name")).isNotNull()));
assertThat(response.getStatus()).isEqualTo(200);
}

@ -17,7 +17,6 @@
package org.springframework.boot.test.mock.mockito;
import java.io.InputStream;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -32,6 +31,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -53,9 +53,6 @@ class MockitoTestExecutionListenerTests {
@Mock
private MockitoPostProcessor postProcessor;
@Captor
private ArgumentCaptor<Field> fieldCaptor;
@Test
void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception {
WithMockitoAnnotations instance = new WithMockitoAnnotations();
@ -71,8 +68,9 @@ class MockitoTestExecutionListenerTests {
TestContext testContext = mockTestContext(instance);
given(testContext.getApplicationContext()).willReturn(this.applicationContext);
this.listener.prepareTestInstance(testContext);
then(this.postProcessor).should().inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class));
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
then(this.postProcessor).should()
.inject(assertArg((field) -> assertThat(field.getName()).isEqualTo("mockBean")), eq(instance),
any(MockDefinition.class));
}
@Test
@ -90,8 +88,9 @@ class MockitoTestExecutionListenerTests {
given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))
.willReturn(Boolean.TRUE);
this.listener.beforeTestMethod(mockTestContext);
then(this.postProcessor).should().inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class));
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
then(this.postProcessor).should()
.inject(assertArg((field) -> assertThat(field.getName()).isEqualTo("mockBean")), eq(instance),
any(MockDefinition.class));
}
@SuppressWarnings({ "unchecked", "rawtypes" })

@ -22,19 +22,17 @@ import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.then;
@ -49,9 +47,6 @@ class QualifierDefinitionTests {
@Mock
private ConfigurableListableBeanFactory beanFactory;
@Captor
private ArgumentCaptor<DependencyDescriptor> descriptorCaptor;
@Test
void forElementFieldIsNullShouldReturnNull() {
assertThat(QualifierDefinition.forElement((Field) null)).isNull();
@ -81,8 +76,9 @@ class QualifierDefinitionTests {
Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier");
QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field);
qualifierDefinition.matches(this.beanFactory, "bean");
then(this.beanFactory).should().isAutowireCandidate(eq("bean"), this.descriptorCaptor.capture());
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()).isEqualTo(field);
then(this.beanFactory).should()
.isAutowireCandidate(eq("bean"), assertArg(
(dependencyDescriptor) -> assertThat(dependencyDescriptor.getAnnotatedElement()).isEqualTo(field)));
}
@Test

@ -21,8 +21,6 @@ import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -39,6 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -60,9 +59,6 @@ class RootUriRequestExpectationManagerTests {
private RootUriRequestExpectationManager manager;
@Captor
private ArgumentCaptor<ClientHttpRequest> requestCaptor;
@BeforeEach
void setup() {
this.manager = new RootUriRequestExpectationManager(this.uri, this.delegate);
@ -101,10 +97,14 @@ class RootUriRequestExpectationManagerTests {
ClientHttpRequest request = mock(ClientHttpRequest.class);
given(request.getURI()).willReturn(new URI(this.uri + "/hello"));
this.manager.validateRequest(request);
then(this.delegate).should().validateRequest(this.requestCaptor.capture());
HttpRequestWrapper actual = (HttpRequestWrapper) this.requestCaptor.getValue();
assertThat(actual.getRequest()).isSameAs(request);
assertThat(actual.getURI()).isEqualTo(new URI("/hello"));
URI expectedURI = new URI("/hello");
then(this.delegate).should()
.validateRequest(assertArg((actual) -> assertThat(actual).isInstanceOfSatisfying(HttpRequestWrapper.class,
(requestWrapper) -> {
assertThat(requestWrapper.getRequest()).isSameAs(request);
assertThat(requestWrapper.getURI()).isEqualTo(expectedURI);
})));
}
@Test

@ -22,12 +22,9 @@ import java.net.URL;
import com.gargoylesoftware.htmlunit.StringWebResponse;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.env.MockEnvironment;
@ -35,6 +32,7 @@ import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -48,9 +46,6 @@ import static org.mockito.Mockito.mock;
@ExtendWith(MockitoExtension.class)
class LocalHostWebClientTests {
@Captor
private ArgumentCaptor<WebRequest> requestCaptor;
@Test
void createWhenEnvironmentIsNullWillThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null))
@ -64,8 +59,9 @@ class LocalHostWebClientTests {
WebConnection connection = mockConnection();
client.setWebConnection(connection);
client.getPage("/test");
then(connection).should().getResponse(this.requestCaptor.capture());
assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8080/test"));
URL expectedUrl = new URL("http://localhost:8080/test");
then(connection).should()
.getResponse(assertArg((request) -> assertThat(request.getUrl()).isEqualTo(expectedUrl)));
}
@Test
@ -76,8 +72,9 @@ class LocalHostWebClientTests {
WebConnection connection = mockConnection();
client.setWebConnection(connection);
client.getPage("/test");
then(connection).should().getResponse(this.requestCaptor.capture());
assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8181/test"));
URL expectedUrl = new URL("http://localhost:8181/test");
then(connection).should()
.getResponse(assertArg((request) -> assertThat(request.getUrl()).isEqualTo(expectedUrl)));
}
private WebConnection mockConnection() throws IOException {

@ -47,6 +47,7 @@ import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -77,9 +78,6 @@ class HttpClientTransportTests {
@Mock
private InputStream content;
@Captor
private ArgumentCaptor<HttpHost> hostCaptor;
@Captor
private ArgumentCaptor<HttpUriRequest> requestCaptor;
@ -99,12 +97,18 @@ class HttpClientTransportTests {
given(this.entity.getContent()).willReturn(this.content);
given(this.response.getCode()).willReturn(200);
Response response = this.http.get(this.uri);
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
assertThat(request).isInstanceOf(HttpGet.class);
assertThat(request.getUri()).isEqualTo(this.uri);
assertThat(request.getFirstHeader(HttpHeaders.CONTENT_TYPE)).isNull();
assertThat(response.getContent()).isSameAs(this.content);
then(this.client).should().executeOpen(any(HttpHost.class), assertArg((request) -> {
try {
assertThat(request).isInstanceOf(HttpGet.class);
assertThat(request.getUri()).isEqualTo(this.uri);
assertThat(request.getFirstHeader(HttpHeaders.CONTENT_TYPE)).isNull();
assertThat(response.getContent()).isSameAs(this.content);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}), isNull());
}
@Test
@ -113,7 +117,7 @@ class HttpClientTransportTests {
given(this.entity.getContent()).willReturn(this.content);
given(this.response.getCode()).willReturn(200);
Response response = this.http.post(this.uri);
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
assertThat(request).isInstanceOf(HttpPost.class);
assertThat(request.getUri()).isEqualTo(this.uri);
@ -128,7 +132,7 @@ class HttpClientTransportTests {
given(this.entity.getContent()).willReturn(this.content);
given(this.response.getCode()).willReturn(200);
Response response = this.http.post(this.uri, "auth token");
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
assertThat(request).isInstanceOf(HttpPost.class);
assertThat(request.getUri()).isEqualTo(this.uri);
@ -143,7 +147,7 @@ class HttpClientTransportTests {
given(this.entity.getContent()).willReturn(this.content);
given(this.response.getCode()).willReturn(200);
Response response = this.http.post(this.uri, "");
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
assertThat(request).isInstanceOf(HttpPost.class);
assertThat(request.getUri()).isEqualTo(this.uri);
@ -160,7 +164,7 @@ class HttpClientTransportTests {
given(this.response.getCode()).willReturn(200);
Response response = this.http.post(this.uri, APPLICATION_JSON,
(out) -> StreamUtils.copy(content, StandardCharsets.UTF_8, out));
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
HttpEntity entity = request.getEntity();
assertThat(request).isInstanceOf(HttpPost.class);
@ -182,7 +186,7 @@ class HttpClientTransportTests {
given(this.response.getCode()).willReturn(200);
Response response = this.http.post(this.uri, APPLICATION_X_TAR,
(out) -> StreamUtils.copy(content, StandardCharsets.UTF_8, out));
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
HttpEntity entity = request.getEntity();
assertThat(request).isInstanceOf(HttpPost.class);
@ -204,7 +208,7 @@ class HttpClientTransportTests {
given(this.response.getCode()).willReturn(200);
Response response = this.http.put(this.uri, APPLICATION_JSON,
(out) -> StreamUtils.copy(content, StandardCharsets.UTF_8, out));
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
HttpEntity entity = request.getEntity();
assertThat(request).isInstanceOf(HttpPut.class);
@ -226,7 +230,7 @@ class HttpClientTransportTests {
given(this.response.getCode()).willReturn(200);
Response response = this.http.put(this.uri, APPLICATION_X_TAR,
(out) -> StreamUtils.copy(content, StandardCharsets.UTF_8, out));
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
HttpEntity entity = request.getEntity();
assertThat(request).isInstanceOf(HttpPut.class);
@ -246,7 +250,7 @@ class HttpClientTransportTests {
given(this.entity.getContent()).willReturn(this.content);
given(this.response.getCode()).willReturn(200);
Response response = this.http.delete(this.uri);
then(this.client).should().executeOpen(this.hostCaptor.capture(), this.requestCaptor.capture(), isNull());
then(this.client).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
HttpUriRequest request = this.requestCaptor.getValue();
assertThat(request).isInstanceOf(HttpDelete.class);
assertThat(request.getUri()).isEqualTo(this.uri);

@ -25,14 +25,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import joptsimple.OptionSet;
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHost;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.cli.command.status.ExitStatus;
@ -40,6 +36,7 @@ import org.springframework.boot.cli.command.status.ExitStatus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.then;
@ -57,9 +54,6 @@ class InitCommandTests extends AbstractHttpClientMockTests {
private final InitCommand command;
@Captor
private ArgumentCaptor<HttpUriRequest> requestCaptor;
InitCommandTests() {
InitializrService initializrService = new InitializrService(this.http);
this.handler = new TestableInitCommandOptionHandler(initializrService);
@ -400,9 +394,9 @@ class InitCommandTests extends AbstractHttpClientMockTests {
@Test
void userAgent() throws Exception {
this.command.run("--list", "--target=https://fake-service");
then(this.http).should().executeOpen(any(HttpHost.class), this.requestCaptor.capture(), isNull());
Header agent = this.requestCaptor.getValue().getHeaders("User-Agent")[0];
assertThat(agent.getValue()).startsWith("SpringBootCli/");
then(this.http).should()
.executeOpen(any(HttpHost.class), assertArg((request) -> assertThat(
request.getHeaders("User-Agent")[0].getValue().startsWith("SpringBootCli/"))), isNull());
}
private byte[] createFakeZipArchive(String fileName, String content) throws IOException {

@ -41,6 +41,7 @@ import org.springframework.boot.loader.tools.LibraryCallback;
import org.springframework.boot.loader.tools.LibraryScope;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -85,11 +86,11 @@ class ArtifactsLibrariesTests {
given(this.artifact.getArtifactHandler()).willReturn(this.artifactHandler);
given(this.artifact.getScope()).willReturn("compile");
this.libs.doWithLibraries(this.callback);
then(this.callback).should().library(this.libraryCaptor.capture());
Library library = this.libraryCaptor.getValue();
assertThat(library.getFile()).isEqualTo(this.file);
assertThat(library.getScope()).isEqualTo(LibraryScope.COMPILE);
assertThat(library.isUnpackRequired()).isFalse();
then(this.callback).should().library(assertArg((library) -> {
assertThat(library.getFile()).isEqualTo(this.file);
assertThat(library.getScope()).isEqualTo(LibraryScope.COMPILE);
assertThat(library.isUnpackRequired()).isFalse();
}));
}
@Test
@ -105,8 +106,7 @@ class ArtifactsLibrariesTests {
this.libs = new ArtifactsLibraries(this.artifacts, Collections.emptyList(), Collections.singleton(unpack),
mock(Log.class));
this.libs.doWithLibraries(this.callback);
then(this.callback).should().library(this.libraryCaptor.capture());
assertThat(this.libraryCaptor.getValue().isUnpackRequired()).isTrue();
then(this.callback).should().library(assertArg((library) -> assertThat(library.isUnpackRequired()).isTrue()));
}
@Test

@ -21,8 +21,6 @@ import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -33,6 +31,7 @@ import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
/**
@ -47,9 +46,6 @@ class DefaultPropertiesPropertySourceTests {
@Mock
private Consumer<DefaultPropertiesPropertySource> action;
@Captor
private ArgumentCaptor<DefaultPropertiesPropertySource> captor;
@Test
void nameIsDefaultProperties() {
assertThat(DefaultPropertiesPropertySource.NAME).isEqualTo("defaultProperties");
@ -95,8 +91,8 @@ class DefaultPropertiesPropertySourceTests {
@Test
void ifNotEmptyHasValueCallsAction() {
DefaultPropertiesPropertySource.ifNotEmpty(Collections.singletonMap("spring", "boot"), this.action);
then(this.action).should().accept(this.captor.capture());
assertThat(this.captor.getValue().getProperty("spring")).isEqualTo("boot");
then(this.action).should()
.accept(assertArg((properties) -> assertThat(properties.getProperty("spring")).isEqualTo("boot")));
}
@Test

@ -34,7 +34,6 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
@ -129,6 +128,7 @@ import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
@ -829,9 +829,9 @@ class SpringApplicationTests {
application.addListeners(listener);
application.setWebApplicationType(WebApplicationType.NONE);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run);
ArgumentCaptor<RuntimeException> exceptionCaptor = ArgumentCaptor.forClass(RuntimeException.class);
then(handler).should().registerLoggedException(exceptionCaptor.capture());
assertThat(exceptionCaptor.getValue()).hasCauseInstanceOf(RefreshFailureException.class);
then(handler).should()
.registerLoggedException(
assertArg((exception) -> assertThat(exception).hasCauseInstanceOf(RefreshFailureException.class)));
assertThat(output).doesNotContain("NullPointerException");
}

@ -20,11 +20,11 @@ import java.time.Duration;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.system.ApplicationPid;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -44,11 +44,11 @@ class StartupInfoLoggerTests {
void startingFormat() {
given(this.log.isInfoEnabled()).willReturn(true);
new StartupInfoLogger(getClass()).logStarting(this.log);
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
then(this.log).should().info(captor.capture());
assertThat(captor.getValue().toString()).contains("Starting " + getClass().getSimpleName() + " using Java "
+ System.getProperty("java.version") + " with PID " + new ApplicationPid() + " (started by "
+ System.getProperty("user.name") + " in " + System.getProperty("user.dir") + ")");
then(this.log).should()
.info(assertArg((message) -> assertThat(message.toString())
.contains("Starting " + getClass().getSimpleName() + " using Java " + System.getProperty("java.version")
+ " with PID " + new ApplicationPid() + " (started by " + System.getProperty("user.name")
+ " in " + System.getProperty("user.dir") + ")")));
}
@Test
@ -57,12 +57,11 @@ class StartupInfoLoggerTests {
try {
given(this.log.isInfoEnabled()).willReturn(true);
new StartupInfoLogger(getClass()).logStarting(this.log);
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
then(this.log).should().info(captor.capture());
assertThat(captor.getValue().toString())
.contains("Starting AOT-processed " + getClass().getSimpleName() + " using Java "
+ System.getProperty("java.version") + " with PID " + new ApplicationPid() + " (started by "
+ System.getProperty("user.name") + " in " + System.getProperty("user.dir") + ")");
then(this.log).should()
.info(assertArg((message) -> assertThat(message.toString())
.contains("Starting AOT-processed " + getClass().getSimpleName() + " using Java "
+ System.getProperty("java.version") + " with PID " + new ApplicationPid() + " (started by "
+ System.getProperty("user.name") + " in " + System.getProperty("user.dir") + ")")));
}
finally {
@ -75,10 +74,9 @@ class StartupInfoLoggerTests {
given(this.log.isInfoEnabled()).willReturn(true);
Duration timeTakenToStartup = Duration.ofMillis(10);
new StartupInfoLogger(getClass()).logStarted(this.log, timeTakenToStartup);
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
then(this.log).should().info(captor.capture());
assertThat(captor.getValue().toString()).matches("Started " + getClass().getSimpleName()
+ " in \\d+\\.\\d{1,3} seconds \\(process running for \\d+\\.\\d{1,3}\\)");
then(this.log).should()
.info(assertArg((message) -> assertThat(message.toString()).matches("Started " + getClass().getSimpleName()
+ " in \\d+\\.\\d{1,3} seconds \\(process running for \\d+\\.\\d{1,3}\\)")));
}
}

@ -17,10 +17,8 @@
package org.springframework.boot.availability;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
@ -28,6 +26,7 @@ import org.springframework.core.ResolvableType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
@ -76,11 +75,12 @@ class AvailabilityChangeEventTests {
ApplicationContext context = mock(ApplicationContext.class);
AvailabilityState state = LivenessState.CORRECT;
AvailabilityChangeEvent.publish(context, state);
ArgumentCaptor<ApplicationEvent> captor = ArgumentCaptor.forClass(ApplicationEvent.class);
then(context).should().publishEvent(captor.capture());
AvailabilityChangeEvent<?> event = (AvailabilityChangeEvent<?>) captor.getValue();
assertThat(event.getSource()).isEqualTo(context);
assertThat(event.getState()).isEqualTo(state);
then(context).should()
.publishEvent(assertArg((event) -> assertThat(event).isInstanceOfSatisfying(AvailabilityChangeEvent.class,
(castedEvent) -> {
assertThat(castedEvent.getSource()).isEqualTo(context);
assertThat(castedEvent.getState()).isEqualTo(state);
})));
}
@Test

@ -46,6 +46,7 @@ import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -79,9 +80,6 @@ class ConfigDataEnvironmentContributorsTests {
@Captor
private ArgumentCaptor<ConfigDataLocationResolverContext> locationResolverContext;
@Captor
private ArgumentCaptor<ConfigDataLoaderContext> loaderContext;
@BeforeEach
void setup() {
this.environment = new MockEnvironment();
@ -187,9 +185,11 @@ class ConfigDataEnvironmentContributorsTests {
ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory,
this.bootstrapContext, Arrays.asList(existingContributor, contributor));
contributors.withProcessedImports(this.importer, this.activationContext);
then(this.importer).should().resolveAndLoad(any(), this.locationResolverContext.capture(), any(), any());
ConfigDataLocationResolverContext context = this.locationResolverContext.getValue();
assertThat(context.getBinder().bind("test", String.class).get()).isEqualTo("springboot");
then(this.importer).should()
.resolveAndLoad(any(),
assertArg((context) -> assertThat(context.getBinder().bind("test", String.class).get())
.isEqualTo("springboot")),
any(), any());
}
@Test
@ -238,9 +238,10 @@ class ConfigDataEnvironmentContributorsTests {
ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory,
this.bootstrapContext, Arrays.asList(existingContributor, contributor));
contributors.withProcessedImports(this.importer, this.activationContext);
then(this.importer).should().resolveAndLoad(any(), this.locationResolverContext.capture(), any(), any());
ConfigDataLocationResolverContext context = this.locationResolverContext.getValue();
assertThat(context.getBootstrapContext()).isSameAs(this.bootstrapContext);
then(this.importer).should()
.resolveAndLoad(any(),
assertArg((context) -> assertThat(context.getBootstrapContext()).isSameAs(this.bootstrapContext)),
any(), any());
}
@Test
@ -261,9 +262,10 @@ class ConfigDataEnvironmentContributorsTests {
ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory,
this.bootstrapContext, Arrays.asList(existingContributor, contributor));
contributors.withProcessedImports(this.importer, this.activationContext);
then(this.importer).should().resolveAndLoad(any(), any(), this.loaderContext.capture(), any());
ConfigDataLoaderContext context = this.loaderContext.getValue();
assertThat(context.getBootstrapContext()).isSameAs(this.bootstrapContext);
then(this.importer).should()
.resolveAndLoad(any(), any(),
assertArg((context) -> assertThat(context.getBootstrapContext()).isSameAs(this.bootstrapContext)),
any());
}
@Test

@ -17,13 +17,10 @@
package org.springframework.boot.context.config;
import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ -36,6 +33,7 @@ import org.springframework.core.io.ResourceLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willReturn;
import static org.mockito.Mockito.mock;
@ -61,19 +59,15 @@ class ConfigDataEnvironmentPostProcessorTests {
private ConfigDataEnvironmentPostProcessor postProcessor = new ConfigDataEnvironmentPostProcessor(Supplier::get,
new DefaultBootstrapContext());
@Captor
private ArgumentCaptor<Set<String>> additionalProfilesCaptor;
@Captor
private ArgumentCaptor<ResourceLoader> resourceLoaderCaptor;
@Test
void postProcessEnvironmentWhenNoLoaderCreatesDefaultLoaderInstance() {
willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any());
this.postProcessor.postProcessEnvironment(this.environment, this.application);
then(this.postProcessor).should().getConfigDataEnvironment(any(), this.resourceLoaderCaptor.capture(), any());
then(this.postProcessor).should()
.getConfigDataEnvironment(any(),
assertArg((resourceLoader) -> assertThat(resourceLoader).isInstanceOf(DefaultResourceLoader.class)),
any());
then(this.configDataEnvironment).should().processAndApply();
assertThat(this.resourceLoaderCaptor.getValue()).isInstanceOf(DefaultResourceLoader.class);
}
@Test
@ -82,9 +76,10 @@ class ConfigDataEnvironmentPostProcessorTests {
this.application.setResourceLoader(resourceLoader);
willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any());
this.postProcessor.postProcessEnvironment(this.environment, this.application);
then(this.postProcessor).should().getConfigDataEnvironment(any(), this.resourceLoaderCaptor.capture(), any());
then(this.postProcessor).should()
.getConfigDataEnvironment(any(),
assertArg((resourceLoaderB) -> assertThat(resourceLoaderB).isSameAs(resourceLoader)), any());
then(this.configDataEnvironment).should().processAndApply();
assertThat(this.resourceLoaderCaptor.getValue()).isSameAs(resourceLoader);
}
@Test
@ -93,16 +88,16 @@ class ConfigDataEnvironmentPostProcessorTests {
willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any());
this.postProcessor.postProcessEnvironment(this.environment, this.application);
then(this.postProcessor).should()
.getConfigDataEnvironment(any(), any(), this.additionalProfilesCaptor.capture());
.getConfigDataEnvironment(any(), any(),
assertArg((additionalProperties) -> assertThat(additionalProperties).containsExactly("dev")));
then(this.configDataEnvironment).should().processAndApply();
assertThat(this.additionalProfilesCaptor.getValue()).containsExactly("dev");
}
@Test
void postProcessEnvironmentWhenNoActiveProfiles() {
willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any());
this.postProcessor.postProcessEnvironment(this.environment, this.application);
then(this.postProcessor).should().getConfigDataEnvironment(any(), this.resourceLoaderCaptor.capture(), any());
then(this.postProcessor).should().getConfigDataEnvironment(any(), any(ResourceLoader.class), any());
then(this.configDataEnvironment).should().processAndApply();
assertThat(this.environment.getActiveProfiles()).isEmpty();
}

@ -36,7 +36,6 @@ import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactory;
@ -51,6 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@ -89,9 +89,7 @@ class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFacto
TomcatContextCustomizer customizer = mock(TomcatContextCustomizer.class);
factory.addContextCustomizers(customizer);
this.webServer = factory.getWebServer(mock(HttpHandler.class));
ArgumentCaptor<Context> contextCaptor = ArgumentCaptor.forClass(Context.class);
then(customizer).should().customize(contextCaptor.capture());
assertThat(contextCaptor.getValue().getParent()).isNotNull();
then(customizer).should().customize(assertArg((context) -> assertThat(context.getParent()).isNotNull()));
}
@Test

@ -71,7 +71,6 @@ import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.springframework.boot.testsupport.system.CapturedOutput;
@ -97,6 +96,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.assertArg;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@ -184,9 +184,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory
TomcatContextCustomizer customizer = mock(TomcatContextCustomizer.class);
factory.addContextCustomizers(customizer);
this.webServer = factory.getWebServer();
ArgumentCaptor<Context> contextCaptor = ArgumentCaptor.forClass(Context.class);
then(customizer).should().customize(contextCaptor.capture());
assertThat(contextCaptor.getValue().getParent()).isNotNull();
then(customizer).should().customize(assertArg((context) -> assertThat(context.getParent()).isNotNull()));
}
@Test

Loading…
Cancel
Save