提交 798b51f4 编写于 作者: P Phillip Webb

Migrate to BDD Mockito

Migrate all tests to consistently use BDD Mockito. Also add
checksyle rule to enforce going forwards.
上级 816bbee8
......@@ -45,7 +45,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
......@@ -112,13 +111,13 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests properties population and autowire behavior.
......@@ -135,8 +134,6 @@ public class DefaultListableBeanFactoryTests {
private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
@Test
public void testUnreferencedSingletonWasInstantiated() {
KnowsIfInstantiated.clearInstantiationRecord();
......@@ -1240,8 +1237,8 @@ public class DefaultListableBeanFactoryTests {
public void testExpressionInStringArray() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class);
when(beanExpressionResolver.evaluate(eq("#{foo}"), ArgumentMatchers.any(BeanExpressionContext.class)))
.thenReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
given(beanExpressionResolver.evaluate(eq("#{foo}"), any(BeanExpressionContext.class)))
.willReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
bf.setBeanExpressionResolver(beanExpressionResolver);
RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class);
......
......@@ -33,8 +33,8 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ParameterResolutionDelegate}.
......@@ -128,7 +128,7 @@ public class ParameterResolutionTests {
AutowireCapableBeanFactory beanFactory = mock(AutowireCapableBeanFactory.class);
// Configure the mocked BeanFactory to return the DependencyDescriptor for convenience and
// to avoid using an ArgumentCaptor.
when(beanFactory.resolveDependency(any(), isNull())).thenAnswer(invocation -> invocation.getArgument(0));
given(beanFactory.resolveDependency(any(), isNull())).willAnswer(invocation -> invocation.getArgument(0));
Parameter[] parameters = constructor.getParameters();
for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) {
......
......@@ -36,12 +36,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Stephane Nicoll
......@@ -312,7 +312,7 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv
public void beanInstanceRetrievedAtEveryInvocation() {
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "handleGenericString", GenericTestEvent.class);
when(this.context.getBean("testBean")).thenReturn(this.sampleEvents);
given(this.context.getBean("testBean")).willReturn(this.sampleEvents);
ApplicationListenerMethodAdapter listener = new ApplicationListenerMethodAdapter(
"testBean", GenericTestEvent.class, method);
listener.init(this.context, new EventExpressionEvaluator());
......
......@@ -53,9 +53,9 @@ import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -94,14 +94,14 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
@Test
public void readByteChannelError() throws Exception {
ReadableByteChannel channel = mock(ReadableByteChannel.class);
when(channel.read(any()))
.thenAnswer(invocation -> {
given(channel.read(any()))
.willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
buffer.put("foo".getBytes(StandardCharsets.UTF_8));
buffer.flip();
return 3;
})
.thenThrow(new IOException());
.willThrow(new IOException());
Flux<DataBuffer> result =
DataBufferUtils.readByteChannel(() -> channel, this.bufferFactory, 3);
......@@ -151,7 +151,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
@Test
public void readAsynchronousFileChannelError() throws Exception {
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
doAnswer(invocation -> {
willAnswer(invocation -> {
ByteBuffer byteBuffer = invocation.getArgument(0);
byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
......@@ -161,13 +161,13 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3);
completionHandler.completed(3, dataBuffer);
return null;
}).doAnswer(invocation -> {
}).willAnswer(invocation -> {
DataBuffer dataBuffer = invocation.getArgument(2);
CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3);
completionHandler.failed(new IOException(), dataBuffer);
return null;
})
.when(channel).read(any(), anyLong(), any(), any());
.given(channel).read(any(), anyLong(), any(), any());
Flux<DataBuffer> result =
DataBufferUtils.readAsynchronousFileChannel(() -> channel, this.bufferFactory, 3);
......@@ -318,14 +318,14 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
Flux<DataBuffer> flux = Flux.just(foo, bar);
WritableByteChannel channel = mock(WritableByteChannel.class);
when(channel.write(any()))
.thenAnswer(invocation -> {
given(channel.write(any()))
.willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
int written = buffer.remaining();
buffer.position(buffer.limit());
return written;
})
.thenThrow(new IOException());
.willThrow(new IOException());
Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel);
StepVerifier.create(writeResult)
......@@ -420,7 +420,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
Flux<DataBuffer> flux = Flux.just(foo, bar);
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
doAnswer(invocation -> {
willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
long pos = invocation.getArgument(1);
CompletionHandler<Integer, ByteBuffer> completionHandler = invocation.getArgument(3);
......@@ -433,15 +433,14 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
return null;
})
.doAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
CompletionHandler<Integer, ByteBuffer> completionHandler =
invocation.getArgument(3);
completionHandler.failed(new IOException(), buffer);
return null;
})
.when(channel).write(isA(ByteBuffer.class), anyLong(), isA(ByteBuffer.class),
isA(CompletionHandler.class));
.willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
CompletionHandler<Integer, ByteBuffer> completionHandler =
invocation.getArgument(3);
completionHandler.failed(new IOException(), buffer);
return null;
})
.given(channel).write(isA(ByteBuffer.class), anyLong(), isA(ByteBuffer.class), isA(CompletionHandler.class));
Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel);
StepVerifier.create(writeResult)
......@@ -684,11 +683,11 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
@Test
public void SPR16070() throws Exception {
ReadableByteChannel channel = mock(ReadableByteChannel.class);
when(channel.read(any()))
.thenAnswer(putByte('a'))
.thenAnswer(putByte('b'))
.thenAnswer(putByte('c'))
.thenReturn(-1);
given(channel.read(any()))
.willAnswer(putByte('a'))
.willAnswer(putByte('b'))
.willAnswer(putByte('c'))
.willReturn(-1);
Flux<DataBuffer> read =
DataBufferUtils.readByteChannel(() -> channel, this.bufferFactory, 1);
......
......@@ -55,7 +55,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Stephane Nicoll
......@@ -149,7 +148,7 @@ public class MessagingMessageListenerAdapterTests {
@Test
public void headerConversionLazilyInvoked() throws JMSException {
javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
when(jmsMessage.getPropertyNames()).thenThrow(new IllegalArgumentException("Header failure"));
given(jmsMessage.getPropertyNames()).willThrow(new IllegalArgumentException("Header failure"));
MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
Message<?> message = listener.toMessagingMessage(jmsMessage);
......
......@@ -47,7 +47,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
......@@ -80,10 +80,10 @@ public class GenericMessagingTemplateTests {
public void sendWithTimeout() {
SubscribableChannel channel = mock(SubscribableChannel.class);
final AtomicReference<Message<?>> sent = new AtomicReference<>();
doAnswer(invocation -> {
willAnswer(invocation -> {
sent.set(invocation.getArgument(0));
return true;
}).when(channel).send(any(Message.class), eq(30_000L));
}).given(channel).send(any(Message.class), eq(30_000L));
Message<?> message = MessageBuilder.withPayload("request")
.setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L)
.setHeader(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER, 1L)
......@@ -99,10 +99,10 @@ public class GenericMessagingTemplateTests {
public void sendWithTimeoutMutable() {
SubscribableChannel channel = mock(SubscribableChannel.class);
final AtomicReference<Message<?>> sent = new AtomicReference<>();
doAnswer(invocation -> {
willAnswer(invocation -> {
sent.set(invocation.getArgument(0));
return true;
}).when(channel).send(any(Message.class), eq(30_000L));
}).given(channel).send(any(Message.class), eq(30_000L));
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setLeaveMutable(true);
Message<?> message = new GenericMessage<>("request", accessor.getMessageHeaders());
......@@ -140,10 +140,10 @@ public class GenericMessagingTemplateTests {
SubscribableChannel channel = mock(SubscribableChannel.class);
MessageHandler handler = createLateReplier(latch, failure);
doAnswer(invocation -> {
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).when(channel).send(any(Message.class), anyLong());
}).given(channel).send(any(Message.class), anyLong());
assertNull(this.template.convertSendAndReceive(channel, "request", String.class));
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
......@@ -166,10 +166,10 @@ public class GenericMessagingTemplateTests {
SubscribableChannel channel = mock(SubscribableChannel.class);
MessageHandler handler = createLateReplier(latch, failure);
doAnswer(invocation -> {
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).when(channel).send(any(Message.class), anyLong());
}).given(channel).send(any(Message.class), anyLong());
Message<?> message = MessageBuilder.withPayload("request")
.setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L)
......@@ -198,10 +198,10 @@ public class GenericMessagingTemplateTests {
SubscribableChannel channel = mock(SubscribableChannel.class);
MessageHandler handler = createLateReplier(latch, failure);
doAnswer(invocation -> {
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).when(channel).send(any(Message.class), anyLong());
}).given(channel).send(any(Message.class), anyLong());
Message<?> message = MessageBuilder.withPayload("request")
.setHeader("sto", 30_000L)
......
......@@ -36,8 +36,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link MessageMethodArgumentResolver}.
......@@ -96,7 +96,7 @@ public class MessageMethodArgumentResolverTests {
Message<String> message = MessageBuilder.withPayload("test").build();
MethodParameter parameter = new MethodParameter(this.method, 1);
when(this.converter.fromMessage(message, Integer.class)).thenReturn(4);
given(this.converter.fromMessage(message, Integer.class)).willReturn(4);
@SuppressWarnings("unchecked")
Message<Integer> actual = (Message<Integer>) this.resolver.resolveArgument(parameter, message);
......
......@@ -30,10 +30,10 @@ import reactor.core.publisher.Mono;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultRSocketRequesterBuilder}.
......@@ -48,7 +48,7 @@ public class DefaultRSocketRequesterBuilderTests {
@Before
public void setup() {
this.transport = mock(ClientTransport.class);
when(this.transport.connect(anyInt())).thenReturn(Mono.just(new MockConnection()));
given(this.transport.connect(anyInt())).willReturn(Mono.just(new MockConnection()));
}
......
......@@ -46,13 +46,13 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link SimpleBrokerMessageHandler}.
......@@ -186,7 +186,7 @@ public class SimpleBrokerMessageHandlerTests {
@Test
public void startAndStopWithHeartbeatValue() {
ScheduledFuture future = mock(ScheduledFuture.class);
when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).thenReturn(future);
given(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).willReturn(future);
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.setHeartbeatValue(new long[] {15000, 16000});
......
......@@ -56,11 +56,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultStompSession}.
......@@ -94,7 +94,7 @@ public class DefaultStompSessionTests {
SettableListenableFuture<Void> future = new SettableListenableFuture<>();
future.set(null);
when(this.connection.send(this.messageCaptor.capture())).thenReturn(future);
given(this.connection.send(this.messageCaptor.capture())).willReturn(future);
}
......@@ -236,7 +236,7 @@ public class DefaultStompSessionTests {
String payload = "Oops";
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
given(this.sessionHandler.getPayloadType(stompHeaders)).willReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(
payload.getBytes(StandardCharsets.UTF_8), accessor.getMessageHeaders()));
......@@ -267,7 +267,7 @@ public class DefaultStompSessionTests {
byte[] payload = "{'foo':'bar'}".getBytes(StandardCharsets.UTF_8);
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(Map.class);
given(this.sessionHandler.getPayloadType(stompHeaders)).willReturn(Map.class);
this.session.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
......@@ -294,7 +294,7 @@ public class DefaultStompSessionTests {
String payload = "sample payload";
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(frameHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
given(frameHandler.getPayloadType(stompHeaders)).willReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8),
accessor.getMessageHeaders()));
......@@ -322,7 +322,7 @@ public class DefaultStompSessionTests {
byte[] payload = "{'foo':'bar'}".getBytes(StandardCharsets.UTF_8);
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(frameHandler.getPayloadType(stompHeaders)).thenReturn(Map.class);
given(frameHandler.getPayloadType(stompHeaders)).willReturn(Map.class);
this.session.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
......@@ -419,7 +419,7 @@ public class DefaultStompSessionTests {
SettableListenableFuture<Void> future = new SettableListenableFuture<>();
future.setException(exception);
when(this.connection.send(any())).thenReturn(future);
given(this.connection.send(any())).willReturn(future);
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() ->
this.session.send("/topic/foo", "sample payload".getBytes(StandardCharsets.UTF_8)))
.withCause(exception);
......@@ -609,7 +609,7 @@ public class DefaultStompSessionTests {
AtomicReference<Boolean> notReceived = new AtomicReference<>();
ScheduledFuture future = mock(ScheduledFuture.class);
when(taskScheduler.schedule(any(Runnable.class), any(Date.class))).thenReturn(future);
given(taskScheduler.schedule(any(Runnable.class), any(Date.class))).willReturn(future);
StompHeaders headers = new StompHeaders();
headers.setDestination("/topic/foo");
......
......@@ -30,8 +30,8 @@ import org.springframework.util.StringUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for
......@@ -52,7 +52,7 @@ public class DefaultUserDestinationResolverTests {
simpUser.addSessions(new TestSimpSession("123"));
this.registry = mock(SimpUserRegistry.class);
when(this.registry.getUser("joe")).thenReturn(simpUser);
given(this.registry.getUser("joe")).willReturn(simpUser);
this.resolver = new DefaultUserDestinationResolver(this.registry);
}
......@@ -91,7 +91,7 @@ public class DefaultUserDestinationResolverTests {
TestSimpUser simpUser = new TestSimpUser("joe");
simpUser.addSessions(new TestSimpSession("123"), new TestSimpSession("456"));
when(this.registry.getUser("joe")).thenReturn(simpUser);
given(this.registry.getUser("joe")).willReturn(simpUser);
TestPrincipal user = new TestPrincipal("joe");
Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, user, "456", "/user/queue/foo");
......@@ -157,7 +157,7 @@ public class DefaultUserDestinationResolverTests {
TestSimpUser otherSimpUser = new TestSimpUser("anna");
otherSimpUser.addSessions(new TestSimpSession("456"));
when(this.registry.getUser("anna")).thenReturn(otherSimpUser);
given(this.registry.getUser("anna")).willReturn(otherSimpUser);
TestPrincipal user = new TestPrincipal("joe");
TestPrincipal otherUser = new TestPrincipal("anna");
......@@ -179,7 +179,7 @@ public class DefaultUserDestinationResolverTests {
TestSimpUser simpUser = new TestSimpUser(userName);
simpUser.addSessions(new TestSimpSession("openid123"));
when(this.registry.getUser(userName)).thenReturn(simpUser);
given(this.registry.getUser(userName)).willReturn(simpUser);
String destination = "/user/" + StringUtils.replace(userName, "/", "%2F") + "/queue/foo";
......
......@@ -36,8 +36,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link MultiServerUserRegistry}.
......@@ -65,9 +65,9 @@ public class MultiServerUserRegistryTests {
public void getUserFromLocalRegistry() throws Exception {
SimpUser user = Mockito.mock(SimpUser.class);
Set<SimpUser> users = Collections.singleton(user);
when(this.localRegistry.getUsers()).thenReturn(users);
when(this.localRegistry.getUserCount()).thenReturn(1);
when(this.localRegistry.getUser("joe")).thenReturn(user);
given(this.localRegistry.getUsers()).willReturn(users);
given(this.localRegistry.getUserCount()).willReturn(1);
given(this.localRegistry.getUser("joe")).willReturn(user);
assertEquals(1, this.registry.getUserCount());
assertSame(user, this.registry.getUser("joe"));
......@@ -81,7 +81,7 @@ public class MultiServerUserRegistryTests {
testSession.addSubscriptions(new TestSimpSubscription("remote-sub", "/remote-dest"));
testUser.addSessions(testSession);
SimpUserRegistry testRegistry = mock(SimpUserRegistry.class);
when(testRegistry.getUsers()).thenReturn(Collections.singleton(testUser));
given(testRegistry.getUsers()).willReturn(Collections.singleton(testUser));
Object registryDto = new MultiServerUserRegistry(testRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
......@@ -120,7 +120,7 @@ public class MultiServerUserRegistryTests {
user2.addSessions(session2);
user3.addSessions(session3);
SimpUserRegistry userRegistry = mock(SimpUserRegistry.class);
when(userRegistry.getUsers()).thenReturn(new HashSet<>(Arrays.asList(user1, user2, user3)));
given(userRegistry.getUsers()).willReturn(new HashSet<>(Arrays.asList(user1, user2, user3)));
Object registryDto = new MultiServerUserRegistry(userRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
......@@ -143,14 +143,14 @@ public class MultiServerUserRegistryTests {
TestSimpUser localUser = new TestSimpUser("joe");
TestSimpSession localSession = new TestSimpSession("sess123");
localUser.addSessions(localSession);
when(this.localRegistry.getUser("joe")).thenReturn(localUser);
given(this.localRegistry.getUser("joe")).willReturn(localUser);
// Prepare broadcast message from remote server
TestSimpUser remoteUser = new TestSimpUser("joe");
TestSimpSession remoteSession = new TestSimpSession("sess456");
remoteUser.addSessions(remoteSession);
SimpUserRegistry remoteRegistry = mock(SimpUserRegistry.class);
when(remoteRegistry.getUsers()).thenReturn(Collections.singleton(remoteUser));
given(remoteRegistry.getUsers()).willReturn(Collections.singleton(remoteUser));
Object remoteRegistryDto = new MultiServerUserRegistry(remoteRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(remoteRegistryDto, null);
......@@ -179,7 +179,7 @@ public class MultiServerUserRegistryTests {
TestSimpUser testUser = new TestSimpUser("joe");
testUser.addSessions(new TestSimpSession("remote-sub"));
SimpUserRegistry testRegistry = mock(SimpUserRegistry.class);
when(testRegistry.getUsers()).thenReturn(Collections.singleton(testUser));
given(testRegistry.getUsers()).willReturn(Collections.singleton(testUser));
Object registryDto = new MultiServerUserRegistry(testRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
......
......@@ -39,7 +39,6 @@ import static org.junit.Assert.assertNotNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.ORIGINAL_DESTINATION;
/**
......@@ -94,7 +93,7 @@ public class UserDestinationMessageHandlerTests {
public void handleMessage() {
TestSimpUser simpUser = new TestSimpUser("joe");
simpUser.addSessions(new TestSimpSession("123"));
when(this.registry.getUser("joe")).thenReturn(simpUser);
given(this.registry.getUser("joe")).willReturn(simpUser);
given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
this.handler.handleMessage(createWith(SimpMessageType.MESSAGE, "joe", "123", "/user/joe/queue/foo"));
......@@ -130,7 +129,7 @@ public class UserDestinationMessageHandlerTests {
public void handleMessageFromBrokerWithActiveSession() {
TestSimpUser simpUser = new TestSimpUser("joe");
simpUser.addSessions(new TestSimpSession("123"));
when(this.registry.getUser("joe")).thenReturn(simpUser);
given(this.registry.getUser("joe")).willReturn(simpUser);
this.handler.setBroadcastDestination("/topic/unresolved");
given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
......
......@@ -42,10 +42,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* User tests for {@link UserRegistryMessageHandler}.
......@@ -73,7 +73,7 @@ public class UserRegistryMessageHandlerTests {
MockitoAnnotations.initMocks(this);
when(this.brokerChannel.send(any())).thenReturn(true);
given(this.brokerChannel.send(any())).willReturn(true);
this.converter = new MappingJackson2MessageConverter();
SimpMessagingTemplate brokerTemplate = new SimpMessagingTemplate(this.brokerChannel);
......@@ -97,7 +97,7 @@ public class UserRegistryMessageHandlerTests {
public void brokerUnavailableEvent() throws Exception {
ScheduledFuture future = Mockito.mock(ScheduledFuture.class);
when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), any(Long.class))).thenReturn(future);
given(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), any(Long.class))).willReturn(future);
BrokerAvailabilityEvent event = new BrokerAvailabilityEvent(true, this);
this.handler.onApplicationEvent(event);
......@@ -118,7 +118,7 @@ public class UserRegistryMessageHandlerTests {
simpUser1.addSessions(new TestSimpSession("456"));
HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2));
when(this.localRegistry.getUsers()).thenReturn(simpUsers);
given(this.localRegistry.getUsers()).willReturn(simpUsers);
getUserRegistryTask().run();
......@@ -148,8 +148,8 @@ public class UserRegistryMessageHandlerTests {
HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2));
SimpUserRegistry remoteUserRegistry = mock(SimpUserRegistry.class);
when(remoteUserRegistry.getUserCount()).thenReturn(2);
when(remoteUserRegistry.getUsers()).thenReturn(simpUsers);
given(remoteUserRegistry.getUserCount()).willReturn(2);
given(remoteUserRegistry.getUsers()).willReturn(simpUsers);
MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(remoteUserRegistry);
Message<?> message = this.converter.toMessage(remoteRegistry.getLocalRegistryDto(), null);
......@@ -166,8 +166,8 @@ public class UserRegistryMessageHandlerTests {
TestSimpUser simpUser = new TestSimpUser("joe");
simpUser.addSessions(new TestSimpSession("123"));
when(this.localRegistry.getUserCount()).thenReturn(1);
when(this.localRegistry.getUsers()).thenReturn(Collections.singleton(simpUser));
given(this.localRegistry.getUserCount()).willReturn(1);
given(this.localRegistry.getUsers()).willReturn(Collections.singleton(simpUser));
assertEquals(1, this.multiServerRegistry.getUserCount());
......
......@@ -37,11 +37,11 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willCallRealMethod;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link EventPublishingTestExecutionListener}.
......@@ -71,10 +71,10 @@ public class EventPublishingTestExecutionListenerTests {
@Before
public void configureMock() {
// Force Mockito to invoke the interface default method
doCallRealMethod().when(testContext).publishEvent(any());
when(testContext.getApplicationContext()).thenReturn(applicationContext);
willCallRealMethod().given(testContext).publishEvent(any());
given(testContext.getApplicationContext()).willReturn(applicationContext);
// Only allow events to be published for test methods named "publish*".
when(testContext.hasApplicationContext()).thenReturn(testName.getMethodName().startsWith("publish"));
given(testContext.hasApplicationContext()).willReturn(testName.getMethodName().startsWith("publish"));
}
@Test
......
......@@ -41,8 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link DisabledIfCondition} that verify actual condition evaluation
......@@ -124,12 +124,12 @@ class DisabledIfConditionTests {
Class<?> testClass = SpringTestCase.class;
Method method = ReflectionUtils.findMethod(getClass(), methodName);
Store store = mock(Store.class);
when(store.getOrComputeIfAbsent(any(), any(), any())).thenReturn(new TestContextManager(testClass));
given(store.getOrComputeIfAbsent(any(), any(), any())).willReturn(new TestContextManager(testClass));
ExtensionContext extensionContext = mock(ExtensionContext.class);
when(extensionContext.getTestClass()).thenReturn(Optional.of(testClass));
when(extensionContext.getElement()).thenReturn(Optional.of(method));
when(extensionContext.getStore(any())).thenReturn(store);
given(extensionContext.getTestClass()).willReturn(Optional.of(testClass));
given(extensionContext.getElement()).willReturn(Optional.of(method));
given(extensionContext.getStore(any())).willReturn(store);
return extensionContext;
}
......
......@@ -25,8 +25,8 @@ import org.mockito.stubbing.Answer;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
/**
......@@ -55,7 +55,7 @@ public class SpringFailOnTimeoutTests {
@Test
public void userExceptionPropagates() throws Throwable {
doThrow(new Boom()).when(statement).evaluate();
willThrow(new Boom()).given(statement).evaluate();
assertThatExceptionOfType(Boom.class).isThrownBy(() ->
new SpringFailOnTimeout(statement, 1).evaluate());
......@@ -63,10 +63,10 @@ public class SpringFailOnTimeoutTests {
@Test
public void timeoutExceptionThrownIfNoUserException() throws Throwable {
doAnswer((Answer<Void>) invocation -> {
willAnswer((Answer<Void>) invocation -> {
TimeUnit.MILLISECONDS.sleep(50);
return null;
}).when(statement).evaluate();
}).given(statement).evaluate();
assertThatExceptionOfType(TimeoutException.class).isThrownBy(() ->
new SpringFailOnTimeout(statement, 1).evaluate());
......@@ -74,7 +74,7 @@ public class SpringFailOnTimeoutTests {
@Test
public void noExceptionThrownIfNoUserExceptionAndTimeoutDoesNotOccur() throws Throwable {
doAnswer((Answer<Void>) invocation -> null).when(statement).evaluate();
willAnswer((Answer<Void>) invocation -> null).given(statement).evaluate();
new SpringFailOnTimeout(statement, 100).evaluate();
}
......
......@@ -37,8 +37,8 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.context.support.TestPropertySourceUtils.addInlinedPropertiesToEnvironment;
import static org.springframework.test.context.support.TestPropertySourceUtils.addPropertiesFilesToEnvironment;
import static org.springframework.test.context.support.TestPropertySourceUtils.buildMergedTestPropertySources;
......@@ -165,7 +165,7 @@ public class TestPropertySourceUtilsTests {
String pair = "key = value";
ByteArrayResource resource = new ByteArrayResource(pair.getBytes(), "from inlined property: " + pair);
ResourceLoader resourceLoader = mock(ResourceLoader.class);
when(resourceLoader.getResource(anyString())).thenReturn(resource);
given(resourceLoader.getResource(anyString())).willReturn(resource);
addPropertiesFilesToEnvironment(environment, resourceLoader, FOO_LOCATIONS);
assertEquals(1, propertySources.size());
......
......@@ -44,9 +44,9 @@ import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.core.IsNot.not;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Unit and integration tests for {@link DelegatingWebConnection}.
......@@ -92,7 +92,7 @@ public class DelegatingWebConnectionTests {
@Test
public void getResponseDefault() throws Exception {
when(defaultConnection.getResponse(request)).thenReturn(expectedResponse);
given(defaultConnection.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
......@@ -104,8 +104,8 @@ public class DelegatingWebConnectionTests {
@Test
public void getResponseAllMatches() throws Exception {
when(matcher1.matches(request)).thenReturn(true);
when(connection1.getResponse(request)).thenReturn(expectedResponse);
given(matcher1.matches(request)).willReturn(true);
given(connection1.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
......@@ -116,8 +116,8 @@ public class DelegatingWebConnectionTests {
@Test
public void getResponseSecondMatches() throws Exception {
when(matcher2.matches(request)).thenReturn(true);
when(connection2.getResponse(request)).thenReturn(expectedResponse);
given(matcher2.matches(request)).willReturn(true);
given(connection2.getResponse(request)).willReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
......
......@@ -44,8 +44,8 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Integration tests for {@link MockMvcWebConnectionBuilderSupport}.
......@@ -70,7 +70,7 @@ public class MockMvcConnectionBuilderSupportTests {
@Before
public void setup() {
when(this.client.getWebConnection()).thenReturn(mock(WebConnection.class));
given(this.client.getWebConnection()).willReturn(mock(WebConnection.class));
this.builder = new MockMvcWebConnectionBuilderSupport(this.wac) {};
}
......
......@@ -33,7 +33,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* Unit tests for {@link WebConnectionHtmlUnitDriver}.
......@@ -52,7 +52,7 @@ public class WebConnectionHtmlUnitDriverTests {
@Before
public void setup() throws Exception {
when(this.connection.getResponse(any(WebRequest.class))).thenThrow(new IOException(""));
given(this.connection.getResponse(any(WebRequest.class))).willThrow(new IOException(""));
}
......
......@@ -34,11 +34,11 @@ import org.springframework.transaction.reactive.TransactionContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Abstract support class to test {@link TransactionAspectSupport} with reactive methods.
......@@ -96,8 +96,8 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransaction status = mock(ReactiveTransaction.class);
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
// expect a transaction
when(rtm.getReactiveTransaction(txatt)).thenReturn(Mono.just(status));
when(rtm.commit(status)).thenReturn(Mono.empty());
given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status));
given(rtm.commit(status)).willReturn(Mono.empty());
DefaultTestBean tb = new DefaultTestBean();
TestBean itb = (TestBean) advised(tb, rtm, tas);
......@@ -124,8 +124,8 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransaction status = mock(ReactiveTransaction.class);
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
// expect a transaction
when(rtm.getReactiveTransaction(txatt)).thenReturn(Mono.just(status));
when(rtm.commit(status)).thenReturn(Mono.empty());
given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status));
given(rtm.commit(status)).willReturn(Mono.empty());
DefaultTestBean tb = new DefaultTestBean();
TestBean itb = (TestBean) advised(tb, rtm, new TransactionAttributeSource[] {tas1, tas2});
......@@ -154,8 +154,8 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransaction status = mock(ReactiveTransaction.class);
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
// expect a transaction
when(rtm.getReactiveTransaction(txatt)).thenReturn(Mono.just(status));
when(rtm.commit(status)).thenReturn(Mono.empty());
given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status));
given(rtm.commit(status)).willReturn(Mono.empty());
DefaultTestBean tb = new DefaultTestBean();
TestBean itb = (TestBean) advised(tb, rtm, tas);
......@@ -234,20 +234,20 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
// Gets additional call(s) from TransactionControl
when(rtm.getReactiveTransaction(txatt)).thenReturn(Mono.just(status));
given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status));
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException) {
if (shouldRollback) {
when(rtm.rollback(status)).thenReturn(Mono.error(tex));
given(rtm.rollback(status)).willReturn(Mono.error(tex));
}
else {
when(rtm.commit(status)).thenReturn(Mono.error(tex));
given(rtm.commit(status)).willReturn(Mono.error(tex));
}
}
else {
when(rtm.commit(status)).thenReturn(Mono.empty());
when(rtm.rollback(status)).thenReturn(Mono.empty());
given(rtm.commit(status)).willReturn(Mono.empty());
given(rtm.rollback(status)).willReturn(Mono.empty());
}
DefaultTestBean tb = new DefaultTestBean();
......@@ -289,7 +289,7 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
// Expect a transaction
CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
when(rtm.getReactiveTransaction(txatt)).thenThrow(ex);
given(rtm.getReactiveTransaction(txatt)).willThrow(ex);
DefaultTestBean tb = new DefaultTestBean() {
@Override
......@@ -324,10 +324,10 @@ public abstract class AbstractReactiveTransactionAspectTests {
ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
ReactiveTransaction status = mock(ReactiveTransaction.class);
when(rtm.getReactiveTransaction(txatt)).thenReturn(Mono.just(status));
given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status));
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
when(rtm.commit(status)).thenReturn(Mono.error(ex));
when(rtm.rollback(status)).thenReturn(Mono.empty());
given(rtm.commit(status)).willReturn(Mono.error(ex));
given(rtm.rollback(status)).willReturn(Mono.empty());
DefaultTestBean tb = new DefaultTestBean();
TestBean itb = (TestBean) advised(tb, rtm, tas);
......
......@@ -34,8 +34,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
/**
......@@ -83,7 +83,7 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq
CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(client);
assertSame("Default client configuration is expected", defaultConfig, retrieveRequestConfig(hrf));
......@@ -103,7 +103,7 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq
CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(client);
hrf.setConnectTimeout(5000);
......@@ -121,7 +121,7 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq
final CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory() {
@Override
......@@ -139,7 +139,7 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq
// Update the Http client so that it returns an updated config
RequestConfig updatedDefaultConfig = RequestConfig.custom()
.setConnectTimeout(1234).build();
when(configurable.getConfig()).thenReturn(updatedDefaultConfig);
given(configurable.getConfig()).willReturn(updatedDefaultConfig);
hrf.setReadTimeout(7000);
RequestConfig requestConfig2 = retrieveRequestConfig(hrf);
assertEquals(1234, requestConfig2.getConnectTimeout());
......
......@@ -31,7 +31,7 @@ import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.mockito.BDDMockito.willDoNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
......@@ -100,7 +100,7 @@ public class SimpleClientHttpResponseTests {
public void shouldNotDrainWhenErrorStreamClosed() throws Exception {
InputStream is = mock(InputStream.class);
given(this.connection.getErrorStream()).willReturn(is);
doNothing().when(is).close();
willDoNothing().given(is).close();
given(is.read(any())).willThrow(new NullPointerException("from HttpURLConnection#ErrorStream"));
InputStream responseStream = this.response.getBody();
......
......@@ -45,7 +45,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
import static org.springframework.core.ResolvableType.forClass;
import static org.springframework.http.MediaType.TEXT_HTML;
import static org.springframework.http.MediaType.TEXT_PLAIN;
......@@ -88,7 +88,7 @@ public class EncoderHttpMessageWriterTests {
@Test
public void canWrite() {
HttpMessageWriter<?> writer = getWriter(MimeTypeUtils.TEXT_HTML);
when(this.encoder.canEncode(forClass(String.class), TEXT_HTML)).thenReturn(true);
given(this.encoder.canEncode(forClass(String.class), TEXT_HTML)).willReturn(true);
assertTrue(writer.canWrite(forClass(String.class), TEXT_HTML));
assertFalse(writer.canWrite(forClass(String.class), TEXT_XML));
......@@ -184,8 +184,8 @@ public class EncoderHttpMessageWriterTests {
private HttpMessageWriter<String> getWriter(Flux<DataBuffer> encodedStream, MimeType... mimeTypes) {
List<MimeType> typeList = Arrays.asList(mimeTypes);
when(this.encoder.getEncodableMimeTypes()).thenReturn(typeList);
when(this.encoder.encode(any(), any(), any(), this.mediaTypeCaptor.capture(), any())).thenReturn(encodedStream);
given(this.encoder.getEncodableMimeTypes()).willReturn(typeList);
given(this.encoder.encode(any(), any(), any(), this.mediaTypeCaptor.capture(), any())).willReturn(encodedStream);
return new EncoderHttpMessageWriter<>(this.encoder);
}
......
......@@ -48,8 +48,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Sebastien Deleuze
......@@ -97,7 +97,7 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas
this.bufferFactory.wrap("Cc".getBytes(StandardCharsets.UTF_8))
);
Part mockPart = mock(Part.class);
when(mockPart.content()).thenReturn(bufferPublisher);
given(mockPart.content()).willReturn(bufferPublisher);
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
bodyBuilder.part("name 1", "value 1");
......
......@@ -56,8 +56,8 @@ import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link BaseDefaultCodecs}.
......@@ -110,14 +110,14 @@ public class CodecConfigurerTests {
Decoder<?> customDecoder1 = mock(Decoder.class);
Decoder<?> customDecoder2 = mock(Decoder.class);
when(customDecoder1.canDecode(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customDecoder2.canDecode(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customDecoder1.canDecode(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customDecoder2.canDecode(ResolvableType.forClass(Object.class), null)).willReturn(true);
HttpMessageReader<?> customReader1 = mock(HttpMessageReader.class);
HttpMessageReader<?> customReader2 = mock(HttpMessageReader.class);
when(customReader1.canRead(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customReader2.canRead(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customReader1.canRead(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customReader2.canRead(ResolvableType.forClass(Object.class), null)).willReturn(true);
this.configurer.customCodecs().decoder(customDecoder1);
this.configurer.customCodecs().decoder(customDecoder2);
......@@ -150,14 +150,14 @@ public class CodecConfigurerTests {
Encoder<?> customEncoder1 = mock(Encoder.class);
Encoder<?> customEncoder2 = mock(Encoder.class);
when(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(true);
HttpMessageWriter<?> customWriter1 = mock(HttpMessageWriter.class);
HttpMessageWriter<?> customWriter2 = mock(HttpMessageWriter.class);
when(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(true);
this.configurer.customCodecs().encoder(customEncoder1);
this.configurer.customCodecs().encoder(customEncoder2);
......@@ -189,14 +189,14 @@ public class CodecConfigurerTests {
Decoder<?> customDecoder1 = mock(Decoder.class);
Decoder<?> customDecoder2 = mock(Decoder.class);
when(customDecoder1.canDecode(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customDecoder2.canDecode(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customDecoder1.canDecode(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customDecoder2.canDecode(ResolvableType.forClass(Object.class), null)).willReturn(true);
HttpMessageReader<?> customReader1 = mock(HttpMessageReader.class);
HttpMessageReader<?> customReader2 = mock(HttpMessageReader.class);
when(customReader1.canRead(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customReader2.canRead(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customReader1.canRead(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customReader2.canRead(ResolvableType.forClass(Object.class), null)).willReturn(true);
this.configurer.customCodecs().decoder(customDecoder1);
this.configurer.customCodecs().decoder(customDecoder2);
......@@ -220,14 +220,14 @@ public class CodecConfigurerTests {
Encoder<?> customEncoder1 = mock(Encoder.class);
Encoder<?> customEncoder2 = mock(Encoder.class);
when(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(true);
HttpMessageWriter<?> customWriter1 = mock(HttpMessageWriter.class);
HttpMessageWriter<?> customWriter2 = mock(HttpMessageWriter.class);
when(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(false);
when(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(true);
given(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(false);
given(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(true);
this.configurer.customCodecs().encoder(customEncoder1);
this.configurer.customCodecs().encoder(customEncoder2);
......
......@@ -41,7 +41,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
/**
......@@ -141,7 +141,7 @@ public class ResourceHttpMessageConverterTests {
InputStream inputStream = mock(InputStream.class);
given(resource.getInputStream()).willReturn(inputStream);
given(inputStream.read(any())).willReturn(-1);
doThrow(new NullPointerException()).when(inputStream).close();
willThrow(new NullPointerException()).given(inputStream).close();
converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage);
assertEquals(0, outputMessage.getHeaders().getContentLength());
......
......@@ -30,8 +30,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
/**
......@@ -75,7 +75,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests {
CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsHttpInvokerRequestExecutor executor =
new HttpComponentsHttpInvokerRequestExecutor(client);
......@@ -98,7 +98,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests {
CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsHttpInvokerRequestExecutor executor =
new HttpComponentsHttpInvokerRequestExecutor(client);
......@@ -119,7 +119,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests {
final CloseableHttpClient client = mock(CloseableHttpClient.class,
withSettings().extraInterfaces(Configurable.class));
Configurable configurable = (Configurable) client;
when(configurable.getConfig()).thenReturn(defaultConfig);
given(configurable.getConfig()).willReturn(defaultConfig);
HttpComponentsHttpInvokerRequestExecutor executor =
new HttpComponentsHttpInvokerRequestExecutor() {
......@@ -139,7 +139,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests {
// Update the Http client so that it returns an updated config
RequestConfig updatedDefaultConfig = RequestConfig.custom()
.setConnectTimeout(1234).build();
when(configurable.getConfig()).thenReturn(updatedDefaultConfig);
given(configurable.getConfig()).willReturn(updatedDefaultConfig);
executor.setReadTimeout(7000);
HttpPost httpPost2 = executor.createHttpPost(config);
RequestConfig requestConfig2 = httpPost2.getConfig();
......@@ -165,7 +165,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests {
private HttpInvokerClientConfiguration mockHttpInvokerClientConfiguration(String serviceUrl) {
HttpInvokerClientConfiguration config = mock(HttpInvokerClientConfiguration.class);
when(config.getServiceUrl()).thenReturn(serviceUrl);
given(config.getServiceUrl()).willReturn(serviceUrl);
return config;
}
......
......@@ -36,7 +36,6 @@ import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.web.context.request.async.CallableProcessingInterceptor.RESULT_NONE;
/**
......@@ -163,7 +162,7 @@ public class WebAsyncManagerTimeoutTests {
Future future = mock(Future.class);
AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
when(executor.submit(any(Runnable.class))).thenReturn(future);
given(executor.submit(any(Runnable.class))).willReturn(future);
this.asyncManager.setTaskExecutor(executor);
this.asyncManager.startCallableProcessing(callable);
......
......@@ -23,10 +23,10 @@ import org.springframework.core.MethodParameter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Test fixture with {@link HandlerMethodReturnValueHandlerComposite}.
......@@ -53,7 +53,7 @@ public class HandlerMethodReturnValueHandlerCompositeTests {
this.stringType = new MethodParameter(getClass().getDeclaredMethod("handleString"), -1);
this.integerHandler = mock(HandlerMethodReturnValueHandler.class);
when(this.integerHandler.supportsReturnType(this.integerType)).thenReturn(true);
given(this.integerHandler.supportsReturnType(this.integerType)).willReturn(true);
this.handlers = new HandlerMethodReturnValueHandlerComposite();
this.handlers.addHandler(this.integerHandler);
......@@ -76,7 +76,7 @@ public class HandlerMethodReturnValueHandlerCompositeTests {
@Test
public void handleReturnValueWithMultipleHandlers() throws Exception {
HandlerMethodReturnValueHandler anotherIntegerHandler = mock(HandlerMethodReturnValueHandler.class);
when(anotherIntegerHandler.supportsReturnType(this.integerType)).thenReturn(true);
given(anotherIntegerHandler.supportsReturnType(this.integerType)).willReturn(true);
this.handlers.handleReturnValue(55, this.integerType, this.mavContainer, null);
......@@ -91,12 +91,12 @@ public class HandlerMethodReturnValueHandlerCompositeTests {
MethodParameter promiseType = new MethodParameter(getClass().getDeclaredMethod("handlePromise"), -1);
HandlerMethodReturnValueHandler responseBodyHandler = mock(HandlerMethodReturnValueHandler.class);
when(responseBodyHandler.supportsReturnType(promiseType)).thenReturn(true);
given(responseBodyHandler.supportsReturnType(promiseType)).willReturn(true);
this.handlers.addHandler(responseBodyHandler);
AsyncHandlerMethodReturnValueHandler promiseHandler = mock(AsyncHandlerMethodReturnValueHandler.class);
when(promiseHandler.supportsReturnType(promiseType)).thenReturn(true);
when(promiseHandler.isAsyncReturnValue(promise, promiseType)).thenReturn(true);
given(promiseHandler.supportsReturnType(promiseType)).willReturn(true);
given(promiseHandler.isAsyncReturnValue(promise, promiseType)).willReturn(true);
this.handlers.addHandler(promiseHandler);
this.handlers.handleReturnValue(promise, promiseType, this.mavContainer, null);
......
......@@ -40,9 +40,9 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultWebSessionManager}.
......@@ -72,12 +72,12 @@ public class DefaultWebSessionManagerTests {
@Before
public void setUp() throws Exception {
when(this.createSession.save()).thenReturn(Mono.empty());
when(this.createSession.getId()).thenReturn("create-session-id");
when(this.updateSession.getId()).thenReturn("update-session-id");
given(this.createSession.save()).willReturn(Mono.empty());
given(this.createSession.getId()).willReturn("create-session-id");
given(this.updateSession.getId()).willReturn("update-session-id");
when(this.sessionStore.createWebSession()).thenReturn(Mono.just(this.createSession));
when(this.sessionStore.retrieveSession(this.updateSession.getId())).thenReturn(Mono.just(this.updateSession));
given(this.sessionStore.createWebSession()).willReturn(Mono.just(this.createSession));
given(this.sessionStore.retrieveSession(this.updateSession.getId())).willReturn(Mono.just(this.updateSession));
this.sessionManager = new DefaultWebSessionManager();
this.sessionManager.setSessionIdResolver(this.sessionIdResolver);
......@@ -92,7 +92,7 @@ public class DefaultWebSessionManagerTests {
@Test
public void getSessionSaveWhenCreatedAndNotStartedThenNotSaved() {
when(this.sessionIdResolver.resolveSessionIds(this.exchange)).thenReturn(Collections.emptyList());
given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.emptyList());
WebSession session = this.sessionManager.getSession(this.exchange).block();
this.exchange.getResponse().setComplete().block();
......@@ -106,12 +106,12 @@ public class DefaultWebSessionManagerTests {
@Test
public void getSessionSaveWhenCreatedAndStartedThenSavesAndSetsId() {
when(this.sessionIdResolver.resolveSessionIds(this.exchange)).thenReturn(Collections.emptyList());
given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.emptyList());
WebSession session = this.sessionManager.getSession(this.exchange).block();
assertSame(this.createSession, session);
String sessionId = this.createSession.getId();
when(this.createSession.isStarted()).thenReturn(true);
given(this.createSession.isStarted()).willReturn(true);
this.exchange.getResponse().setComplete().block();
verify(this.sessionStore).createWebSession();
......@@ -123,7 +123,7 @@ public class DefaultWebSessionManagerTests {
public void existingSession() {
String sessionId = this.updateSession.getId();
when(this.sessionIdResolver.resolveSessionIds(this.exchange)).thenReturn(Collections.singletonList(sessionId));
given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.singletonList(sessionId));
WebSession actual = this.sessionManager.getSession(this.exchange).block();
assertNotNull(actual);
......@@ -134,9 +134,9 @@ public class DefaultWebSessionManagerTests {
public void multipleSessionIds() {
List<String> ids = Arrays.asList("not-this", "not-that", this.updateSession.getId());
when(this.sessionStore.retrieveSession("not-this")).thenReturn(Mono.empty());
when(this.sessionStore.retrieveSession("not-that")).thenReturn(Mono.empty());
when(this.sessionIdResolver.resolveSessionIds(this.exchange)).thenReturn(ids);
given(this.sessionStore.retrieveSession("not-this")).willReturn(Mono.empty());
given(this.sessionStore.retrieveSession("not-that")).willReturn(Mono.empty());
given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(ids);
WebSession actual = this.sessionManager.getSession(this.exchange).block();
assertNotNull(actual);
......
......@@ -35,8 +35,8 @@ import org.springframework.web.server.ServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
/**
......@@ -53,10 +53,10 @@ public class DispatcherHandlerTests {
public void handlerMappingOrder() {
HandlerMapping hm1 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
HandlerMapping hm2 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
when(((Ordered) hm1).getOrder()).thenReturn(1);
when(((Ordered) hm2).getOrder()).thenReturn(2);
when((hm1).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "1"));
when((hm2).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "2"));
given(((Ordered) hm1).getOrder()).willReturn(1);
given(((Ordered) hm2).getOrder()).willReturn(2);
given((hm1).getHandler(any())).willReturn(Mono.just((Supplier<String>) () -> "1"));
given((hm2).getHandler(any())).willReturn(Mono.just((Supplier<String>) () -> "2"));
StaticApplicationContext context = new StaticApplicationContext();
context.registerBean("b2", HandlerMapping.class, () -> hm2);
......
......@@ -43,7 +43,7 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.verify;
/**
......@@ -115,11 +115,11 @@ public class DelegatingWebFluxConfigurationTests {
@Test
public void resourceHandlerMapping() throws Exception {
delegatingConfig.setConfigurers(Collections.singletonList(webFluxConfigurer));
doAnswer(invocation -> {
willAnswer(invocation -> {
ResourceHandlerRegistry registry = invocation.getArgument(0);
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static");
return null;
}).when(webFluxConfigurer).addResourceHandlers(any(ResourceHandlerRegistry.class));
}).given(webFluxConfigurer).addResourceHandlers(any(ResourceHandlerRegistry.class));
delegatingConfig.resourceHandlerMapping(delegatingConfig.resourceUrlProvider());
verify(webFluxConfigurer).addResourceHandlers(any(ResourceHandlerRegistry.class));
......
......@@ -39,8 +39,8 @@ import org.springframework.web.reactive.function.BodyInserter;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.http.HttpMethod.DELETE;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.OPTIONS;
......@@ -131,7 +131,7 @@ public class DefaultClientRequestBuilderTests {
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
ExchangeStrategies strategies = mock(ExchangeStrategies.class);
when(strategies.messageWriters()).thenReturn(messageWriters);
given(strategies.messageWriters()).willReturn(messageWriters);
MockClientHttpRequest request = new MockClientHttpRequest(GET, "/");
result.writeTo(request, strategies).block();
......@@ -153,7 +153,7 @@ public class DefaultClientRequestBuilderTests {
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
ExchangeStrategies strategies = mock(ExchangeStrategies.class);
when(strategies.messageWriters()).thenReturn(messageWriters);
given(strategies.messageWriters()).willReturn(messageWriters);
MockClientHttpRequest request = new MockClientHttpRequest(GET, "/");
result.writeTo(request, strategies).block();
......@@ -176,7 +176,7 @@ public class DefaultClientRequestBuilderTests {
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
ExchangeStrategies strategies = mock(ExchangeStrategies.class);
when(strategies.messageWriters()).thenReturn(messageWriters);
given(strategies.messageWriters()).willReturn(messageWriters);
MockClientHttpRequest request = new MockClientHttpRequest(GET, "/");
result.writeTo(request, strategies).block();
......
......@@ -49,8 +49,8 @@ import org.springframework.util.MultiValueMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.web.reactive.function.BodyExtractors.toMono;
/**
......@@ -77,7 +77,7 @@ public class DefaultClientResponseTests {
@Test
public void statusCode() {
HttpStatus status = HttpStatus.CONTINUE;
when(mockResponse.getStatusCode()).thenReturn(status);
given(mockResponse.getStatusCode()).willReturn(status);
assertEquals(status, defaultClientResponse.statusCode());
}
......@@ -85,7 +85,7 @@ public class DefaultClientResponseTests {
@Test
public void rawStatusCode() {
int status = 999;
when(mockResponse.getRawStatusCode()).thenReturn(status);
given(mockResponse.getRawStatusCode()).willReturn(status);
assertEquals(status, defaultClientResponse.rawStatusCode());
}
......@@ -102,7 +102,7 @@ public class DefaultClientResponseTests {
List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
httpHeaders.setRange(range);
when(mockResponse.getHeaders()).thenReturn(httpHeaders);
given(mockResponse.getHeaders()).willReturn(httpHeaders);
ClientResponse.Headers headers = defaultClientResponse.headers();
assertEquals(OptionalLong.of(contentLength), headers.contentLength());
......@@ -116,7 +116,7 @@ public class DefaultClientResponseTests {
MultiValueMap<String, ResponseCookie> cookies = new LinkedMultiValueMap<>();
cookies.add("foo", cookie);
when(mockResponse.getCookies()).thenReturn(cookies);
given(mockResponse.getCookies()).willReturn(cookies);
assertSame(cookies, defaultClientResponse.cookies());
}
......@@ -132,7 +132,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
Mono<String> resultMono = defaultClientResponse.body(toMono(String.class));
assertEquals("foo", resultMono.block());
......@@ -148,7 +148,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
Mono<String> resultMono = defaultClientResponse.bodyToMono(String.class);
assertEquals("foo", resultMono.block());
......@@ -164,7 +164,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
Mono<String> resultMono =
defaultClientResponse.bodyToMono(new ParameterizedTypeReference<String>() {
......@@ -182,7 +182,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
Flux<String> resultFlux = defaultClientResponse.bodyToFlux(String.class);
Mono<List<String>> result = resultFlux.collectList();
......@@ -199,7 +199,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
Flux<String> resultFlux =
defaultClientResponse.bodyToFlux(new ParameterizedTypeReference<String>() {
......@@ -218,7 +218,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<String> result = defaultClientResponse.toEntity(String.class).block();
assertEquals("foo", result.getBody());
......@@ -236,14 +236,14 @@ public class DefaultClientResponseTests {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.TEXT_PLAIN);
when(mockResponse.getHeaders()).thenReturn(httpHeaders);
when(mockResponse.getStatusCode()).thenThrow(new IllegalArgumentException("999"));
when(mockResponse.getRawStatusCode()).thenReturn(999);
when(mockResponse.getBody()).thenReturn(body);
given(mockResponse.getHeaders()).willReturn(httpHeaders);
given(mockResponse.getStatusCode()).willThrow(new IllegalArgumentException("999"));
given(mockResponse.getRawStatusCode()).willReturn(999);
given(mockResponse.getBody()).willReturn(body);
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<String> result = defaultClientResponse.toEntity(String.class).block();
assertEquals("foo", result.getBody());
......@@ -268,7 +268,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<String> result = defaultClientResponse.toEntity(
new ParameterizedTypeReference<String>() {
......@@ -289,7 +289,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(String.class).block();
assertEquals(Collections.singletonList("foo"), result.getBody());
......@@ -307,14 +307,14 @@ public class DefaultClientResponseTests {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.TEXT_PLAIN);
when(mockResponse.getHeaders()).thenReturn(httpHeaders);
when(mockResponse.getStatusCode()).thenThrow(new IllegalArgumentException("999"));
when(mockResponse.getRawStatusCode()).thenReturn(999);
when(mockResponse.getBody()).thenReturn(body);
given(mockResponse.getHeaders()).willReturn(httpHeaders);
given(mockResponse.getStatusCode()).willThrow(new IllegalArgumentException("999"));
given(mockResponse.getRawStatusCode()).willReturn(999);
given(mockResponse.getBody()).willReturn(body);
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(String.class).block();
assertEquals(Collections.singletonList("foo"), result.getBody());
......@@ -340,7 +340,7 @@ public class DefaultClientResponseTests {
List<HttpMessageReader<?>> messageReaders = Collections
.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);
given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);
ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(
new ParameterizedTypeReference<String>() {
......@@ -355,10 +355,10 @@ public class DefaultClientResponseTests {
private void mockTextPlainResponse(Flux<DataBuffer> body) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.TEXT_PLAIN);
when(mockResponse.getHeaders()).thenReturn(httpHeaders);
when(mockResponse.getStatusCode()).thenReturn(HttpStatus.OK);
when(mockResponse.getRawStatusCode()).thenReturn(HttpStatus.OK.value());
when(mockResponse.getBody()).thenReturn(body);
given(mockResponse.getHeaders()).willReturn(httpHeaders);
given(mockResponse.getStatusCode()).willReturn(HttpStatus.OK);
given(mockResponse.getRawStatusCode()).willReturn(HttpStatus.OK.value());
given(mockResponse.getBody()).willReturn(body);
}
}
......@@ -38,10 +38,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultWebClient}.
......@@ -64,7 +64,7 @@ public class DefaultWebClientTests {
MockitoAnnotations.initMocks(this);
this.exchangeFunction = mock(ExchangeFunction.class);
ClientResponse mockResponse = mock(ClientResponse.class);
when(this.exchangeFunction.exchange(this.captor.capture())).thenReturn(Mono.just(mockResponse));
given(this.exchangeFunction.exchange(this.captor.capture())).willReturn(Mono.just(mockResponse));
this.builder = WebClient.builder().baseUrl("/base").exchangeFunction(this.exchangeFunction);
}
......@@ -283,7 +283,7 @@ public class DefaultWebClientTests {
@Test
public void switchToErrorOnEmptyClientResponseMono() {
ExchangeFunction exchangeFunction = mock(ExchangeFunction.class);
when(exchangeFunction.exchange(any())).thenReturn(Mono.empty());
given(exchangeFunction.exchange(any())).willReturn(Mono.empty());
WebClient.Builder builder = WebClient.builder().baseUrl("/base").exchangeFunction(exchangeFunction);
StepVerifier.create(builder.build().get().uri("/path").exchange())
.expectErrorMessage("The underlying HTTP client completed without emitting a response.")
......
......@@ -36,8 +36,8 @@ import org.springframework.web.reactive.function.BodyExtractors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ExchangeFilterFunctions}.
......@@ -165,7 +165,7 @@ public class ExchangeFilterFunctionsTests {
public void statusHandlerMatch() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, DEFAULT_URL).build();
ClientResponse response = mock(ClientResponse.class);
when(response.statusCode()).thenReturn(HttpStatus.NOT_FOUND);
given(response.statusCode()).willReturn(HttpStatus.NOT_FOUND);
ExchangeFunction exchange = r -> Mono.just(response);
......@@ -183,7 +183,7 @@ public class ExchangeFilterFunctionsTests {
public void statusHandlerNoMatch() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, DEFAULT_URL).build();
ClientResponse response = mock(ClientResponse.class);
when(response.statusCode()).thenReturn(HttpStatus.NOT_FOUND);
given(response.statusCode()).willReturn(HttpStatus.NOT_FOUND);
Mono<ClientResponse> result = ExchangeFilterFunctions
.statusError(HttpStatus::is5xxServerError, req -> new MyException())
......
......@@ -36,8 +36,8 @@ import org.springframework.web.reactive.function.client.ClientResponse;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -62,7 +62,7 @@ public class ClientResponseWrapperTests {
@Test
public void statusCode() {
HttpStatus status = HttpStatus.BAD_REQUEST;
when(mockResponse.statusCode()).thenReturn(status);
given(mockResponse.statusCode()).willReturn(status);
assertSame(status, wrapper.statusCode());
}
......@@ -70,7 +70,7 @@ public class ClientResponseWrapperTests {
@Test
public void rawStatusCode() {
int status = 999;
when(mockResponse.rawStatusCode()).thenReturn(status);
given(mockResponse.rawStatusCode()).willReturn(status);
assertEquals(status, wrapper.rawStatusCode());
}
......@@ -78,7 +78,7 @@ public class ClientResponseWrapperTests {
@Test
public void headers() {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
when(mockResponse.headers()).thenReturn(headers);
given(mockResponse.headers()).willReturn(headers);
assertSame(headers, wrapper.headers());
}
......@@ -87,7 +87,7 @@ public class ClientResponseWrapperTests {
@SuppressWarnings("unchecked")
public void cookies() {
MultiValueMap<String, ResponseCookie> cookies = mock(MultiValueMap.class);
when(mockResponse.cookies()).thenReturn(cookies);
given(mockResponse.cookies()).willReturn(cookies);
assertSame(cookies, wrapper.cookies());
}
......@@ -96,7 +96,7 @@ public class ClientResponseWrapperTests {
public void bodyExtractor() {
Mono<String> result = Mono.just("foo");
BodyExtractor<Mono<String>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class);
when(mockResponse.body(extractor)).thenReturn(result);
given(mockResponse.body(extractor)).willReturn(result);
assertSame(result, wrapper.body(extractor));
}
......@@ -104,7 +104,7 @@ public class ClientResponseWrapperTests {
@Test
public void bodyToMonoClass() {
Mono<String> result = Mono.just("foo");
when(mockResponse.bodyToMono(String.class)).thenReturn(result);
given(mockResponse.bodyToMono(String.class)).willReturn(result);
assertSame(result, wrapper.bodyToMono(String.class));
}
......@@ -113,7 +113,7 @@ public class ClientResponseWrapperTests {
public void bodyToMonoParameterizedTypeReference() {
Mono<String> result = Mono.just("foo");
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockResponse.bodyToMono(reference)).thenReturn(result);
given(mockResponse.bodyToMono(reference)).willReturn(result);
assertSame(result, wrapper.bodyToMono(reference));
}
......@@ -121,7 +121,7 @@ public class ClientResponseWrapperTests {
@Test
public void bodyToFluxClass() {
Flux<String> result = Flux.just("foo");
when(mockResponse.bodyToFlux(String.class)).thenReturn(result);
given(mockResponse.bodyToFlux(String.class)).willReturn(result);
assertSame(result, wrapper.bodyToFlux(String.class));
}
......@@ -130,7 +130,7 @@ public class ClientResponseWrapperTests {
public void bodyToFluxParameterizedTypeReference() {
Flux<String> result = Flux.just("foo");
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockResponse.bodyToFlux(reference)).thenReturn(result);
given(mockResponse.bodyToFlux(reference)).willReturn(result);
assertSame(result, wrapper.bodyToFlux(reference));
}
......@@ -138,7 +138,7 @@ public class ClientResponseWrapperTests {
@Test
public void toEntityClass() {
Mono<ResponseEntity<String>> result = Mono.just(new ResponseEntity<>("foo", HttpStatus.OK));
when(mockResponse.toEntity(String.class)).thenReturn(result);
given(mockResponse.toEntity(String.class)).willReturn(result);
assertSame(result, wrapper.toEntity(String.class));
}
......@@ -147,7 +147,7 @@ public class ClientResponseWrapperTests {
public void toEntityParameterizedTypeReference() {
Mono<ResponseEntity<String>> result = Mono.just(new ResponseEntity<>("foo", HttpStatus.OK));
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockResponse.toEntity(reference)).thenReturn(result);
given(mockResponse.toEntity(reference)).willReturn(result);
assertSame(result, wrapper.toEntity(reference));
}
......@@ -155,7 +155,7 @@ public class ClientResponseWrapperTests {
@Test
public void toEntityListClass() {
Mono<ResponseEntity<List<String>>> result = Mono.just(new ResponseEntity<>(singletonList("foo"), HttpStatus.OK));
when(mockResponse.toEntityList(String.class)).thenReturn(result);
given(mockResponse.toEntityList(String.class)).willReturn(result);
assertSame(result, wrapper.toEntityList(String.class));
}
......@@ -164,7 +164,7 @@ public class ClientResponseWrapperTests {
public void toEntityListParameterizedTypeReference() {
Mono<ResponseEntity<List<String>>> result = Mono.just(new ResponseEntity<>(singletonList("foo"), HttpStatus.OK));
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockResponse.toEntityList(reference)).thenReturn(result);
given(mockResponse.toEntityList(reference)).willReturn(result);
assertSame(result, wrapper.toEntityList(reference));
}
......
......@@ -47,8 +47,8 @@ import org.springframework.web.server.ServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -139,14 +139,14 @@ public class DefaultRenderingResponseTests {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
ViewResolver viewResolver = mock(ViewResolver.class);
View view = mock(View.class);
when(viewResolver.resolveViewName("view", Locale.ENGLISH)).thenReturn(Mono.just(view));
when(view.render(model, null, exchange)).thenReturn(Mono.empty());
given(viewResolver.resolveViewName("view", Locale.ENGLISH)).willReturn(Mono.just(view));
given(view.render(model, null, exchange)).willReturn(Mono.empty());
List<ViewResolver> viewResolvers = new ArrayList<>();
viewResolvers.add(viewResolver);
HandlerStrategies mockConfig = mock(HandlerStrategies.class);
when(mockConfig.viewResolvers()).thenReturn(viewResolvers);
given(mockConfig.viewResolvers()).willReturn(viewResolvers);
StepVerifier.create(result)
.expectNextMatches(response -> "view".equals(response.name()) &&
......@@ -162,13 +162,13 @@ public class DefaultRenderingResponseTests {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));
TestView view = new TestView();
ViewResolver viewResolver = mock(ViewResolver.class);
when(viewResolver.resolveViewName(any(), any())).thenReturn(Mono.just(view));
given(viewResolver.resolveViewName(any(), any())).willReturn(Mono.just(view));
List<ViewResolver> viewResolvers = new ArrayList<>();
viewResolvers.add(viewResolver);
ServerResponse.Context context = mock(ServerResponse.Context.class);
when(context.viewResolvers()).thenReturn(viewResolvers);
given(context.viewResolvers()).willReturn(viewResolvers);
StepVerifier.create(result.flatMap(response -> response.writeTo(exchange, context)))
.verifyComplete();
......
......@@ -33,8 +33,8 @@ import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.support.ServerRequestWrapper;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -56,7 +56,7 @@ public class HeadersWrapperTests {
@Test
public void accept() {
List<MediaType> accept = Collections.singletonList(MediaType.APPLICATION_JSON);
when(mockHeaders.accept()).thenReturn(accept);
given(mockHeaders.accept()).willReturn(accept);
assertSame(accept, wrapper.accept());
}
......@@ -64,7 +64,7 @@ public class HeadersWrapperTests {
@Test
public void acceptCharset() {
List<Charset> acceptCharset = Collections.singletonList(StandardCharsets.UTF_8);
when(mockHeaders.acceptCharset()).thenReturn(acceptCharset);
given(mockHeaders.acceptCharset()).willReturn(acceptCharset);
assertSame(acceptCharset, wrapper.acceptCharset());
}
......@@ -72,7 +72,7 @@ public class HeadersWrapperTests {
@Test
public void contentLength() {
OptionalLong contentLength = OptionalLong.of(42L);
when(mockHeaders.contentLength()).thenReturn(contentLength);
given(mockHeaders.contentLength()).willReturn(contentLength);
assertSame(contentLength, wrapper.contentLength());
}
......@@ -80,7 +80,7 @@ public class HeadersWrapperTests {
@Test
public void contentType() {
Optional<MediaType> contentType = Optional.of(MediaType.APPLICATION_JSON);
when(mockHeaders.contentType()).thenReturn(contentType);
given(mockHeaders.contentType()).willReturn(contentType);
assertSame(contentType, wrapper.contentType());
}
......@@ -88,7 +88,7 @@ public class HeadersWrapperTests {
@Test
public void host() {
InetSocketAddress host = InetSocketAddress.createUnresolved("example.com", 42);
when(mockHeaders.host()).thenReturn(host);
given(mockHeaders.host()).willReturn(host);
assertSame(host, wrapper.host());
}
......@@ -96,7 +96,7 @@ public class HeadersWrapperTests {
@Test
public void range() {
List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(42));
when(mockHeaders.range()).thenReturn(range);
given(mockHeaders.range()).willReturn(range);
assertSame(range, wrapper.range());
}
......@@ -105,7 +105,7 @@ public class HeadersWrapperTests {
public void header() {
String name = "foo";
List<String> value = Collections.singletonList("bar");
when(mockHeaders.header(name)).thenReturn(value);
given(mockHeaders.header(name)).willReturn(value);
assertSame(value, wrapper.header(name));
}
......@@ -113,7 +113,7 @@ public class HeadersWrapperTests {
@Test
public void asHttpHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
when(mockHeaders.asHttpHeaders()).thenReturn(httpHeaders);
given(mockHeaders.asHttpHeaders()).willReturn(httpHeaders);
assertSame(httpHeaders, wrapper.asHttpHeaders());
}
......
......@@ -39,8 +39,8 @@ import org.springframework.web.server.WebFilterChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -55,7 +55,7 @@ public class RouterFunctionsTests {
MockServerRequest request = MockServerRequest.builder().build();
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.test(request)).thenReturn(true);
given(requestPredicate.test(request)).willReturn(true);
RouterFunction<ServerResponse>
result = RouterFunctions.route(requestPredicate, handlerFunction);
......@@ -75,7 +75,7 @@ public class RouterFunctionsTests {
MockServerRequest request = MockServerRequest.builder().build();
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.test(request)).thenReturn(false);
given(requestPredicate.test(request)).willReturn(false);
RouterFunction<ServerResponse> result = RouterFunctions.route(requestPredicate, handlerFunction);
assertNotNull(result);
......@@ -93,7 +93,7 @@ public class RouterFunctionsTests {
MockServerRequest request = MockServerRequest.builder().build();
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.nest(request)).thenReturn(Optional.of(request));
given(requestPredicate.nest(request)).willReturn(Optional.of(request));
RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction);
assertNotNull(result);
......@@ -112,7 +112,7 @@ public class RouterFunctionsTests {
MockServerRequest request = MockServerRequest.builder().build();
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.nest(request)).thenReturn(Optional.empty());
given(requestPredicate.nest(request)).willReturn(Optional.empty());
RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction);
assertNotNull(result);
......
......@@ -37,8 +37,8 @@ import org.springframework.web.reactive.function.server.ServerRequest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -58,7 +58,7 @@ public class ServerRequestWrapperTests {
@Test
public void method() {
HttpMethod method = HttpMethod.POST;
when(mockRequest.method()).thenReturn(method);
given(mockRequest.method()).willReturn(method);
assertSame(method, wrapper.method());
}
......@@ -66,7 +66,7 @@ public class ServerRequestWrapperTests {
@Test
public void uri() {
URI uri = URI.create("https://example.com");
when(mockRequest.uri()).thenReturn(uri);
given(mockRequest.uri()).willReturn(uri);
assertSame(uri, wrapper.uri());
}
......@@ -74,7 +74,7 @@ public class ServerRequestWrapperTests {
@Test
public void path() {
String path = "/foo/bar";
when(mockRequest.path()).thenReturn(path);
given(mockRequest.path()).willReturn(path);
assertSame(path, wrapper.path());
}
......@@ -82,7 +82,7 @@ public class ServerRequestWrapperTests {
@Test
public void headers() {
ServerRequest.Headers headers = mock(ServerRequest.Headers.class);
when(mockRequest.headers()).thenReturn(headers);
given(mockRequest.headers()).willReturn(headers);
assertSame(headers, wrapper.headers());
}
......@@ -91,7 +91,7 @@ public class ServerRequestWrapperTests {
public void attribute() {
String name = "foo";
String value = "bar";
when(mockRequest.attribute(name)).thenReturn(Optional.of(value));
given(mockRequest.attribute(name)).willReturn(Optional.of(value));
assertEquals(Optional.of(value), wrapper.attribute(name));
}
......@@ -100,7 +100,7 @@ public class ServerRequestWrapperTests {
public void queryParam() {
String name = "foo";
String value = "bar";
when(mockRequest.queryParam(name)).thenReturn(Optional.of(value));
given(mockRequest.queryParam(name)).willReturn(Optional.of(value));
assertEquals(Optional.of(value), wrapper.queryParam(name));
}
......@@ -109,7 +109,7 @@ public class ServerRequestWrapperTests {
public void queryParams() {
MultiValueMap<String, String> value = new LinkedMultiValueMap<>();
value.add("foo", "bar");
when(mockRequest.queryParams()).thenReturn(value);
given(mockRequest.queryParams()).willReturn(value);
assertSame(value, wrapper.queryParams());
}
......@@ -118,7 +118,7 @@ public class ServerRequestWrapperTests {
public void pathVariable() {
String name = "foo";
String value = "bar";
when(mockRequest.pathVariable(name)).thenReturn(value);
given(mockRequest.pathVariable(name)).willReturn(value);
assertEquals(value, wrapper.pathVariable(name));
}
......@@ -126,7 +126,7 @@ public class ServerRequestWrapperTests {
@Test
public void pathVariables() {
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
when(mockRequest.pathVariables()).thenReturn(pathVariables);
given(mockRequest.pathVariables()).willReturn(pathVariables);
assertSame(pathVariables, wrapper.pathVariables());
}
......@@ -135,7 +135,7 @@ public class ServerRequestWrapperTests {
@SuppressWarnings("unchecked")
public void cookies() {
MultiValueMap<String, HttpCookie> cookies = mock(MultiValueMap.class);
when(mockRequest.cookies()).thenReturn(cookies);
given(mockRequest.cookies()).willReturn(cookies);
assertSame(cookies, wrapper.cookies());
}
......@@ -144,7 +144,7 @@ public class ServerRequestWrapperTests {
public void bodyExtractor() {
Mono<String> result = Mono.just("foo");
BodyExtractor<Mono<String>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class);
when(mockRequest.body(extractor)).thenReturn(result);
given(mockRequest.body(extractor)).willReturn(result);
assertSame(result, wrapper.body(extractor));
}
......@@ -152,7 +152,7 @@ public class ServerRequestWrapperTests {
@Test
public void bodyToMonoClass() {
Mono<String> result = Mono.just("foo");
when(mockRequest.bodyToMono(String.class)).thenReturn(result);
given(mockRequest.bodyToMono(String.class)).willReturn(result);
assertSame(result, wrapper.bodyToMono(String.class));
}
......@@ -161,7 +161,7 @@ public class ServerRequestWrapperTests {
public void bodyToMonoParameterizedTypeReference() {
Mono<String> result = Mono.just("foo");
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockRequest.bodyToMono(reference)).thenReturn(result);
given(mockRequest.bodyToMono(reference)).willReturn(result);
assertSame(result, wrapper.bodyToMono(reference));
}
......@@ -169,7 +169,7 @@ public class ServerRequestWrapperTests {
@Test
public void bodyToFluxClass() {
Flux<String> result = Flux.just("foo");
when(mockRequest.bodyToFlux(String.class)).thenReturn(result);
given(mockRequest.bodyToFlux(String.class)).willReturn(result);
assertSame(result, wrapper.bodyToFlux(String.class));
}
......@@ -178,7 +178,7 @@ public class ServerRequestWrapperTests {
public void bodyToFluxParameterizedTypeReference() {
Flux<String> result = Flux.just("foo");
ParameterizedTypeReference<String> reference = new ParameterizedTypeReference<String>() {};
when(mockRequest.bodyToFlux(reference)).thenReturn(result);
given(mockRequest.bodyToFlux(reference)).willReturn(result);
assertSame(result, wrapper.bodyToFlux(reference));
}
......
......@@ -64,8 +64,8 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ResourceWebHandler}.
......@@ -250,10 +250,10 @@ public class ResourceWebHandlerTests {
// Use mock ResourceResolver: i.e. we're only testing upfront validations...
Resource resource = mock(Resource.class);
when(resource.getFilename()).thenThrow(new AssertionError("Resource should not be resolved"));
when(resource.getInputStream()).thenThrow(new AssertionError("Resource should not be resolved"));
given(resource.getFilename()).willThrow(new AssertionError("Resource should not be resolved"));
given(resource.getInputStream()).willThrow(new AssertionError("Resource should not be resolved"));
ResourceResolver resolver = mock(ResourceResolver.class);
when(resolver.resolveResource(any(), any(), any(), any())).thenReturn(Mono.just(resource));
given(resolver.resolveResource(any(), any(), any(), any())).willReturn(Mono.just(resource));
ResourceWebHandler handler = new ResourceWebHandler();
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass())));
......
......@@ -50,8 +50,8 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
/**
......@@ -253,8 +253,8 @@ public class InvocableHandlerMethodTests {
private <T> HandlerMethodArgumentResolver stubResolver(Mono<Object> stubValue) {
HandlerMethodArgumentResolver resolver = mock(HandlerMethodArgumentResolver.class);
when(resolver.supportsParameter(any())).thenReturn(true);
when(resolver.resolveArgument(any(), any(), any())).thenReturn(stubValue);
given(resolver.supportsParameter(any())).willReturn(true);
given(resolver.resolveArgument(any(), any(), any())).willReturn(stubValue);
return resolver;
}
......
......@@ -46,8 +46,8 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link SessionAttributeMethodArgumentResolver}.
......@@ -90,7 +90,7 @@ public class SessionAttributeMethodArgumentResolverTests {
StepVerifier.create(mono).expectError(ServerWebInputException.class).verify();
Foo foo = new Foo();
when(this.session.getAttribute("foo")).thenReturn(foo);
given(this.session.getAttribute("foo")).willReturn(foo);
mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
assertSame(foo, mono.block());
}
......@@ -99,7 +99,7 @@ public class SessionAttributeMethodArgumentResolverTests {
public void resolveWithName() {
MethodParameter param = initMethodParameter(1);
Foo foo = new Foo();
when(this.session.getAttribute("specialFoo")).thenReturn(foo);
given(this.session.getAttribute("specialFoo")).willReturn(foo);
Mono<Object> mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
assertSame(foo, mono.block());
}
......@@ -111,7 +111,7 @@ public class SessionAttributeMethodArgumentResolverTests {
assertNull(mono.block());
Foo foo = new Foo();
when(this.session.getAttribute("foo")).thenReturn(foo);
given(this.session.getAttribute("foo")).willReturn(foo);
mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange);
assertSame(foo, mono.block());
}
......@@ -131,7 +131,7 @@ public class SessionAttributeMethodArgumentResolverTests {
BindingContext bindingContext = new BindingContext(initializer);
Foo foo = new Foo();
when(this.session.getAttribute("foo")).thenReturn(foo);
given(this.session.getAttribute("foo")).willReturn(foo);
actual = (Optional<Object>) this.resolver.resolveArgument(param, bindingContext, this.exchange).block();
assertNotNull(actual);
......
......@@ -27,8 +27,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
......@@ -43,7 +43,7 @@ public class RouterFunctionsTests {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.test(request)).thenReturn(true);
given(requestPredicate.test(request)).willReturn(true);
RouterFunction<ServerResponse>
result = RouterFunctions.route(requestPredicate, handlerFunction);
......@@ -61,7 +61,7 @@ public class RouterFunctionsTests {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.test(request)).thenReturn(false);
given(requestPredicate.test(request)).willReturn(false);
RouterFunction<ServerResponse> result = RouterFunctions.route(requestPredicate, handlerFunction);
assertNotNull(result);
......@@ -78,7 +78,7 @@ public class RouterFunctionsTests {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.nest(request)).thenReturn(Optional.of(request));
given(requestPredicate.nest(request)).willReturn(Optional.of(request));
RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction);
assertNotNull(result);
......@@ -96,7 +96,7 @@ public class RouterFunctionsTests {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());
RequestPredicate requestPredicate = mock(RequestPredicate.class);
when(requestPredicate.nest(request)).thenReturn(Optional.empty());
given(requestPredicate.nest(request)).willReturn(Optional.empty());
RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction);
assertNotNull(result);
......
......@@ -29,7 +29,7 @@ import org.springframework.http.MediaType;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
......@@ -150,7 +150,7 @@ public class ResponseBodyEmitterTests {
verifyNoMoreInteractions(this.handler);
IOException failure = new IOException();
doThrow(failure).when(this.handler).send("foo", MediaType.TEXT_PLAIN);
willThrow(failure).given(this.handler).send("foo", MediaType.TEXT_PLAIN);
try {
this.emitter.send("foo", MediaType.TEXT_PLAIN);
fail("Expected exception");
......
......@@ -48,8 +48,8 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ResourceHttpRequestHandler}.
......@@ -315,10 +315,10 @@ public class ResourceHttpRequestHandlerTests {
// Use mock ResourceResolver: i.e. we're only testing upfront validations...
Resource resource = mock(Resource.class);
when(resource.getFilename()).thenThrow(new AssertionError("Resource should not be resolved"));
when(resource.getInputStream()).thenThrow(new AssertionError("Resource should not be resolved"));
given(resource.getFilename()).willThrow(new AssertionError("Resource should not be resolved"));
given(resource.getInputStream()).willThrow(new AssertionError("Resource should not be resolved"));
ResourceResolver resolver = mock(ResourceResolver.class);
when(resolver.resolveResource(any(), any(), any(), any())).thenReturn(resource);
given(resolver.resolveResource(any(), any(), any(), any())).willReturn(resource);
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass())));
......
......@@ -39,8 +39,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ResourceUrlProvider}.
......@@ -156,7 +156,7 @@ public class ResourceUrlProviderTests {
public void getForLookupPathShouldNotFailIfPathContainsDoubleSlashes() {
// given
ResourceResolver mockResourceResolver = mock(ResourceResolver.class);
when(mockResourceResolver.resolveUrlPath(any(), any(), any())).thenReturn("some-path");
given(mockResourceResolver.resolveUrlPath(any(), any(), any())).willReturn("some-path");
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.getResourceResolvers().add(mockResourceResolver);
......
......@@ -52,7 +52,6 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link ScriptTemplateView}.
......@@ -212,7 +211,7 @@ public class ScriptTemplateViewTests {
MockHttpServletResponse response = new MockHttpServletResponse();
Map<String, Object> model = new HashMap<>();
InvocableScriptEngine engine = mock(InvocableScriptEngine.class);
when(engine.invokeFunction(any(), any(), any(), any())).thenReturn("foo");
given(engine.invokeFunction(any(), any(), any(), any())).willReturn("foo");
this.view.setEngine(engine);
this.view.setRenderFunction("render");
this.view.setApplicationContext(this.wac);
......
......@@ -67,13 +67,13 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Test fixture for {@link StompSubProtocolHandler} tests.
......@@ -99,7 +99,7 @@ public class StompSubProtocolHandlerTests {
this.channel = Mockito.mock(MessageChannel.class);
this.messageCaptor = ArgumentCaptor.forClass(Message.class);
when(this.channel.send(any())).thenReturn(true);
given(this.channel.send(any())).willReturn(true);
this.session = new TestWebSocketSession();
this.session.setId("s1");
......@@ -223,7 +223,7 @@ public class StompSubProtocolHandlerTests {
public void handleMessageToClientWithHeartbeatSuppressingSockJsHeartbeat() throws IOException {
SockJsSession sockJsSession = Mockito.mock(SockJsSession.class);
when(sockJsSession.getId()).thenReturn("s1");
given(sockJsSession.getId()).willReturn("s1");
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
accessor.setHeartbeat(0, 10);
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
......@@ -236,7 +236,7 @@ public class StompSubProtocolHandlerTests {
verifyNoMoreInteractions(sockJsSession);
sockJsSession = Mockito.mock(SockJsSession.class);
when(sockJsSession.getId()).thenReturn("s1");
given(sockJsSession.getId()).willReturn("s1");
accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
accessor.setHeartbeat(0, 0);
message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
......
......@@ -54,11 +54,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link WebSocketStompClient}.
......@@ -95,8 +95,8 @@ public class WebSocketStompClientTests {
this.webSocketHandlerCaptor = ArgumentCaptor.forClass(WebSocketHandler.class);
this.handshakeFuture = new SettableListenableFuture<>();
when(webSocketClient.doHandshake(this.webSocketHandlerCaptor.capture(), any(), any(URI.class)))
.thenReturn(this.handshakeFuture);
given(webSocketClient.doHandshake(this.webSocketHandlerCaptor.capture(), any(), any(URI.class)))
.willReturn(this.handshakeFuture);
}
......@@ -303,7 +303,7 @@ public class WebSocketStompClientTests {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
ScheduledFuture future = mock(ScheduledFuture.class);
when(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).thenReturn(future);
given(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).willReturn(future);
tcpConnection.onReadInactivity(mock(Runnable.class), 2L);
tcpConnection.onWriteInactivity(mock(Runnable.class), 2L);
......
......@@ -43,7 +43,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link org.springframework.web.socket.sockjs.client.SockJsClient}.
......@@ -182,7 +181,7 @@ public class SockJsClientTests {
private ArgumentCaptor<HttpHeaders> setupInfoRequest(boolean webSocketEnabled) {
ArgumentCaptor<HttpHeaders> headersCaptor = ArgumentCaptor.forClass(HttpHeaders.class);
when(this.infoReceiver.executeInfoRequest(any(), headersCaptor.capture())).thenReturn(
given(this.infoReceiver.executeInfoRequest(any(), headersCaptor.capture())).willReturn(
"{\"entropy\":123," +
"\"origins\":[\"*:*\"]," +
"\"cookie_needed\":true," +
......
......@@ -159,6 +159,13 @@
value="Please use specialized AssertJ assertThat*Exception method." />
<property name="ignoreComments" value="true" />
</module>
<module name="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck">
<property name="maximum" value="0"/>
<property name="format" value="org\.mockito\.Mockito\.(when|doThrow|doAnswer)" />
<property name="message"
value="Please use BDDMockito imports." />
<property name="ignoreComments" value="true" />
</module>
<!-- Spring Conventions -->
<module name="io.spring.javaformat.checkstyle.check.SpringLambdaCheck">
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册