Skip to content

Commit 798b51f

Browse files
committed
Migrate to BDD Mockito
Migrate all tests to consistently use BDD Mockito. Also add checksyle rule to enforce going forwards.
1 parent 816bbee commit 798b51f

File tree

55 files changed

+322
-324
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+322
-324
lines changed

spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@
4545
import org.apache.commons.logging.LogFactory;
4646
import org.junit.Ignore;
4747
import org.junit.Test;
48-
import org.mockito.ArgumentMatchers;
4948

5049
import org.springframework.beans.BeansException;
5150
import org.springframework.beans.MutablePropertyValues;
@@ -112,13 +111,13 @@
112111
import static org.junit.Assert.assertSame;
113112
import static org.junit.Assert.assertTrue;
114113
import static org.junit.Assert.fail;
114+
import static org.mockito.ArgumentMatchers.any;
115115
import static org.mockito.ArgumentMatchers.eq;
116116
import static org.mockito.ArgumentMatchers.isNull;
117117
import static org.mockito.BDDMockito.given;
118118
import static org.mockito.Mockito.mock;
119119
import static org.mockito.Mockito.never;
120120
import static org.mockito.Mockito.verify;
121-
import static org.mockito.Mockito.when;
122121

123122
/**
124123
* Tests properties population and autowire behavior.
@@ -135,8 +134,6 @@ public class DefaultListableBeanFactoryTests {
135134

136135
private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
137136

138-
139-
140137
@Test
141138
public void testUnreferencedSingletonWasInstantiated() {
142139
KnowsIfInstantiated.clearInstantiationRecord();
@@ -1240,8 +1237,8 @@ public void testDoubleArrayConstructorWithOptionalAutowiring() throws MalformedU
12401237
public void testExpressionInStringArray() {
12411238
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
12421239
BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class);
1243-
when(beanExpressionResolver.evaluate(eq("#{foo}"), ArgumentMatchers.any(BeanExpressionContext.class)))
1244-
.thenReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
1240+
given(beanExpressionResolver.evaluate(eq("#{foo}"), any(BeanExpressionContext.class)))
1241+
.willReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
12451242
bf.setBeanExpressionResolver(beanExpressionResolver);
12461243

12471244
RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class);

spring-beans/src/test/java/org/springframework/beans/factory/annotation/ParameterResolutionTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333
import static org.junit.Assert.assertTrue;
3434
import static org.mockito.ArgumentMatchers.any;
3535
import static org.mockito.ArgumentMatchers.isNull;
36+
import static org.mockito.BDDMockito.given;
3637
import static org.mockito.Mockito.mock;
37-
import static org.mockito.Mockito.when;
3838

3939
/**
4040
* Unit tests for {@link ParameterResolutionDelegate}.
@@ -128,7 +128,7 @@ public void resolveDependencyForAnnotatedParametersInTopLevelClassConstructor()
128128
AutowireCapableBeanFactory beanFactory = mock(AutowireCapableBeanFactory.class);
129129
// Configure the mocked BeanFactory to return the DependencyDescriptor for convenience and
130130
// to avoid using an ArgumentCaptor.
131-
when(beanFactory.resolveDependency(any(), isNull())).thenAnswer(invocation -> invocation.getArgument(0));
131+
given(beanFactory.resolveDependency(any(), isNull())).willAnswer(invocation -> invocation.getArgument(0));
132132

133133
Parameter[] parameters = constructor.getParameters();
134134
for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) {

spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@
3636
import static org.junit.Assert.assertEquals;
3737
import static org.mockito.ArgumentMatchers.any;
3838
import static org.mockito.ArgumentMatchers.anyString;
39+
import static org.mockito.BDDMockito.given;
3940
import static org.mockito.Mockito.mock;
4041
import static org.mockito.Mockito.never;
4142
import static org.mockito.Mockito.spy;
4243
import static org.mockito.Mockito.times;
4344
import static org.mockito.Mockito.verify;
44-
import static org.mockito.Mockito.when;
4545

4646
/**
4747
* @author Stephane Nicoll
@@ -312,7 +312,7 @@ public void invokeListenerWithSeveralTypes() {
312312
public void beanInstanceRetrievedAtEveryInvocation() {
313313
Method method = ReflectionUtils.findMethod(
314314
SampleEvents.class, "handleGenericString", GenericTestEvent.class);
315-
when(this.context.getBean("testBean")).thenReturn(this.sampleEvents);
315+
given(this.context.getBean("testBean")).willReturn(this.sampleEvents);
316316
ApplicationListenerMethodAdapter listener = new ApplicationListenerMethodAdapter(
317317
"testBean", GenericTestEvent.class, method);
318318
listener.init(this.context, new EventExpressionEvaluator());

spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@
5353
import static org.mockito.ArgumentMatchers.any;
5454
import static org.mockito.ArgumentMatchers.anyLong;
5555
import static org.mockito.ArgumentMatchers.isA;
56-
import static org.mockito.Mockito.doAnswer;
56+
import static org.mockito.BDDMockito.given;
57+
import static org.mockito.BDDMockito.willAnswer;
5758
import static org.mockito.Mockito.mock;
58-
import static org.mockito.Mockito.when;
5959

6060
/**
6161
* @author Arjen Poutsma
@@ -94,14 +94,14 @@ public void readByteChannel() throws Exception {
9494
@Test
9595
public void readByteChannelError() throws Exception {
9696
ReadableByteChannel channel = mock(ReadableByteChannel.class);
97-
when(channel.read(any()))
98-
.thenAnswer(invocation -> {
97+
given(channel.read(any()))
98+
.willAnswer(invocation -> {
9999
ByteBuffer buffer = invocation.getArgument(0);
100100
buffer.put("foo".getBytes(StandardCharsets.UTF_8));
101101
buffer.flip();
102102
return 3;
103103
})
104-
.thenThrow(new IOException());
104+
.willThrow(new IOException());
105105

106106
Flux<DataBuffer> result =
107107
DataBufferUtils.readByteChannel(() -> channel, this.bufferFactory, 3);
@@ -151,7 +151,7 @@ public void readAsynchronousFileChannelPosition() throws Exception {
151151
@Test
152152
public void readAsynchronousFileChannelError() throws Exception {
153153
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
154-
doAnswer(invocation -> {
154+
willAnswer(invocation -> {
155155
ByteBuffer byteBuffer = invocation.getArgument(0);
156156
byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8));
157157
byteBuffer.flip();
@@ -161,13 +161,13 @@ public void readAsynchronousFileChannelError() throws Exception {
161161
CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3);
162162
completionHandler.completed(3, dataBuffer);
163163
return null;
164-
}).doAnswer(invocation -> {
164+
}).willAnswer(invocation -> {
165165
DataBuffer dataBuffer = invocation.getArgument(2);
166166
CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3);
167167
completionHandler.failed(new IOException(), dataBuffer);
168168
return null;
169169
})
170-
.when(channel).read(any(), anyLong(), any(), any());
170+
.given(channel).read(any(), anyLong(), any(), any());
171171

172172
Flux<DataBuffer> result =
173173
DataBufferUtils.readAsynchronousFileChannel(() -> channel, this.bufferFactory, 3);
@@ -318,14 +318,14 @@ public void writeWritableByteChannelErrorInWrite() throws Exception {
318318
Flux<DataBuffer> flux = Flux.just(foo, bar);
319319

320320
WritableByteChannel channel = mock(WritableByteChannel.class);
321-
when(channel.write(any()))
322-
.thenAnswer(invocation -> {
321+
given(channel.write(any()))
322+
.willAnswer(invocation -> {
323323
ByteBuffer buffer = invocation.getArgument(0);
324324
int written = buffer.remaining();
325325
buffer.position(buffer.limit());
326326
return written;
327327
})
328-
.thenThrow(new IOException());
328+
.willThrow(new IOException());
329329

330330
Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel);
331331
StepVerifier.create(writeResult)
@@ -420,7 +420,7 @@ public void writeAsynchronousFileChannelErrorInWrite() throws Exception {
420420
Flux<DataBuffer> flux = Flux.just(foo, bar);
421421

422422
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
423-
doAnswer(invocation -> {
423+
willAnswer(invocation -> {
424424
ByteBuffer buffer = invocation.getArgument(0);
425425
long pos = invocation.getArgument(1);
426426
CompletionHandler<Integer, ByteBuffer> completionHandler = invocation.getArgument(3);
@@ -433,15 +433,14 @@ public void writeAsynchronousFileChannelErrorInWrite() throws Exception {
433433

434434
return null;
435435
})
436-
.doAnswer(invocation -> {
437-
ByteBuffer buffer = invocation.getArgument(0);
438-
CompletionHandler<Integer, ByteBuffer> completionHandler =
439-
invocation.getArgument(3);
440-
completionHandler.failed(new IOException(), buffer);
441-
return null;
442-
})
443-
.when(channel).write(isA(ByteBuffer.class), anyLong(), isA(ByteBuffer.class),
444-
isA(CompletionHandler.class));
436+
.willAnswer(invocation -> {
437+
ByteBuffer buffer = invocation.getArgument(0);
438+
CompletionHandler<Integer, ByteBuffer> completionHandler =
439+
invocation.getArgument(3);
440+
completionHandler.failed(new IOException(), buffer);
441+
return null;
442+
})
443+
.given(channel).write(isA(ByteBuffer.class), anyLong(), isA(ByteBuffer.class), isA(CompletionHandler.class));
445444

446445
Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel);
447446
StepVerifier.create(writeResult)
@@ -684,11 +683,11 @@ private static void assertReleased(DataBuffer dataBuffer) {
684683
@Test
685684
public void SPR16070() throws Exception {
686685
ReadableByteChannel channel = mock(ReadableByteChannel.class);
687-
when(channel.read(any()))
688-
.thenAnswer(putByte('a'))
689-
.thenAnswer(putByte('b'))
690-
.thenAnswer(putByte('c'))
691-
.thenReturn(-1);
686+
given(channel.read(any()))
687+
.willAnswer(putByte('a'))
688+
.willAnswer(putByte('b'))
689+
.willAnswer(putByte('c'))
690+
.willReturn(-1);
692691

693692
Flux<DataBuffer> read =
694693
DataBufferUtils.readByteChannel(() -> channel, this.bufferFactory, 1);

spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555
import static org.mockito.Mockito.never;
5656
import static org.mockito.Mockito.times;
5757
import static org.mockito.Mockito.verify;
58-
import static org.mockito.Mockito.when;
5958

6059
/**
6160
* @author Stephane Nicoll
@@ -149,7 +148,7 @@ public void payloadConversionLazilyInvoked() throws JMSException {
149148
@Test
150149
public void headerConversionLazilyInvoked() throws JMSException {
151150
javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
152-
when(jmsMessage.getPropertyNames()).thenThrow(new IllegalArgumentException("Header failure"));
151+
given(jmsMessage.getPropertyNames()).willThrow(new IllegalArgumentException("Header failure"));
153152
MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
154153
Message<?> message = listener.toMessagingMessage(jmsMessage);
155154

spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
import static org.mockito.ArgumentMatchers.any;
4848
import static org.mockito.ArgumentMatchers.anyLong;
4949
import static org.mockito.ArgumentMatchers.eq;
50-
import static org.mockito.Mockito.doAnswer;
50+
import static org.mockito.BDDMockito.willAnswer;
5151
import static org.mockito.Mockito.mock;
5252
import static org.mockito.Mockito.verify;
5353

@@ -80,10 +80,10 @@ public void setup() {
8080
public void sendWithTimeout() {
8181
SubscribableChannel channel = mock(SubscribableChannel.class);
8282
final AtomicReference<Message<?>> sent = new AtomicReference<>();
83-
doAnswer(invocation -> {
83+
willAnswer(invocation -> {
8484
sent.set(invocation.getArgument(0));
8585
return true;
86-
}).when(channel).send(any(Message.class), eq(30_000L));
86+
}).given(channel).send(any(Message.class), eq(30_000L));
8787
Message<?> message = MessageBuilder.withPayload("request")
8888
.setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L)
8989
.setHeader(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER, 1L)
@@ -99,10 +99,10 @@ public void sendWithTimeout() {
9999
public void sendWithTimeoutMutable() {
100100
SubscribableChannel channel = mock(SubscribableChannel.class);
101101
final AtomicReference<Message<?>> sent = new AtomicReference<>();
102-
doAnswer(invocation -> {
102+
willAnswer(invocation -> {
103103
sent.set(invocation.getArgument(0));
104104
return true;
105-
}).when(channel).send(any(Message.class), eq(30_000L));
105+
}).given(channel).send(any(Message.class), eq(30_000L));
106106
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
107107
accessor.setLeaveMutable(true);
108108
Message<?> message = new GenericMessage<>("request", accessor.getMessageHeaders());
@@ -140,10 +140,10 @@ public void sendAndReceiveTimeout() throws InterruptedException {
140140

141141
SubscribableChannel channel = mock(SubscribableChannel.class);
142142
MessageHandler handler = createLateReplier(latch, failure);
143-
doAnswer(invocation -> {
143+
willAnswer(invocation -> {
144144
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
145145
return true;
146-
}).when(channel).send(any(Message.class), anyLong());
146+
}).given(channel).send(any(Message.class), anyLong());
147147

148148
assertNull(this.template.convertSendAndReceive(channel, "request", String.class));
149149
assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
@@ -166,10 +166,10 @@ public void sendAndReceiveVariableTimeout() throws InterruptedException {
166166

167167
SubscribableChannel channel = mock(SubscribableChannel.class);
168168
MessageHandler handler = createLateReplier(latch, failure);
169-
doAnswer(invocation -> {
169+
willAnswer(invocation -> {
170170
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
171171
return true;
172-
}).when(channel).send(any(Message.class), anyLong());
172+
}).given(channel).send(any(Message.class), anyLong());
173173

174174
Message<?> message = MessageBuilder.withPayload("request")
175175
.setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L)
@@ -198,10 +198,10 @@ public void sendAndReceiveVariableTimeoutCustomHeaders() throws InterruptedExcep
198198

199199
SubscribableChannel channel = mock(SubscribableChannel.class);
200200
MessageHandler handler = createLateReplier(latch, failure);
201-
doAnswer(invocation -> {
201+
willAnswer(invocation -> {
202202
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
203203
return true;
204-
}).when(channel).send(any(Message.class), anyLong());
204+
}).given(channel).send(any(Message.class), anyLong());
205205

206206
Message<?> message = MessageBuilder.withPayload("request")
207207
.setHeader("sto", 30_000L)

spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/MessageMethodArgumentResolverTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636
import static org.junit.Assert.assertNotNull;
3737
import static org.junit.Assert.assertSame;
3838
import static org.junit.Assert.assertTrue;
39+
import static org.mockito.BDDMockito.given;
3940
import static org.mockito.Mockito.mock;
40-
import static org.mockito.Mockito.when;
4141

4242
/**
4343
* Unit tests for {@link MessageMethodArgumentResolver}.
@@ -96,7 +96,7 @@ public void resolveWithConversion() throws Exception {
9696
Message<String> message = MessageBuilder.withPayload("test").build();
9797
MethodParameter parameter = new MethodParameter(this.method, 1);
9898

99-
when(this.converter.fromMessage(message, Integer.class)).thenReturn(4);
99+
given(this.converter.fromMessage(message, Integer.class)).willReturn(4);
100100

101101
@SuppressWarnings("unchecked")
102102
Message<Integer> actual = (Message<Integer>) this.resolver.resolveArgument(parameter, message);

spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilderTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@
3030

3131
import static org.mockito.ArgumentMatchers.any;
3232
import static org.mockito.ArgumentMatchers.anyInt;
33+
import static org.mockito.BDDMockito.given;
3334
import static org.mockito.Mockito.mock;
3435
import static org.mockito.Mockito.verify;
3536
import static org.mockito.Mockito.verifyZeroInteractions;
36-
import static org.mockito.Mockito.when;
3737

3838
/**
3939
* Unit tests for {@link DefaultRSocketRequesterBuilder}.
@@ -48,7 +48,7 @@ public class DefaultRSocketRequesterBuilderTests {
4848
@Before
4949
public void setup() {
5050
this.transport = mock(ClientTransport.class);
51-
when(this.transport.connect(anyInt())).thenReturn(Mono.just(new MockConnection()));
51+
given(this.transport.connect(anyInt())).willReturn(Mono.just(new MockConnection()));
5252
}
5353

5454

spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@
4646
import static org.junit.Assert.assertTrue;
4747
import static org.mockito.ArgumentMatchers.any;
4848
import static org.mockito.ArgumentMatchers.eq;
49+
import static org.mockito.BDDMockito.given;
4950
import static org.mockito.Mockito.atLeast;
5051
import static org.mockito.Mockito.mock;
5152
import static org.mockito.Mockito.reset;
5253
import static org.mockito.Mockito.times;
5354
import static org.mockito.Mockito.verify;
5455
import static org.mockito.Mockito.verifyNoMoreInteractions;
55-
import static org.mockito.Mockito.when;
5656

5757
/**
5858
* Unit tests for {@link SimpleBrokerMessageHandler}.
@@ -186,7 +186,7 @@ public void startWithHeartbeatValueWithoutTaskScheduler() {
186186
@Test
187187
public void startAndStopWithHeartbeatValue() {
188188
ScheduledFuture future = mock(ScheduledFuture.class);
189-
when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).thenReturn(future);
189+
given(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).willReturn(future);
190190

191191
this.messageHandler.setTaskScheduler(this.taskScheduler);
192192
this.messageHandler.setHeartbeatValue(new long[] {15000, 16000});

0 commit comments

Comments
 (0)