Migrate to Mockito.mock(T...) where feasible

This commit is contained in:
Sam Brannen
2023-01-19 14:32:29 +01:00
parent c3d123fef7
commit c4c786596f
369 changed files with 2267 additions and 2707 deletions

View File

@@ -160,7 +160,7 @@ class GeneratedClassesTests {
@Test
@SuppressWarnings("unchecked")
void writeToInvokeTypeSpecCustomizer() throws IOException {
Consumer<TypeSpec.Builder> typeSpecCustomizer = mock(Consumer.class);
Consumer<TypeSpec.Builder> typeSpecCustomizer = mock();
this.generatedClasses.addForFeatureComponent("one", TestComponent.class, typeSpecCustomizer);
verifyNoInteractions(typeSpecCustomizer);
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles();

View File

@@ -57,7 +57,7 @@ class ReflectionHintsTests {
@Test
@SuppressWarnings("unchecked")
void registerTypeIfPresentIgnoresMissingClass() {
Consumer<TypeHint.Builder> hintBuilder = mock(Consumer.class);
Consumer<TypeHint.Builder> hintBuilder = mock();
this.reflectionHints.registerTypeIfPresent(null, "com.example.DoesNotExist", hintBuilder);
assertThat(this.reflectionHints.typeHints()).isEmpty();
verifyNoInteractions(hintBuilder);

View File

@@ -134,7 +134,7 @@ class ResourceHintsTests {
@Test
@SuppressWarnings("unchecked")
void registerIfPresentIgnoreMissingLocation() {
Consumer<ResourcePatternHints.Builder> hintBuilder = mock(Consumer.class);
Consumer<ResourcePatternHints.Builder> hintBuilder = mock();
this.resourceHints.registerPatternIfPresent(null, "location/does-not-exist/", hintBuilder);
assertThat(this.resourceHints.resourcePatternHints()).isEmpty();
verifyNoInteractions(hintBuilder);

View File

@@ -51,7 +51,7 @@ class ReflectiveRuntimeHintsRegistrarTests {
@Test
void shouldIgnoreNonAnnotatedType() {
RuntimeHints mock = mock(RuntimeHints.class);
RuntimeHints mock = mock();
this.registrar.registerRuntimeHints(mock, String.class);
verifyNoInteractions(mock);
}

View File

@@ -869,7 +869,7 @@ class ResolvableTypeTests {
@Test
void resolveTypeWithCustomVariableResolver() throws Exception {
VariableResolver variableResolver = mock(VariableResolver.class);
VariableResolver variableResolver = mock();
given(variableResolver.getSource()).willReturn(this);
ResolvableType longType = ResolvableType.forClass(Long.class);
given(variableResolver.resolveVariable(any())).willReturn(longType);

View File

@@ -118,7 +118,7 @@ class AttributeMethodsTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void isValidWhenDoesNotHaveTypeNotPresentExceptionReturnsTrue() {
ClassValue annotation = mock(ClassValue.class);
ClassValue annotation = mock();
given(annotation.value()).willReturn((Class) InputStream.class);
AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType());
assertThat(attributes.isValid(annotation)).isTrue();

View File

@@ -53,7 +53,7 @@ class MergedAnnotationsCollectionTests {
@Test
void createWhenAnnotationIsNotDirectlyPresentThrowsException() {
MergedAnnotation<?> annotation = mock(MergedAnnotation.class);
MergedAnnotation<?> annotation = mock();
given(annotation.isDirectlyPresent()).willReturn(false);
assertThatIllegalArgumentException().isThrownBy(() ->
MergedAnnotationsCollection.of(Collections.singleton(annotation)))
@@ -62,7 +62,7 @@ class MergedAnnotationsCollectionTests {
@Test
void createWhenAnnotationAggregateIndexIsNotZeroThrowsException() {
MergedAnnotation<?> annotation = mock(MergedAnnotation.class);
MergedAnnotation<?> annotation = mock();
given(annotation.isDirectlyPresent()).willReturn(true);
given(annotation.getAggregateIndex()).willReturn(1);
assertThatIllegalArgumentException().isThrownBy(() ->

View File

@@ -193,7 +193,7 @@ class PathResourceTests {
@Test
void getFileUnsupported() throws IOException {
Path path = mock(Path.class);
Path path = mock();
given(path.normalize()).willReturn(path);
given(path.toFile()).willThrow(new UnsupportedOperationException());
PathResource resource = new PathResource(path);

View File

@@ -101,7 +101,7 @@ class DataBufferUtilsTests extends AbstractDataBufferAllocatingTests {
void readByteChannelError(DataBufferFactory bufferFactory) throws Exception {
super.bufferFactory = bufferFactory;
ReadableByteChannel channel = mock(ReadableByteChannel.class);
ReadableByteChannel channel = mock();
given(channel.read(any()))
.willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
@@ -166,7 +166,7 @@ class DataBufferUtilsTests extends AbstractDataBufferAllocatingTests {
void readAsynchronousFileChannelError(DataBufferFactory bufferFactory) throws Exception {
super.bufferFactory = bufferFactory;
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
AsynchronousFileChannel channel = mock();
willAnswer(invocation -> {
ByteBuffer byteBuffer = invocation.getArgument(0);
byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8));
@@ -360,7 +360,7 @@ class DataBufferUtilsTests extends AbstractDataBufferAllocatingTests {
DataBuffer bar = stringBuffer("bar");
Flux<DataBuffer> flux = Flux.just(foo, bar);
WritableByteChannel channel = mock(WritableByteChannel.class);
WritableByteChannel channel = mock();
given(channel.write(any()))
.willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
@@ -470,7 +470,7 @@ class DataBufferUtilsTests extends AbstractDataBufferAllocatingTests {
DataBuffer bar = stringBuffer("bar");
Flux<DataBuffer> flux = Flux.just(foo, bar);
AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class);
AsynchronousFileChannel channel = mock();
willAnswer(invocation -> {
ByteBuffer buffer = invocation.getArgument(0);
long pos = invocation.getArgument(1);
@@ -777,7 +777,7 @@ class DataBufferUtilsTests extends AbstractDataBufferAllocatingTests {
void SPR16070(DataBufferFactory bufferFactory) throws Exception {
super.bufferFactory = bufferFactory;
ReadableByteChannel channel = mock(ReadableByteChannel.class);
ReadableByteChannel channel = mock();
given(channel.read(any()))
.willAnswer(putByte('a'))
.willAnswer(putByte('b'))

View File

@@ -18,8 +18,6 @@ package org.springframework.core.io.support;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
@@ -32,20 +30,20 @@ class ResourceRegionTests {
@Test
void shouldThrowExceptionWithNullResource() {
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(null, 0, 1));
assertThatIllegalArgumentException()
.isThrownBy(() -> new ResourceRegion(null, 0, 1));
}
@Test
void shouldThrowExceptionForNegativePosition() {
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(mock(Resource.class), -1, 1));
assertThatIllegalArgumentException()
.isThrownBy(() -> new ResourceRegion(mock(), -1, 1));
}
@Test
void shouldThrowExceptionForNegativeCount() {
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(mock(Resource.class), 0, -1));
assertThatIllegalArgumentException()
.isThrownBy(() -> new ResourceRegion(mock(), 0, -1));
}
}

View File

@@ -107,7 +107,7 @@ class SpringFactoriesLoaderTests {
@Test
void loadWithLoggingFailureHandlerWhenIncompatibleTypeReturnsEmptyList() {
Log logger = mock(Log.class);
Log logger = mock();
FailureHandler failureHandler = FailureHandler.logging(logger);
List<String> factories = SpringFactoriesLoader.forDefaultResourceLocation().load(String.class, failureHandler);
assertThat(factories).isEmpty();
@@ -138,7 +138,7 @@ class SpringFactoriesLoaderTests {
@Test
void loadWithLoggingFailureHandlerWhenMissingArgumentDropsItem() {
Log logger = mock(Log.class);
Log logger = mock();
FailureHandler failureHandler = FailureHandler.logging(logger);
List<DummyFactory> factories = SpringFactoriesLoader.forDefaultResourceLocation(LimitedClassLoader.multipleArgumentFactories)
.load(DummyFactory.class, failureHandler);
@@ -202,7 +202,7 @@ class SpringFactoriesLoaderTests {
@Test
void loggingReturnsHandlerThatLogs() {
Log logger = mock(Log.class);
Log logger = mock();
FailureHandler handler = FailureHandler.logging(logger);
RuntimeException cause = new RuntimeException();
handler.handleFailure(DummyFactory.class, MyDummyFactory1.class.getName(), cause);

View File

@@ -33,9 +33,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class CompositeLogTests {
private final Log logger1 = mock(Log.class);
private final Log logger1 = mock();
private final Log logger2 = mock(Log.class);
private final Log logger2 = mock();
private final CompositeLog compositeLog = new CompositeLog(Arrays.asList(logger1, logger2));

View File

@@ -100,7 +100,7 @@ class StreamUtilsTests {
@Test
void nonClosingInputStream() throws Exception {
InputStream source = mock(InputStream.class);
InputStream source = mock();
InputStream nonClosing = StreamUtils.nonClosing(source);
nonClosing.read();
nonClosing.read(bytes);
@@ -115,7 +115,7 @@ class StreamUtilsTests {
@Test
void nonClosingOutputStream() throws Exception {
OutputStream source = mock(OutputStream.class);
OutputStream source = mock();
OutputStream nonClosing = StreamUtils.nonClosing(source);
nonClosing.write(1);
nonClosing.write(bytes);

View File

@@ -43,7 +43,7 @@ class UnmodifiableMultiValueMapTests {
@Test
@SuppressWarnings("unchecked")
void delegation() {
MultiValueMap<String, String> mock = mock(MultiValueMap.class);
MultiValueMap<String, String> mock = mock();
UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(mock);
given(mock.size()).willReturn(1);
@@ -101,8 +101,8 @@ class UnmodifiableMultiValueMapTests {
@Test
@SuppressWarnings("unchecked")
void entrySetDelegation() {
MultiValueMap<String, String> mockMap = mock(MultiValueMap.class);
Set<Map.Entry<String, List<String>>> mockSet = mock(Set.class);
MultiValueMap<String, String> mockMap = mock();
Set<Map.Entry<String, List<String>>> mockSet = mock();
given(mockMap.entrySet()).willReturn(mockSet);
Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<>(mockMap).entrySet();
@@ -112,7 +112,7 @@ class UnmodifiableMultiValueMapTests {
given(mockSet.isEmpty()).willReturn(false);
assertThat(set.isEmpty()).isFalse();
Map.Entry<String, List<String>> mockedEntry = mock(Map.Entry.class);
Map.Entry<String, List<String>> mockedEntry = mock();
given(mockSet.contains(mockedEntry)).willReturn(true);
assertThat(set.contains(mockedEntry)).isTrue();
@@ -120,7 +120,7 @@ class UnmodifiableMultiValueMapTests {
given(mockSet.containsAll(mockEntries)).willReturn(true);
assertThat(set.containsAll(mockEntries)).isTrue();
Iterator<Map.Entry<String, List<String>>> mockIterator = mock(Iterator.class);
Iterator<Map.Entry<String, List<String>>> mockIterator = mock();
given(mockSet.iterator()).willReturn(mockIterator);
given(mockIterator.hasNext()).willReturn(false);
assertThat(set.iterator()).isExhausted();
@@ -143,8 +143,8 @@ class UnmodifiableMultiValueMapTests {
@Test
@SuppressWarnings("unchecked")
void valuesDelegation() {
MultiValueMap<String, String> mockMap = mock(MultiValueMap.class);
Collection<List<String>> mockValues = mock(Collection.class);
MultiValueMap<String, String> mockMap = mock();
Collection<List<String>> mockValues = mock();
given(mockMap.values()).willReturn(mockValues);
Collection<List<String>> values = new UnmodifiableMultiValueMap<>(mockMap).values();

View File

@@ -20,7 +20,6 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -33,22 +32,17 @@ import static org.mockito.Mockito.mock;
@SuppressWarnings("deprecation")
class FutureAdapterTests {
private FutureAdapter<String, Integer> adapter;
private Future<Integer> adaptee;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
adaptee = mock(Future.class);
adapter = new FutureAdapter<>(adaptee) {
@Override
protected String adapt(Integer adapteeResult) throws ExecutionException {
return adapteeResult.toString();
}
};
}
private Future<Integer> adaptee = mock();
private FutureAdapter<String, Integer> adapter = new FutureAdapter<>(adaptee) {
@Override
protected String adapt(Integer adapteeResult) throws ExecutionException {
return adapteeResult.toString();
}
};
@Test
void cancel() {

View File

@@ -94,8 +94,8 @@ class ListenableFutureTaskTests {
final String s = "Hello World";
Callable<String> callable = () -> s;
SuccessCallback<String> successCallback = mock(SuccessCallback.class);
FailureCallback failureCallback = mock(FailureCallback.class);
SuccessCallback<String> successCallback = mock();
FailureCallback failureCallback = mock();
ListenableFutureTask<String> task = new ListenableFutureTask<>(callable);
task.addCallback(successCallback, failureCallback);
task.run();
@@ -115,20 +115,22 @@ class ListenableFutureTaskTests {
throw ex;
};
SuccessCallback<String> successCallback = mock(SuccessCallback.class);
FailureCallback failureCallback = mock(FailureCallback.class);
SuccessCallback<String> successCallback = mock();
FailureCallback failureCallback = mock();
ListenableFutureTask<String> task = new ListenableFutureTask<>(callable);
task.addCallback(successCallback, failureCallback);
task.run();
verify(failureCallback).onFailure(ex);
verifyNoInteractions(successCallback);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task::get)
.satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s));
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task.completable()::get)
.satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s));
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(task::get)
.havingCause()
.withMessage(s);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(task.completable()::get)
.havingCause()
.withMessage(s);
}
}

View File

@@ -361,7 +361,7 @@ class SettableListenableFutureTests {
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelDoesNotNotifyCallbacksOnSet() {
ListenableFutureCallback callback = mock(ListenableFutureCallback.class);
ListenableFutureCallback callback = mock();
settableListenableFuture.addCallback(callback);
settableListenableFuture.cancel(true);
@@ -378,7 +378,7 @@ class SettableListenableFutureTests {
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelDoesNotNotifyCallbacksOnSetException() {
ListenableFutureCallback callback = mock(ListenableFutureCallback.class);
ListenableFutureCallback callback = mock();
settableListenableFuture.addCallback(callback);
settableListenableFuture.cancel(true);

View File

@@ -170,7 +170,7 @@ abstract class AbstractStaxXMLReaderTests {
private LexicalHandler mockLexicalHandler() throws Exception {
LexicalHandler lexicalHandler = mock(LexicalHandler.class);
LexicalHandler lexicalHandler = mock();
willAnswer(new CopyCharsAnswer()).given(lexicalHandler).comment(any(char[].class), anyInt(), anyInt());
return lexicalHandler;
}
@@ -180,7 +180,7 @@ abstract class AbstractStaxXMLReaderTests {
}
protected final ContentHandler mockContentHandler() throws Exception {
ContentHandler contentHandler = mock(ContentHandler.class);
ContentHandler contentHandler = mock();
willAnswer(new CopyCharsAnswer()).given(contentHandler).characters(any(char[].class), anyInt(), anyInt());
willAnswer(new CopyCharsAnswer()).given(contentHandler).ignorableWhitespace(any(char[].class), anyInt(), anyInt());
willAnswer(invocation -> {

View File

@@ -48,7 +48,7 @@ class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTests {
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(CONTENT));
eventReader.nextTag(); // skip to root
StaxEventXMLReader xmlReader = new StaxEventXMLReader(eventReader);
ContentHandler contentHandler = mock(ContentHandler.class);
ContentHandler contentHandler = mock();
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource());
verify(contentHandler).startDocument();

View File

@@ -55,7 +55,7 @@ class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTests {
assertThat(streamReader.getName()).as("Invalid element").isEqualTo(new QName("http://springframework.org/spring-ws", "child"));
StaxStreamXMLReader xmlReader = new StaxStreamXMLReader(streamReader);
ContentHandler contentHandler = mock(ContentHandler.class);
ContentHandler contentHandler = mock();
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource());