diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java index 7e6e8f2bbca..0ac01fbc4a6 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java @@ -59,6 +59,7 @@ import org.springframework.integration.json.ObjectToJsonTransformer; import org.springframework.integration.mapping.support.JsonHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.MessageTransformingHandler; import org.springframework.integration.transformer.Transformer; import org.springframework.messaging.Message; @@ -86,7 +87,7 @@ * * @since 3.0 */ -public class InboundEndpointTests { +public class InboundEndpointTests implements TestApplicationContextAware { @Test public void testInt2809JavaTypePropertiesToAmqp() throws Exception { @@ -254,6 +255,7 @@ public Object fromMessage(org.springframework.amqp.core.Message message) throws } }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); org.springframework.amqp.core.Message message = mock(org.springframework.amqp.core.Message.class); MessageProperties props = new MessageProperties(); @@ -310,6 +312,7 @@ public Object fromMessage(org.springframework.amqp.core.Message message) throws } }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); org.springframework.amqp.core.Message message = mock(org.springframework.amqp.core.Message.class); MessageProperties props = new MessageProperties(); @@ -348,6 +351,7 @@ public void testRetryWithinOnMessageAdapter() throws Exception { ErrorMessageSendingRecoverer recoveryCallback = new ErrorMessageSendingRecoverer(errors); recoveryCallback.setErrorMessageStrategy(new AmqpMessageHeaderErrorMessageStrategy()); adapter.setRecoveryCallback(recoveryCallback); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()) @@ -380,6 +384,7 @@ public void testRetryWithMessageRecovererOnMessageAdapter() throws Exception { recoveredError.set(cause); recoveredLatch.countDown(); }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); org.springframework.amqp.core.Message amqpMessage = @@ -409,6 +414,7 @@ public void testRetryWithinOnMessageGateway() throws Exception { ErrorMessageSendingRecoverer recoveryCallback = new ErrorMessageSendingRecoverer(errors); recoveryCallback.setErrorMessageStrategy(new AmqpMessageHeaderErrorMessageStrategy()); adapter.setRecoveryCallback(recoveryCallback); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()) @@ -441,6 +447,7 @@ public void testRetryWithMessageRecovererOnMessageGateway() throws Exception { recoveredError.set(cause); recoveredLatch.countDown(); }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); org.springframework.amqp.core.Message amqpMessage = @@ -467,6 +474,7 @@ public void testBatchAdapter() throws Exception { AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(container); QueueChannel out = new QueueChannel(); adapter.setOutputChannel(out); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); SimpleBatchingStrategy bs = new SimpleBatchingStrategy(2, 10_000, 10_000L); @@ -493,6 +501,7 @@ public void testBatchGateway() throws Exception { gateway.setRequestChannel(out); gateway.setBindSourceMessage(true); gateway.setReplyTimeout(0); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); SimpleBatchingStrategy bs = new SimpleBatchingStrategy(2, 10_000, 10_000L); @@ -521,6 +530,7 @@ public void testConsumerBatchExtract() { adapter.setOutputChannel(out); adapter.setBatchMode(BatchMode.EXTRACT_PAYLOADS_WITH_HEADERS); adapter.setHeaderNameForBatchedHeaders("some_batch_headers"); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareBatchMessageListener listener = (ChannelAwareBatchMessageListener) container.getMessageListener(); MessageProperties messageProperties = new MessageProperties(); @@ -544,6 +554,7 @@ public void testConsumerBatch() { AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(container); QueueChannel out = new QueueChannel(); adapter.setOutputChannel(out); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareBatchMessageListener listener = (ChannelAwareBatchMessageListener) container.getMessageListener(); MessageProperties messageProperties = new MessageProperties(); @@ -564,6 +575,7 @@ public void testConsumerBatchAndWrongMessageRecoverer() { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(mock()); container.setConsumerBatchEnabled(true); AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(container); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.setRetryTemplate(new RetryTemplate()); adapter.setMessageRecoverer((message, cause) -> { }); @@ -580,6 +592,7 @@ public void testExclusiveRecover() { adapter.setMessageRecoverer((message, cause) -> { }); adapter.setRecoveryCallback(context -> null); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalStateException() .isThrownBy(adapter::afterPropertiesSet) .withMessageStartingWith("Only one of 'recoveryCallback' or 'messageRecoverer' may be provided, " + @@ -609,6 +622,7 @@ public Object fromMessage(org.springframework.amqp.core.Message message) throws }); adapter.setBatchMode(BatchMode.EXTRACT_PAYLOADS); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); @@ -665,6 +679,7 @@ public Object fromMessage(org.springframework.amqp.core.Message message) throws } }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); @@ -709,6 +724,7 @@ public void testRetryWithinOnMessageAdapterConsumerBatch() { adapter.setRetryTemplate(new RetryTemplate()); QueueChannel errors = new QueueChannel(); ErrorMessageSendingRecoverer recoveryCallback = new ErrorMessageSendingRecoverer(errors); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); recoveryCallback.setErrorMessageStrategy(new AmqpMessageHeaderErrorMessageStrategy()); adapter.setRecoveryCallback(recoveryCallback); adapter.afterPropertiesSet(); @@ -761,6 +777,7 @@ public void testRetryWithMessageRecovererOnMessageAdapterConsumerBatch() throws recoveredError.set(cause); recoveredLatch.countDown(); }); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); ChannelAwareBatchMessageListener listener = (ChannelAwareBatchMessageListener) container.getMessageListener(); MessageProperties messageProperties = new MessageProperties(); diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java index ff2f00d8436..f975bf1ecf8 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java @@ -37,6 +37,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.mapping.support.JsonHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.GenericMessage; import org.springframework.scheduling.TaskScheduler; @@ -59,7 +60,7 @@ * * @since 3.0 */ -public class OutboundEndpointTests { +public class OutboundEndpointTests implements TestApplicationContextAware { @Test public void testDelayExpression() { @@ -75,6 +76,7 @@ public void testDelayExpression() { endpoint.setRoutingKey("bar"); endpoint.setDelayExpressionString("42"); endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); endpoint.handleMessage(new GenericMessage<>("foo")); ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); @@ -109,6 +111,7 @@ public void testAsyncDelayExpression() { gateway.setDelayExpressionString("42"); gateway.setBeanFactory(mock(BeanFactory.class)); gateway.setOutputChannel(new NullChannel()); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); gateway.start(); ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); diff --git a/spring-integration-camel/src/test/java/org/springframework/integration/camel/dsl/CamelDslTests.java b/spring-integration-camel/src/test/java/org/springframework/integration/camel/dsl/CamelDslTests.java index 34ca1f15039..8f970b5a6c8 100644 --- a/spring-integration-camel/src/test/java/org/springframework/integration/camel/dsl/CamelDslTests.java +++ b/spring-integration-camel/src/test/java/org/springframework/integration/camel/dsl/CamelDslTests.java @@ -35,6 +35,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; /** * @author Artem Bilan @@ -51,7 +52,9 @@ public class CamelDslTests { @Test void sendAndReceiveCamelRoute() { - String result = new MessagingTemplate().convertSendAndReceive(this.input, "apache camel", String.class); + MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(mock()); + String result = messagingTemplate.convertSendAndReceive(this.input, "apache camel", String.class); assertThat(result).isEqualTo("___APACHE CAMEL___"); } diff --git a/spring-integration-camel/src/test/java/org/springframework/integration/camel/outbound/CamelMessageHandlerTests.java b/spring-integration-camel/src/test/java/org/springframework/integration/camel/outbound/CamelMessageHandlerTests.java index 5934e3acb99..53830e0ffae 100644 --- a/spring-integration-camel/src/test/java/org/springframework/integration/camel/outbound/CamelMessageHandlerTests.java +++ b/spring-integration-camel/src/test/java/org/springframework/integration/camel/outbound/CamelMessageHandlerTests.java @@ -26,26 +26,25 @@ import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.camel.support.CamelHeaderMapper; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.expression.FunctionExpression; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Artem Bilan * * @since 6.0 */ -public class CamelMessageHandlerTests extends CamelTestSupport { +public class CamelMessageHandlerTests extends CamelTestSupport implements TestApplicationContextAware { @Test void inOnlyPatternSyncMessageHandler() throws InterruptedException { @@ -60,7 +59,7 @@ void inOnlyPatternSyncMessageHandler() throws InterruptedException { CamelMessageHandler camelMessageHandler = new CamelMessageHandler(template()); camelMessageHandler.setEndpointUri("direct:simple"); - camelMessageHandler.setBeanFactory(mock(BeanFactory.class)); + camelMessageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); camelMessageHandler.afterPropertiesSet(); camelMessageHandler.handleMessage(messageUnderTest); @@ -97,7 +96,7 @@ void inOutPatternSyncMessageHandlerWithNoRequestHeadersButReplyHeaders() throws camelMessageHandler.setEndpointUriExpression(new FunctionExpression<>(m -> "direct:simple")); camelMessageHandler.setExchangePatternExpression(spelExpressionParser.parseExpression("headers.exchangePattern")); camelMessageHandler.setHeaderMapper(headerMapper); - camelMessageHandler.setBeanFactory(mock(BeanFactory.class)); + camelMessageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); camelMessageHandler.afterPropertiesSet(); camelMessageHandler.handleMessage(messageUnderTest); @@ -128,7 +127,7 @@ void inOnlyPatternAsyncMessageHandlerWithException() throws InterruptedException CamelMessageHandler camelMessageHandler = new CamelMessageHandler(template()); camelMessageHandler.setEndpointUri("direct:simple"); - camelMessageHandler.setBeanFactory(mock(BeanFactory.class)); + camelMessageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); camelMessageHandler.setAsync(true); camelMessageHandler.afterPropertiesSet(); @@ -161,7 +160,7 @@ void inOutPatternAsyncMessageHandler() throws InterruptedException { producerTemplate.setDefaultEndpointUri("direct:simple"); CamelMessageHandler camelMessageHandler = new CamelMessageHandler(producerTemplate); camelMessageHandler.setExchangePattern(ExchangePattern.InOut); - camelMessageHandler.setBeanFactory(mock(BeanFactory.class)); + camelMessageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); camelMessageHandler.setAsync(true); camelMessageHandler.afterPropertiesSet(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/acks/package-info.java b/spring-integration-core/src/main/java/org/springframework/integration/acks/package-info.java index f341052a884..c263244d02d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/acks/package-info.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/acks/package-info.java @@ -1,5 +1,5 @@ /** * Provides classes related to message acknowledgment. */ -@org.springframework.lang.NonNullApi +@org.jspecify.annotations.NullMarked package org.springframework.integration.acks; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractAggregatingMessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractAggregatingMessageGroupProcessor.java index 53c78a2de5a..e75755ad006 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractAggregatingMessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractAggregatingMessageGroupProcessor.java @@ -56,6 +56,7 @@ public abstract class AbstractAggregatingMessageGroupProcessor implements Messag private boolean messageBuilderFactorySet; + @SuppressWarnings("NullAway.Init") private BeanFactory beanFactory; @Override diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java index 4f2492e3f74..547a6e2db84 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java @@ -125,8 +125,10 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP private boolean releaseStrategySet; + @Nullable private MessageChannel discardChannel; + @Nullable private String discardChannelName; private boolean sendPartialResultOnExpiry; @@ -143,18 +145,23 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP private boolean releasePartialSequences; + @Nullable private Expression groupTimeoutExpression; + @Nullable private List forceReleaseAdviceChain; private long expireTimeout; + @Nullable private Duration expireDuration; private MessageGroupProcessor forceReleaseProcessor = new ForceReleaseMessageGroupProcessor(); + @SuppressWarnings("NullAway.Init") private EvaluationContext evaluationContext; + @Nullable private ApplicationEventPublisher applicationEventPublisher; private boolean expireGroupsUponTimeout = true; @@ -165,10 +172,11 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP private volatile boolean running; + @Nullable private BiFunction, String, String> groupConditionSupplier; public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, - CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { + @Nullable CorrelationStrategy correlationStrategy, @Nullable ReleaseStrategy releaseStrategy) { Assert.notNull(processor, "'processor' must not be null"); Assert.notNull(store, "'store' must not be null"); @@ -482,7 +490,8 @@ protected BiFunction, String, String> getGroupConditionSupplier() { } @Override - public MessageChannel getDiscardChannel() { + @Nullable + public MessageChannel getDiscardChannel() { String channelName = this.discardChannelName; if (channelName == null && this.discardChannel == null) { channelName = IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME; @@ -504,6 +513,7 @@ public MessageChannel getDiscardChannel() { return this.discardChannel; } + @Nullable protected String getDiscardChannelName() { return this.discardChannelName; } @@ -532,6 +542,7 @@ protected boolean isReleasePartialSequences() { return this.releasePartialSequences; } + @Nullable protected Expression getGroupTimeoutExpression() { return this.groupTimeoutExpression; } @@ -753,7 +764,7 @@ private void discardMessage(Message message) { * @param group The group. * @param completedMessages The completed messages. */ - protected abstract void afterRelease(MessageGroup group, Collection> completedMessages); + protected abstract void afterRelease(MessageGroup group, @Nullable Collection> completedMessages); /** * Subclasses may override if special action is needed because the group was released or discarded @@ -912,14 +923,12 @@ protected void expireGroup(Object correlationKey, MessageGroup group, Lock lock) } protected void completeGroup(Object correlationKey, MessageGroup group, Lock lock) { - Message first = null; - if (group != null) { - first = group.getOne(); - } + Message first = group.getOne(); completeGroup(first, correlationKey, group, lock); } @SuppressWarnings("unchecked") + @Nullable protected Collection> completeGroup(Message message, Object correlationKey, MessageGroup group, Lock lock) { @@ -929,6 +938,7 @@ protected Collection> completeGroup(Message message, Object correl this.logger.debug(() -> "Completing group with correlationKey [" + correlationKey + "]"); result = this.outputProcessor.processMessageGroup(group); + Assert.state(result != null, "The processorMessageGroup returned a null result. Null result is not expected."); if (isResultCollectionOfMessages(result)) { partialSequence = (Collection>) result; } @@ -976,6 +986,7 @@ private static boolean isResultCollectionOfMessages(Object result) { return false; } + @Nullable protected Object obtainGroupTimeout(MessageGroup group) { if (this.groupTimeoutExpression != null) { Object timeout = this.groupTimeoutExpression.getValue(this.evaluationContext, group); @@ -1050,6 +1061,7 @@ public void purgeOrphanedGroups() { protected static class SequenceAwareMessageGroup extends SimpleMessageGroup { + @Nullable private final SimpleMessageGroup sourceGroup; public SequenceAwareMessageGroup(MessageGroup messageGroup) { @@ -1112,6 +1124,7 @@ private class ForceReleaseMessageGroupProcessor implements MessageGroupProcessor } @Override + @Nullable public Object processMessageGroup(MessageGroup group) { forceComplete(group); return null; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AggregatingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AggregatingMessageHandler.java index 31e844f72ad..e39545aaf94 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AggregatingMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AggregatingMessageHandler.java @@ -18,6 +18,8 @@ import java.util.Collection; +import org.jspecify.annotations.Nullable; + import org.springframework.integration.IntegrationPatternType; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.store.MessageGroupStore; @@ -95,7 +97,7 @@ protected boolean shouldSplitOutput(Iterable reply) { * @param completedMessages The completed messages. Ignored in this implementation. */ @Override - protected void afterRelease(MessageGroup messageGroup, Collection> completedMessages) { + protected void afterRelease(MessageGroup messageGroup, @Nullable Collection> completedMessages) { Object groupId = messageGroup.getGroupId(); MessageGroupStore messageStore = getMessageStore(); messageStore.completeGroup(groupId); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java index 15c01bac78a..1d9082f4b38 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java @@ -68,8 +68,10 @@ public class BarrierMessageHandler extends AbstractReplyProducingMessageHandler private final MessageGroupProcessor messageGroupProcessor; + @Nullable private String discardChannelName; + @Nullable private MessageChannel discardChannel; /** @@ -159,7 +161,7 @@ public BarrierMessageHandler(long requestTimeout, long triggerTimeout, Correlati * @since 5.4 */ public BarrierMessageHandler(long requestTimeout, long triggerTimeout, MessageGroupProcessor outputProcessor, - CorrelationStrategy correlationStrategy) { + @Nullable CorrelationStrategy correlationStrategy) { Assert.notNull(outputProcessor, "'messageGroupProcessor' cannot be null"); this.messageGroupProcessor = outputProcessor; @@ -218,6 +220,7 @@ public IntegrationPatternType getIntegrationPatternType() { } @Override + @Nullable protected Object handleRequestMessage(Message requestMessage) { Object key = this.correlationStrategy.getCorrelationKey(requestMessage); if (key == null) { @@ -247,6 +250,7 @@ protected Object handleRequestMessage(Message requestMessage) { return null; } + @Nullable private Object processRelease(Object key, Message requestMessage, Message releaseMessage) { this.suspensions.remove(key); if (releaseMessage.getPayload() instanceof Throwable) { @@ -266,6 +270,7 @@ private Object processRelease(Object key, Message requestMessage, Message * @param releaseMessage the release message. * @return the result. */ + @Nullable protected Object buildResult(Object key, Message requestMessage, Message releaseMessage) { SimpleMessageGroup group = new SimpleMessageGroup(key); group.add(requestMessage); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelatingMessageBarrier.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelatingMessageBarrier.java index 397bd254fd1..10d1bddf485 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelatingMessageBarrier.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelatingMessageBarrier.java @@ -20,6 +20,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.jspecify.annotations.Nullable; + import org.springframework.core.log.LogMessage; import org.springframework.integration.core.MessageSource; import org.springframework.integration.handler.AbstractMessageHandler; @@ -27,6 +29,7 @@ import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.messaging.Message; +import org.springframework.util.Assert; /** * This Endpoint serves as a barrier for messages that should not be processed yet. The decision when a message can be @@ -58,8 +61,10 @@ public class CorrelatingMessageBarrier extends AbstractMessageHandler implements private final MessageGroupStore store; + @Nullable private CorrelationStrategy correlationStrategy; + @Nullable private ReleaseStrategy releaseStrategy; public CorrelatingMessageBarrier() { @@ -86,9 +91,11 @@ public void setReleaseStrategy(ReleaseStrategy releaseStrategy) { this.releaseStrategy = releaseStrategy; } + @SuppressWarnings("NullAway") @Override protected void handleMessageInternal(Message message) { Object correlationKey = this.correlationStrategy.getCorrelationKey(message); + Assert.notNull(correlationKey, "The correlation key is required"); Object lock = getLock(correlationKey); synchronized (lock) { this.store.addMessagesToGroup(correlationKey, message); @@ -101,8 +108,9 @@ private Object getLock(Object correlationKey) { return existingLock == null ? correlationKey : existingLock; } - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked", "NullAway"}) @Override + @Nullable public Message receive() { for (Object key : this.correlationLocks.keySet()) { Object lock = getLock(key); @@ -111,7 +119,6 @@ public Message receive() { //group might be removed by another thread if (group != null && this.releaseStrategy.canRelease(group)) { Message nextMessage = null; - Iterator> messages = group.getMessages().iterator(); if (messages.hasNext()) { nextMessage = messages.next(); @@ -128,6 +135,13 @@ public Message receive() { return null; } + @Override + protected void onInit() { + super.onInit(); + Assert.notNull(this.releaseStrategy, "'releaseStrategy' must not be null"); + Assert.notNull(this.correlationStrategy, "'correlationStrategy' must not be null"); + } + private void remove(Object key) { this.correlationLocks.remove(key); this.store.removeMessageGroup(key); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelationStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelationStrategy.java index 86c0baa88c1..5e8d211031e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelationStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/CorrelationStrategy.java @@ -16,6 +16,8 @@ package org.springframework.integration.aggregator; +import org.jspecify.annotations.Nullable; + import org.springframework.messaging.Message; /** @@ -35,6 +37,7 @@ public interface CorrelationStrategy { * @param message The message. * @return The correlation key. */ + @Nullable Object getCorrelationKey(Message message); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/DelegatingMessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/DelegatingMessageGroupProcessor.java index 10047c8b196..642a0b06183 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/DelegatingMessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/DelegatingMessageGroupProcessor.java @@ -61,6 +61,7 @@ public class DelegatingMessageGroupProcessor implements MessageGroupProcessor, B private volatile boolean messageBuilderFactorySet; + @SuppressWarnings("NullAway.Init") private BeanFactory beanFactory; public DelegatingMessageGroupProcessor(MessageGroupProcessor delegate, diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategy.java index 22b45d2b3fd..8c6a1ace9bd 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategy.java @@ -16,6 +16,8 @@ package org.springframework.integration.aggregator; +import org.jspecify.annotations.Nullable; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -51,7 +53,7 @@ public ExpressionEvaluatingCorrelationStrategy(Expression expression) { this.processor = new ExpressionEvaluatingMessageProcessor<>(expression, Object.class); } - public Object getCorrelationKey(Message message) { + public @Nullable Object getCorrelationKey(Message message) { return this.processor.processMessage(message); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessor.java index ef0b9e8c1e3..93c0653fa81 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessor.java @@ -21,6 +21,7 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.ConversionService; import org.springframework.integration.store.MessageGroup; +import org.springframework.util.Assert; /** * A {@link MessageGroupProcessor} implementation that evaluates a SpEL expression. The SpEL context root is the list of @@ -59,7 +60,9 @@ public void setExpectedType(Class expectedType) { */ @Override protected Object aggregatePayloads(MessageGroup group, Map headers) { - return this.processor.process(group.getMessages()); + Object object = this.processor.process(group.getMessages()); + Assert.state(object != null, "The process returned a null result. Null result is not expected."); + return object; } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageListProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageListProcessor.java index 2f215cc56ea..bdfc86bf049 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageListProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageListProcessor.java @@ -18,6 +18,8 @@ import java.util.Collection; +import org.jspecify.annotations.Nullable; + import org.springframework.expression.Expression; import org.springframework.expression.ParseException; import org.springframework.integration.util.AbstractExpressionEvaluator; @@ -37,6 +39,7 @@ public class ExpressionEvaluatingMessageListProcessor extends AbstractExpression private final Expression expression; + @Nullable private volatile Class expectedType = null; /** @@ -102,7 +105,9 @@ public void setExpectedType(Class expectedType) { */ @Override public Object process(Collection> messages) { - return this.evaluateExpression(this.expression, messages, this.expectedType); + Object object = this.evaluateExpression(this.expression, messages, this.expectedType); + Assert.state(object != null, "The evaluation of the expression returned a null. Null result is not expected: " + this.expression); + return object; } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandler.java index 6bb73c1b9af..15e23cea736 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandler.java @@ -17,10 +17,12 @@ package org.springframework.integration.aggregator; import java.time.Duration; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Predicate; +import org.jspecify.annotations.Nullable; import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; @@ -62,18 +64,23 @@ public class FluxAggregatorMessageHandler extends AbstractMessageProducingHandle private CorrelationStrategy correlationStrategy = new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID); + @Nullable private Predicate> boundaryTrigger; - private Function, Integer> windowSizeFunction = FluxAggregatorMessageHandler::sequenceSizeHeader; + private Function, @Nullable Integer> windowSizeFunction = FluxAggregatorMessageHandler::sequenceSizeHeader; + @Nullable private Function>, Flux>>> windowConfigurer; + @Nullable private Duration windowTimespan; private Function>, Mono>> combineFunction = this::messageForWindowFlux; + @SuppressWarnings("NullAway.Init") private FluxSink> sink; + @Nullable private volatile Disposable subscription; /** @@ -90,7 +97,9 @@ public FluxAggregatorMessageHandler() { } private Object groupBy(Message message) { - return this.correlationStrategy.getCorrelationKey(message); + Object result = this.correlationStrategy.getCorrelationKey(message); + Assert.notNull(result, "Correlation key cannot be null"); + return result; } private Flux> releaseBy(Flux> groupFlux) { @@ -106,7 +115,7 @@ private Flux>> applyWindowOptions(Flux> groupFlux) { return groupFlux .switchOnFirst((signal, group) -> { if (signal.hasValue()) { - Integer maxSize = this.windowSizeFunction.apply(signal.get()); + Integer maxSize = this.windowSizeFunction.apply(Objects.requireNonNull(signal.get())); if (maxSize != null) { if (this.windowTimespan != null) { return group.windowTimeout(maxSize, this.windowTimespan); @@ -185,13 +194,13 @@ public void setWindowSize(int windowSize) { /** * Specify a {@link Function} to determine a size for windows to close against the first message in group. * Tne result of the function can be combined with the {@link #setWindowTimespan(Duration)}. - * By default an {@link IntegrationMessageHeaderAccessor#SEQUENCE_SIZE} header is consulted. + * By default, an {@link IntegrationMessageHeaderAccessor#SEQUENCE_SIZE} header is consulted. * @param windowSizeFunction the {@link Function} to use to determine a window size * against a first message in the group. * @see Flux#window(int) * @see Flux#windowTimeout(int, Duration) */ - public void setWindowSizeFunction(Function, Integer> windowSizeFunction) { + public void setWindowSizeFunction(Function, @Nullable Integer> windowSizeFunction) { Assert.notNull(windowSizeFunction, "'windowSizeFunction' must not be null"); this.windowSizeFunction = windowSizeFunction; } @@ -243,8 +252,9 @@ public void start() { @Override public void stop() { - if (this.subscribed.compareAndSet(true, false) && this.subscription != null) { - this.subscription.dispose(); + Disposable subscriptionToDispose = this.subscription; + if (this.subscribed.compareAndSet(true, false) && subscriptionToDispose != null) { + subscriptionToDispose.dispose(); } } @@ -277,7 +287,7 @@ private Mono> messageForWindowFlux(Flux> messageFlux) { .build()); } - private static Integer sequenceSizeHeader(Message message) { + private static @Nullable Integer sequenceSizeHeader(Message message) { return message.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE, Integer.class); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java index c0dbcb6ad4a..aa0e272845d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java @@ -16,6 +16,8 @@ package org.springframework.integration.aggregator; +import org.jspecify.annotations.Nullable; + import org.springframework.messaging.Message; import org.springframework.util.Assert; @@ -35,6 +37,7 @@ public HeaderAttributeCorrelationStrategy(String attributeName) { this.attributeName = attributeName; } + @Nullable public Object getCorrelationKey(Message message) { return message.getHeaders().get(this.attributeName); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MessageGroupProcessor.java index f19d5ceebb3..3ab59596824 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MessageGroupProcessor.java @@ -16,6 +16,8 @@ package org.springframework.integration.aggregator; +import org.jspecify.annotations.Nullable; + import org.springframework.integration.store.MessageGroup; /** @@ -37,6 +39,7 @@ public interface MessageGroupProcessor { * @param group The message group. * @return The result of processing the group. */ + @Nullable Object processMessageGroup(MessageGroup group); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingCorrelationStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingCorrelationStrategy.java index db23451011a..ef5e5c81216 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingCorrelationStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingCorrelationStrategy.java @@ -18,6 +18,8 @@ import java.lang.reflect.Method; +import org.jspecify.annotations.Nullable; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -57,6 +59,7 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { } @Override + @Nullable public Object getCorrelationKey(Message message) { return this.processor.processMessage(message); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessor.java index 59b4d69a9d5..18ce313f287 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessor.java @@ -26,6 +26,7 @@ import org.springframework.integration.store.MessageGroup; import org.springframework.integration.support.management.ManageableLifecycle; import org.springframework.messaging.Message; +import org.springframework.util.Assert; /** * MessageGroupProcessor that serves as an adapter for the invocation of a POJO method. @@ -87,7 +88,9 @@ public void setBeanFactory(BeanFactory beanFactory) { @Override protected final Object aggregatePayloads(MessageGroup group, Map headers) { final Collection> messagesUpForProcessing = group.getMessages(); - return this.processor.process(messagesUpForProcessing, headers); + Object object = this.processor.process(messagesUpForProcessing, headers); + Assert.state(object != null, "The process returned a null result. Null result is not expected."); + return object; } @Override diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageListProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageListProcessor.java index 3f12b7685f2..2b69424f9f5 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageListProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingMessageListProcessor.java @@ -22,6 +22,7 @@ import java.util.Map; import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.handler.support.MessagingMethodInvokerHelper; @@ -89,7 +90,7 @@ public String toString() { } @SuppressWarnings("unchecked") - public T process(Collection> messages, Map aggregateHeaders) { + public @Nullable T process(Collection> messages, @Nullable Map aggregateHeaders) { return (T) this.delegate.process(messages, aggregateHeaders); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategy.java index 268aef1d0eb..36d2a0e1e3d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategy.java @@ -54,7 +54,7 @@ public void setBeanFactory(BeanFactory beanFactory) { @Override public boolean canRelease(MessageGroup messages) { - return this.adapter.process(messages.getMessages(), null); + return Boolean.TRUE.equals(this.adapter.process(messages.getMessages(), null)); } @Override diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessor.java index f606d36f3dc..a8d1b06b682 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessor.java @@ -21,6 +21,8 @@ import java.util.Comparator; import java.util.List; +import org.jspecify.annotations.Nullable; + import org.springframework.integration.StaticMessageHeaderAccessor; import org.springframework.integration.store.MessageGroup; import org.springframework.messaging.Message; @@ -40,6 +42,7 @@ public class ResequencingMessageGroupProcessor implements MessageGroupProcessor private final Comparator> comparator = new MessageSequenceComparator(); + @Nullable public Object processMessageGroup(MessageGroup group) { Collection> messages = group.getMessages(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageHandler.java index 4b0c57ab5bc..b23ee61686d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/ResequencingMessageHandler.java @@ -18,6 +18,8 @@ import java.util.Collection; +import org.jspecify.annotations.Nullable; + import org.springframework.integration.IntegrationPatternType; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.store.MessageGroupStore; @@ -78,7 +80,7 @@ protected boolean shouldCopyRequestHeaders() { } @Override - protected void afterRelease(MessageGroup messageGroup, Collection> completedMessages) { + protected void afterRelease(MessageGroup messageGroup, @Nullable Collection> completedMessages) { afterRelease(messageGroup, completedMessages, false); } @@ -90,7 +92,7 @@ protected void afterRelease(MessageGroup messageGroup, Collection> co * @param timeout True if the release/discard was due to a timeout. */ @Override - protected void afterRelease(MessageGroup messageGroup, Collection> completedMessages, boolean timeout) { + protected void afterRelease(MessageGroup messageGroup, @Nullable Collection> completedMessages, boolean timeout) { int size = messageGroup.size(); int sequenceSize = messageGroup.getSequenceSize(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/package-info.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/package-info.java index 2ac1aa53803..7deb51b0ff1 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/package-info.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/package-info.java @@ -1,4 +1,5 @@ /** * Provides classes related to message aggregation. */ +@org.jspecify.annotations.NullMarked package org.springframework.integration.aggregator; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/context/ExpressionCapable.java b/spring-integration-core/src/main/java/org/springframework/integration/context/ExpressionCapable.java index a6a4f65a012..c435c66107d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/context/ExpressionCapable.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/context/ExpressionCapable.java @@ -16,6 +16,8 @@ package org.springframework.integration.context; +import org.jspecify.annotations.Nullable; + import org.springframework.expression.Expression; /** @@ -32,6 +34,7 @@ public interface ExpressionCapable { * Return the primary SpEL expression if this component is expression-based. * @return the expression as a String. */ + @Nullable Expression getExpression(); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationContextUtils.java b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationContextUtils.java index 149af647910..a6552328929 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationContextUtils.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationContextUtils.java @@ -16,6 +16,8 @@ package org.springframework.integration.context; +import org.jspecify.annotations.Nullable; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanDefinition; @@ -120,6 +122,7 @@ public abstract class IntegrationContextUtils { * @param beanFactory BeanFactory for lookup, must not be null. * @return The {@link MetadataStore} bean whose name is "metadataStore". */ + @Nullable public static MetadataStore getMetadataStore(BeanFactory beanFactory) { return getBeanOfType(beanFactory, METADATA_STORE_BEAN_NAME, MetadataStore.class); } @@ -129,7 +132,9 @@ public static MetadataStore getMetadataStore(BeanFactory beanFactory) { * @return The {@link MessageChannel} bean whose name is "errorChannel". */ public static MessageChannel getErrorChannel(BeanFactory beanFactory) { - return getBeanOfType(beanFactory, ERROR_CHANNEL_BEAN_NAME, MessageChannel.class); + MessageChannel channel = getBeanOfType(beanFactory, ERROR_CHANNEL_BEAN_NAME, MessageChannel.class); + Assert.state(channel != null, "No such bean '" + ERROR_CHANNEL_BEAN_NAME + "'"); + return channel; } /** @@ -137,7 +142,9 @@ public static MessageChannel getErrorChannel(BeanFactory beanFactory) { * @return The {@link TaskScheduler} bean whose name is "taskScheduler" if available. */ public static TaskScheduler getTaskScheduler(BeanFactory beanFactory) { - return getBeanOfType(beanFactory, TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class); + TaskScheduler taskScheduler = getBeanOfType(beanFactory, TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class); + Assert.state(taskScheduler != null, "No such bean '" + TASK_SCHEDULER_BEAN_NAME + "'"); + return taskScheduler; } /** @@ -157,7 +164,9 @@ public static TaskScheduler getRequiredTaskScheduler(BeanFactory beanFactory) { * {@value #INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME}. */ public static StandardEvaluationContext getEvaluationContext(BeanFactory beanFactory) { - return getBeanOfType(beanFactory, INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, StandardEvaluationContext.class); + StandardEvaluationContext standardEvaluationContext = getBeanOfType(beanFactory, INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, StandardEvaluationContext.class); + Assert.state(standardEvaluationContext != null, "No such bean '" + INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME + "'"); + return standardEvaluationContext; } /** @@ -167,10 +176,14 @@ public static StandardEvaluationContext getEvaluationContext(BeanFactory beanFac * @since 4.3.15 */ public static SimpleEvaluationContext getSimpleEvaluationContext(BeanFactory beanFactory) { - return getBeanOfType(beanFactory, INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME, + SimpleEvaluationContext simpleEvaluationContext = getBeanOfType(beanFactory, INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME, SimpleEvaluationContext.class); + Assert.state(simpleEvaluationContext != null, "No such bean '" + INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME + "'"); + + return simpleEvaluationContext; } + @Nullable private static T getBeanOfType(BeanFactory beanFactory, String beanName, Class type) { Assert.notNull(beanFactory, "BeanFactory must not be null"); if (!beanFactory.containsBean(beanName)) { @@ -190,11 +203,8 @@ private static T getBeanOfType(BeanFactory beanFactory, String beanName, Cla * provided {@code #beanFactory} or provided {@code #beanFactory} is null. */ public static IntegrationProperties getIntegrationProperties(BeanFactory beanFactory) { - IntegrationProperties integrationProperties = null; - if (beanFactory != null) { - integrationProperties = + IntegrationProperties integrationProperties = getBeanOfType(beanFactory, INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, IntegrationProperties.class); - } if (integrationProperties == null) { integrationProperties = IntegrationProperties.DEFAULT_INSTANCE; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationObjectSupport.java b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationObjectSupport.java index 6a4654944e4..5edf363e3aa 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationObjectSupport.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationObjectSupport.java @@ -72,38 +72,50 @@ public abstract class IntegrationObjectSupport implements ComponentSourceAware, protected final LogAccessor logger = new LogAccessor(getClass()); // NOSONAR protected + @SuppressWarnings("NullAway.Init") private DestinationResolver channelResolver; + @SuppressWarnings("NullAway.Init") private String beanName; + @Nullable private String componentName; + @SuppressWarnings("NullAway.Init") private BeanFactory beanFactory; + @Nullable private TaskScheduler taskScheduler; private IntegrationProperties integrationProperties = new IntegrationProperties(); + @Nullable private ConversionService conversionService; + @SuppressWarnings("NullAway.Init") private ApplicationContext applicationContext; + @SuppressWarnings("NullAway.Init") private MessageBuilderFactory messageBuilderFactory; + @Nullable private Expression expression; + @Nullable private Object beanSource; + @Nullable private String beanDescription; private boolean initialized; @Override - public final void setBeanName(@Nullable String beanName) { + public final void setBeanName(String beanName) { this.beanName = beanName; } @Override + @Nullable public String getBeanName() { return this.beanName; } @@ -113,6 +125,7 @@ public String getBeanName() { * If {@link #componentName} was not set this method will default to the 'beanName' of this component; */ @Override + @Nullable public String getComponentName() { return StringUtils.hasText(this.componentName) ? this.componentName : this.beanName; } @@ -129,6 +142,7 @@ public void setComponentName(String componentName) { * Subclasses may implement this method to provide component type information. */ @Override + @Nullable public String getComponentType() { return null; } @@ -138,8 +152,8 @@ public void setComponentSource(Object source) { this.beanSource = source; } - @Nullable @Override + @Nullable public Object getComponentSource() { return this.beanSource; } @@ -149,8 +163,8 @@ public void setComponentDescription(String description) { this.beanDescription = description; } - @Nullable @Override + @Nullable public String getComponentDescription() { return this.beanDescription; } @@ -195,6 +209,7 @@ public void setChannelResolver(DestinationResolver channelResolv } @Override + @Nullable public Expression getExpression() { return this.expression; } @@ -268,6 +283,7 @@ protected TaskScheduler getTaskScheduler() { if (this.taskScheduler == null && this.beanFactory != null) { this.taskScheduler = IntegrationContextUtils.getTaskScheduler(this.beanFactory); } + Assert.notNull(this.taskScheduler, "'taskScheduler' must not be null"); return this.taskScheduler; } @@ -278,6 +294,7 @@ protected DestinationResolver getChannelResolver() { return this.channelResolver; } + @Nullable public ConversionService getConversionService() { if (this.conversionService == null && this.beanFactory != null) { this.conversionService = IntegrationUtils.getConversionService(this.beanFactory); @@ -299,6 +316,7 @@ public void setConversionService(ConversionService conversionService) { * {@link ApplicationContext} is available. * @return The id, or null if there is no application context. */ + @Nullable public String getApplicationContextId() { return this.applicationContext == null ? null : this.applicationContext.getId(); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationProperties.java b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationProperties.java index f4c98f33b74..4efb0e9ffac 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationProperties.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/context/IntegrationProperties.java @@ -19,6 +19,8 @@ import java.util.Arrays; import java.util.Properties; +import org.jspecify.annotations.Nullable; + import org.springframework.integration.JavaUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -139,6 +141,7 @@ public final class IntegrationProperties { private long endpointsDefaultTimeout = IntegrationContextUtils.DEFAULT_TIMEOUT; + @Nullable private volatile Properties properties; static { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/context/package-info.java b/spring-integration-core/src/main/java/org/springframework/integration/context/package-info.java index 1acc7924df0..e72e965c195 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/context/package-info.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/context/package-info.java @@ -1,4 +1,5 @@ /** * Provides classes relating to application context configuration. */ +@org.jspecify.annotations.NullMarked package org.springframework.integration.context; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/core/ErrorMessagePublisher.java b/spring-integration-core/src/main/java/org/springframework/integration/core/ErrorMessagePublisher.java index eeefffe1e17..d98a18cf2ca 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/core/ErrorMessagePublisher.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/core/ErrorMessagePublisher.java @@ -54,10 +54,13 @@ public class ErrorMessagePublisher implements BeanFactoryAware { protected final MessagingTemplate messagingTemplate = new MessagingTemplate(); // NOSONAR final + @SuppressWarnings("NullAway.Init") private DestinationResolver channelResolver; + @Nullable private MessageChannel channel; + @Nullable private String channelName; private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy(); @@ -79,6 +82,7 @@ public ErrorMessageStrategy getErrorMessageStrategy() { return this.errorMessageStrategy; } + @Nullable public MessageChannel getChannel() { populateChannel(); return this.channel; @@ -146,7 +150,7 @@ public void publish(Message inputMessage, MessagingException exception) { * @param failedMessage the message. * @param throwable the throwable. */ - public void publish(@Nullable Message inputMessage, Message failedMessage, Throwable throwable) { + public void publish(@Nullable Message inputMessage, @Nullable Message failedMessage, Throwable throwable) { publish(throwable, ErrorMessageUtils.getAttributeAccessor(inputMessage, failedMessage)); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/core/MessagingTemplate.java b/spring-integration-core/src/main/java/org/springframework/integration/core/MessagingTemplate.java index 40782cc2361..97fda6a4377 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/core/MessagingTemplate.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/core/MessagingTemplate.java @@ -44,6 +44,7 @@ public class MessagingTemplate extends GenericMessagingTemplate { private final Lock lock = new ReentrantLock(); + @SuppressWarnings("NullAway.Init") private BeanFactory beanFactory; private volatile boolean throwExceptionOnLateReplySet; @@ -84,7 +85,7 @@ public void setThrowExceptionOnLateReply(boolean throwExceptionOnLateReply) { * backward compatibility. * @param channel the channel to set. */ - public void setDefaultChannel(MessageChannel channel) { + public void setDefaultChannel(@Nullable MessageChannel channel) { super.setDefaultDestination(channel); } @@ -109,6 +110,7 @@ public Message sendAndReceive(MessageChannel destination, Message requestM return super.sendAndReceive(destination, requestMessage); } + @Nullable public Object receiveAndConvert(MessageChannel destination, long timeout) { Message message = doReceive(destination, timeout); if (message != null) { @@ -119,6 +121,7 @@ public Object receiveAndConvert(MessageChannel destination, long timeout) { } } + @Nullable public Message receive(MessageChannel destination, long timeout) { return doReceive(destination, timeout); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/core/package-info.java b/spring-integration-core/src/main/java/org/springframework/integration/core/package-info.java index b6f850c4881..b1ecdac03f3 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/core/package-info.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/core/package-info.java @@ -1,4 +1,5 @@ /** * Provides core classes. */ +@org.jspecify.annotations.NullMarked package org.springframework.integration.core; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java index 0d626a0bb8e..823470203c5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java @@ -32,7 +32,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.store.MessageGroup; @@ -40,6 +39,7 @@ import org.springframework.integration.store.SimpleMessageGroup; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; @@ -48,7 +48,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -62,7 +61,7 @@ * @since 2.2 * */ -public class AbstractCorrelatingMessageHandlerTests { +public class AbstractCorrelatingMessageHandlerTests implements TestApplicationContextAware { @Test public void testReaperDoesntReapAProcessingGroup() throws Exception { @@ -499,7 +498,8 @@ public void testPurgeOrphanedGroupsOnStartup() throws InterruptedException { QueueChannel discardChannel = new QueueChannel(); handler.setDiscardChannel(discardChannel); handler.setExpireTimeout(1); - handler.setBeanFactory(mock(BeanFactory.class)); + + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessageInternal(MessageBuilder.withPayload("test").setCorrelationId("test").build()); Thread.sleep(100); @@ -518,7 +518,7 @@ public void testPurgeOrphanedGroupsScheduled() { handler.setDiscardChannel(discardChannel); handler.setExpireTimeout(100); handler.setExpireDuration(Duration.ofMillis(10)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.afterPropertiesSet(); handler.setTaskScheduler(taskScheduler); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java index 4121bf82b53..d8a5c6250a4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java @@ -26,17 +26,16 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.store.SimpleMessageGroup; import org.springframework.integration.support.AbstractIntegrationMessageBuilder; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.MutableMessageBuilder; import org.springframework.integration.support.MutableMessageBuilderFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -44,7 +43,7 @@ * * @since 2.0 */ -public class AggregatingMessageGroupProcessorHeaderTests { +public class AggregatingMessageGroupProcessorHeaderTests implements TestApplicationContextAware { private final DefaultAggregatingMessageGroupProcessor defaultProcessor = new DefaultAggregatingMessageGroupProcessor(); @@ -54,8 +53,8 @@ public class AggregatingMessageGroupProcessorHeaderTests { @BeforeEach public void setup() { - this.defaultProcessor.setBeanFactory(mock(BeanFactory.class)); - this.methodInvokingProcessor.setBeanFactory(mock(BeanFactory.class)); + this.defaultProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); + this.methodInvokingProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java index 83096a2a3bd..e2ce821eefb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java @@ -31,7 +31,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.AbstractMessageHandler; @@ -40,6 +39,7 @@ import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.locks.LockRegistry; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.UUIDConverter; import org.springframework.messaging.Message; @@ -51,7 +51,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -60,7 +59,7 @@ * @author Gary Russell * @author Artem Bilan */ -public class AggregatorTests { +public class AggregatorTests implements TestApplicationContextAware { private static final Log logger = LogFactory.getLog(AggregatorTests.class); @@ -73,7 +72,7 @@ public class AggregatorTests { @BeforeEach public void configureAggregator() { this.aggregator = new AggregatingMessageHandler(new MultiplyingProcessor(), store); - this.aggregator.setBeanFactory(mock(BeanFactory.class)); + this.aggregator.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.aggregator.setApplicationEventPublisher(event -> expiryEvents.add((MessageGroupExpiredEvent) event)); this.aggregator.setBeanName("testAggregator"); this.aggregator.afterPropertiesSet(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerIntegrationTests.java index ef85d3db058..82cbf0d4fbb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerIntegrationTests.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -39,7 +39,7 @@ * @author Gary Russell * */ -public class CorrelatingMessageHandlerIntegrationTests { +public class CorrelatingMessageHandlerIntegrationTests implements TestApplicationContextAware { private final MessageGroupStore store = new SimpleMessageStore(100); @@ -54,7 +54,7 @@ public void setupHandler() { when(outputChannel.send(isA(Message.class))).thenReturn(true); defaultHandler.setOutputChannel(outputChannel); defaultHandler.setSendTimeout(-1); - defaultHandler.setBeanFactory(mock(BeanFactory.class)); + defaultHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); defaultHandler.afterPropertiesSet(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java index 5f8db0842f0..ce350f3c73f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java @@ -30,6 +30,7 @@ import org.springframework.integration.store.SimpleMessageGroup; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandlingException; @@ -49,7 +50,7 @@ * @author Dave Syer * @author Artme Bilan */ -public class CorrelatingMessageHandlerTests { +public class CorrelatingMessageHandlerTests implements TestApplicationContextAware { private AggregatingMessageHandler handler; @@ -70,7 +71,7 @@ public void initializeSubject() { outputChannel = mock(MessageChannel.class); handler = new AggregatingMessageHandler(processor, store, correlationStrategy, ReleaseStrategy); handler.setOutputChannel(outputChannel); - handler.setBeanFactory(mock()); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java index 1b153031cf0..7ab3d59db1f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java @@ -19,21 +19,20 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Dave Syer * @author Artem Bilan * */ -public class CorrelationStrategyAdapterTests { +public class CorrelationStrategyAdapterTests implements TestApplicationContextAware { private Message message; @@ -46,7 +45,7 @@ public void init() { public void testMethodName() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), "getKey"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @@ -55,7 +54,7 @@ public void testCorrelationStrategyAdapterObjectMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), ReflectionUtils.findMethod(SimpleMessageCorrelator.class, "getKey", Message.class)); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @@ -63,7 +62,7 @@ public void testCorrelationStrategyAdapterObjectMethod() { public void testCorrelationStrategyAdapterPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimplePojoCorrelator(), "getKey"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.getCorrelationKey(message)).isEqualTo("foo"); } @@ -71,7 +70,7 @@ public void testCorrelationStrategyAdapterPojoMethod() { public void testHeaderPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleHeaderCorrelator(), "getKey"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @@ -79,7 +78,7 @@ public void testHeaderPojoMethod() { public void testHeadersPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new MultiHeaderCorrelator(), ReflectionUtils.findMethod(MultiHeaderCorrelator.class, "getKey", String.class, String.class)); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.getCorrelationKey(message)).isEqualTo("bd"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java index 21aea7bd023..b1063155096 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java @@ -18,7 +18,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; @@ -26,13 +25,13 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; /** * @author Alex Peters @@ -40,7 +39,7 @@ * @author Gunnar Hillert * @author Gary Russell */ -public class ExpressionEvaluatingCorrelationStrategyTests { +public class ExpressionEvaluatingCorrelationStrategyTests implements TestApplicationContextAware { private ExpressionEvaluatingCorrelationStrategy strategy; @@ -62,7 +61,7 @@ public void testCorrelationKeyWithMethodInvokingExpression() throws Exception { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression expression = parser.parseExpression("payload.substring(0,1)"); strategy = new ExpressionEvaluatingCorrelationStrategy(expression); - strategy.setBeanFactory(mock(BeanFactory.class)); + strategy.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object correlationKey = strategy.getCorrelationKey(new GenericMessage("bla")); assertThat(correlationKey).isInstanceOf(String.class); assertThat((String) correlationKey).isEqualTo("b"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java index 8117313c040..8405925bb2e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.support.AbstractIntegrationMessageBuilder; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; @@ -39,7 +39,7 @@ * @author Gary Russell * @author Artem Bilan */ -public class ExpressionEvaluatingMessageGroupProcessorTests { +public class ExpressionEvaluatingMessageGroupProcessorTests implements TestApplicationContextAware { private ExpressionEvaluatingMessageGroupProcessor processor; @@ -59,7 +59,7 @@ public void setup() { public void testProcessAndSendWithSizeExpressionEvaluated() { when(group.getMessages()).thenReturn(messages); processor = new ExpressionEvaluatingMessageGroupProcessor("#root.size()"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessageGroup(group); assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); @@ -70,9 +70,9 @@ public void testProcessAndSendWithSizeExpressionEvaluated() { public void testProcessAndCheckHeaders() { when(group.getMessages()).thenReturn(messages); processor = new ExpressionEvaluatingMessageGroupProcessor("#root"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessageGroup(group); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); assertThat(resultMessage.getHeaders().get("foo")).isEqualTo("bar"); @@ -82,7 +82,7 @@ public void testProcessAndCheckHeaders() { public void testProcessAndSendWithProjectionExpressionEvaluated() { when(group.getMessages()).thenReturn(messages); processor = new ExpressionEvaluatingMessageGroupProcessor("![payload]"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessageGroup(group); assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); @@ -100,7 +100,7 @@ public void testProcessAndSendWithProjectionExpressionEvaluated() { public void testProcessAndSendWithFilterAndProjectionExpressionEvaluated() { when(group.getMessages()).thenReturn(messages); processor = new ExpressionEvaluatingMessageGroupProcessor("?[payload>2].![payload]"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessageGroup(group); assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); @@ -117,7 +117,7 @@ public void testProcessAndSendWithFilterAndProjectionAndMethodInvokingExpression when(group.getMessages()).thenReturn(messages); processor = new ExpressionEvaluatingMessageGroupProcessor(String.format("T(%s).sum(?[payload>2].![payload])", getClass().getName())); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessageGroup(group); assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java index 0d9466732e4..b15954c454f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java @@ -19,12 +19,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.store.SimpleMessageGroup; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Alex Peters @@ -33,7 +32,7 @@ * @author Artem Bilan * */ -public class ExpressionEvaluatingReleaseStrategyTests { +public class ExpressionEvaluatingReleaseStrategyTests implements TestApplicationContextAware { private ExpressionEvaluatingReleaseStrategy strategy; @@ -50,21 +49,21 @@ public void setup() { @Test public void testCompletedWithSizeSpelEvaluated() { strategy = new ExpressionEvaluatingReleaseStrategy("#root.size()==5"); - strategy.setBeanFactory(mock(BeanFactory.class)); + strategy.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(strategy.canRelease(messages)).isTrue(); } @Test public void testCompletedWithFilterSpelEvaluated() { strategy = new ExpressionEvaluatingReleaseStrategy("!messages.?[payload==5].empty"); - strategy.setBeanFactory(mock(BeanFactory.class)); + strategy.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(strategy.canRelease(messages)).isTrue(); } @Test public void testCompletedWithFilterSpelReturnsNotCompleted() { strategy = new ExpressionEvaluatingReleaseStrategy("!messages.?[payload==6].empty"); - strategy.setBeanFactory(mock(BeanFactory.class)); + strategy.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(strategy.canRelease(messages)).isFalse(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandlerTests.java index 84f3a729174..cbf8d4143f7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/FluxAggregatorMessageHandlerTests.java @@ -36,6 +36,7 @@ import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; /** * @author Artem Bilan @@ -159,6 +160,7 @@ void testCustomCombineFunction() { void testWindowTimespan() { QueueChannel resultChannel = new QueueChannel(); FluxAggregatorMessageHandler fluxAggregatorMessageHandler = new FluxAggregatorMessageHandler(); + fluxAggregatorMessageHandler.setTaskScheduler(mock()); fluxAggregatorMessageHandler.setOutputChannel(resultChannel); fluxAggregatorMessageHandler.setWindowTimespan(Duration.ofMillis(100)); fluxAggregatorMessageHandler.start(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java index d9ec35e5c25..78504051543 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java @@ -27,7 +27,6 @@ import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; @@ -40,6 +39,7 @@ import org.springframework.integration.store.SimpleMessageGroup; import org.springframework.integration.support.AbstractIntegrationMessageBuilder; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; @@ -61,7 +61,7 @@ * @author Gary Russell * @author Artem Bilan */ -public class MethodInvokingMessageGroupProcessorTests { +public class MethodInvokingMessageGroupProcessorTests implements TestApplicationContextAware { private final List> messagesUpForProcessing = new ArrayList<>(3); @@ -97,7 +97,7 @@ public String know(List flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new AnnotatedAggregatorMethod()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -121,7 +121,7 @@ public Integer and(List flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -145,7 +145,7 @@ public Integer and(List> flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -172,7 +172,7 @@ public String and(List flags, @Header("foo") List header) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); messagesUpForProcessing.add(MessageBuilder.withPayload(3).setHeader("foo", Arrays.asList(101, 102)).build()); when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); Object result = processor.processMessageGroup(messageGroupMock); @@ -203,7 +203,7 @@ public String and(@Payloads List rawFlags, @Header("foo") List heade MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.messagesUpForProcessing.add( MessageBuilder.withPayload(3) .setHeader("foo", Arrays.asList(101, 102)) @@ -233,7 +233,7 @@ public String or(List flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo("[1, 2, 4]"); @@ -257,7 +257,7 @@ public Integer and(Collection flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -281,7 +281,7 @@ public Integer and(int[] flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -305,7 +305,7 @@ public Integer and(Iterator flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); GenericConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new Converter, Iterator>() { // Must not be lambda @@ -348,7 +348,7 @@ public String methodAcceptingNoCollectionShouldBeIgnored(String irrelevant) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); @@ -378,7 +378,7 @@ public String methodAcceptingNoCollectionShouldBeIgnored(String irrelevant) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isInstanceOf(Iterator.class); @@ -408,7 +408,7 @@ public String listHeaderShouldBeIgnored(@Header List flags) { MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new AnnotatedParametersAggregator()); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); Object payload = ((AbstractIntegrationMessageBuilder) result).build().getPayload(); @@ -436,7 +436,7 @@ public String method2(List input) { SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); - aggregator.setBeanFactory(mock(BeanFactory.class)); + aggregator.setBeanFactory(TEST_INTEGRATION_CONTEXT); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(new GenericMessage<>("foo")); group.add(new GenericMessage<>("bar")); @@ -457,7 +457,7 @@ public String method1(List input, @Header("foo") String foo) { SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(bean); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); @@ -478,7 +478,7 @@ public String method1(List input, @Headers Map map) { SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); - aggregator.setBeanFactory(mock(BeanFactory.class)); + aggregator.setBeanFactory(TEST_INTEGRATION_CONTEXT); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); @@ -525,7 +525,7 @@ String method2(List input) { NoAnnotationTestBean bean = new NoAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); - aggregator.setBeanFactory(mock(BeanFactory.class)); + aggregator.setBeanFactory(TEST_INTEGRATION_CONTEXT); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(new GenericMessage<>("foo")); group.add(new GenericMessage<>("bar")); @@ -582,7 +582,7 @@ public void jdkProxy() { AggregatingMessageHandler handler = new AggregatingMessageHandler(aggregator); handler.setReleaseStrategy(new MessageCountReleaseStrategy()); handler.setOutputChannel(output); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(input, handler); endpoint.start(); @@ -604,7 +604,7 @@ public void cglibProxy() { AggregatingMessageHandler handler = new AggregatingMessageHandler(aggregator); handler.setReleaseStrategy(new MessageCountReleaseStrategy()); handler.setOutputChannel(output); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(input, handler); endpoint.start(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java index d8c9abafb5a..d3b19e3c74e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java @@ -23,11 +23,11 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.ConversionFailedException; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.store.SimpleMessageGroup; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; @@ -42,13 +42,13 @@ * @author Dave Syer * @author Artem Bilan */ -public class MethodInvokingReleaseStrategyTests { +public class MethodInvokingReleaseStrategyTests implements TestApplicationContextAware { @Test public void testTrueConvertedProperly() { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysTrueReleaseStrategy(), "checkCompleteness"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.canRelease(createListOfMessages(0))).isTrue(); } @@ -56,7 +56,7 @@ public void testTrueConvertedProperly() { public void testFalseConvertedProperly() { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysFalseReleaseStrategy(), "checkCompleteness"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(adapter.canRelease(createListOfMessages(0))).isFalse(); } @@ -75,7 +75,7 @@ public boolean checkCompletenessOnNonParameterizedListOfMessages(List MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnNonParameterizedListOfMessages"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThat(adapter.canRelease(messages)).isTrue(); } @@ -95,7 +95,7 @@ public boolean checkCompletenessOnListOfMessagesParametrizedWithWildcard(List messages) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfStrings"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThat(adapter.canRelease(messages)).isTrue(); } @@ -163,7 +163,7 @@ public boolean checkCompletenessOnListOfStrings(List messages) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfStrings"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThat(adapter.canRelease(messages)).isTrue(); } @@ -192,7 +192,7 @@ public boolean invalidParameterType(Date invalid) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "invalidParameterType"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThatIllegalStateException().isThrownBy(() -> adapter.canRelease(messages)); } @@ -254,7 +254,7 @@ public boolean listSubclassParameter(LinkedList l1) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "listSubclassParameter"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThat(adapter.canRelease(messages)).isTrue(); } @@ -272,7 +272,7 @@ public String wrongReturnType(List> messages) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "wrongReturnType"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThatExceptionOfType(ConversionFailedException.class) .isThrownBy(() -> adapter.canRelease(messages)); @@ -307,7 +307,7 @@ public boolean listSubclassParameter(LinkedList l1) { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), TestReleaseStrategy.class.getMethod("listSubclassParameter", LinkedList.class)); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); MessageGroup messages = createListOfMessages(3); assertThat(adapter.canRelease(messages)).isTrue(); } @@ -326,7 +326,7 @@ public int wrongReturnType(List> message) { MethodInvokingReleaseStrategy wrongReturnType = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), TestReleaseStrategy.class.getMethod( "wrongReturnType", List.class)); - wrongReturnType.setBeanFactory(mock(BeanFactory.class)); + wrongReturnType.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalStateException() .isThrownBy(() -> wrongReturnType.canRelease(mock(MessageGroup.class))); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java index a8e077f21e2..f7b12c29e65 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java @@ -23,13 +23,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; @@ -37,7 +37,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Marius Bogoevici @@ -48,7 +47,7 @@ * @author Gary Russell * @author Artem Bilan */ -public class ResequencerTests { +public class ResequencerTests implements TestApplicationContextAware { private ResequencingMessageHandler resequencer; @@ -59,7 +58,7 @@ public class ResequencerTests { @BeforeEach public void configureResequencer() { this.resequencer = new ResequencingMessageHandler(processor, store, null, null); - this.resequencer.setBeanFactory(mock(BeanFactory.class)); + this.resequencer.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.resequencer.afterPropertiesSet(); } @@ -88,7 +87,7 @@ public void testBasicResequencingA() { SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); releaseStrategy.setReleasePartialSequences(true); this.resequencer = new ResequencingMessageHandler(processor, store, null, releaseStrategy); - this.resequencer.setBeanFactory(mock(BeanFactory.class)); + this.resequencer.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.resequencer.afterPropertiesSet(); QueueChannel replyChannel = new QueueChannel(); @@ -109,7 +108,7 @@ public void testBasicUnboundedResequencing() { this.resequencer = new ResequencingMessageHandler(processor, store, null, releaseStrategy); QueueChannel replyChannel = new QueueChannel(); this.resequencer.setCorrelationStrategy(message -> "A"); - this.resequencer.setBeanFactory(mock(BeanFactory.class)); + this.resequencer.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.resequencer.afterPropertiesSet(); //Message message0 = MessageBuilder.withPayload("0").setSequenceNumber(0).build(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java index e71e90902da..13550b36db4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java @@ -24,6 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.core.MessagingTemplate; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -36,7 +37,7 @@ * @author Artem Bilan */ @SpringJUnitConfig -public class NestedAggregationTests { +public class NestedAggregationTests implements TestApplicationContextAware { @Autowired DirectChannel splitter; @@ -66,6 +67,7 @@ public void testAggregatorWithNestedRouter() { private List sendAndReceiveMessage(DirectChannel channel, int timeout, Message input) { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setReceiveTimeout(timeout); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); @SuppressWarnings("unchecked") Message> message = (Message>) messagingTemplate.sendAndReceive(channel, input); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java index 54f843fed5c..17cb1813071 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java @@ -26,7 +26,9 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.expression.Expression; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.support.channel.BeanFactoryChannelResolver; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -54,6 +56,7 @@ public void setup() { beanFactory = new DefaultListableBeanFactory(); channelResolver = new BeanFactoryChannelResolver(beanFactory); beanFactory.registerSingleton("c", testChannel); + beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java index 66e0a424c26..4ed67789124 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java @@ -27,8 +27,10 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.context.support.StaticApplicationContext; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.annotation.Publisher; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Payload; @@ -49,6 +51,7 @@ public class PublisherAnnotationAdvisorTests { public void setup() { context.registerSingleton("testChannel", QueueChannel.class); context.registerSingleton("testMetaChannel", QueueChannel.class); + context.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, StandardEvaluationContext.class); } @AfterEach diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java index 2a867591b43..60272ed97dc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java @@ -25,7 +25,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.integration.MessageDispatchingException; import org.springframework.integration.channel.PublishSubscribeChannel; @@ -38,6 +37,7 @@ import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.scheduling.PollerMetadata; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; @@ -49,14 +49,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Artem Bilan * @author Andreas Baer */ -public class ApplicationContextMessageBusTests { +public class ApplicationContextMessageBusTests implements TestApplicationContextAware { private TestApplicationContext context; @@ -96,7 +95,7 @@ public Object handleRequestMessage(Message message) { handler.setBeanFactory(this.context); handler.afterPropertiesSet(); PollingConsumer endpoint = new PollingConsumer(sourceChannel, handler); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.context.registerEndpoint("testEndpoint", endpoint); this.context.refresh(); sourceChannel.send(message); @@ -160,9 +159,9 @@ public Object handleRequestMessage(Message message) { handler1.setOutputChannel(outputChannel1); handler2.setOutputChannel(outputChannel2); PollingConsumer endpoint1 = new PollingConsumer(inputChannel, handler1); - endpoint1.setBeanFactory(mock(BeanFactory.class)); + endpoint1.setBeanFactory(TEST_INTEGRATION_CONTEXT); PollingConsumer endpoint2 = new PollingConsumer(inputChannel, handler2); - endpoint2.setBeanFactory(mock(BeanFactory.class)); + endpoint2.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.context.registerEndpoint("testEndpoint1", endpoint1); this.context.registerEndpoint("testEndpoint2", endpoint2); this.context.refresh(); @@ -248,7 +247,7 @@ public Object handleRequestMessage(Message message) { } }; PollingConsumer endpoint = new PollingConsumer(errorChannel, handler); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.context.registerEndpoint("testEndpoint", endpoint); this.context.refresh(); errorChannel.send(new ErrorMessage(new RuntimeException("test-exception"))); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/messageBusTests.xml b/spring-integration-core/src/test/java/org/springframework/integration/bus/messageBusTests.xml index 9993ea8d628..2813aebeb3b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/messageBusTests.xml +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/messageBusTests.xml @@ -13,6 +13,8 @@ + + diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java index 01166bebcbc..7858ebd49f5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java @@ -39,7 +39,6 @@ import reactor.util.Loggers; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.FluxMessageChannel; @@ -47,6 +46,7 @@ import org.springframework.integration.config.ConsumerEndpointFactoryBean; import org.springframework.integration.endpoint.ReactiveStreamsConsumer; import org.springframework.integration.handler.MethodInvokingMessageHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; @@ -68,7 +68,7 @@ * * @since 5.0 */ -public class ReactiveStreamsConsumerTests { +public class ReactiveStreamsConsumerTests implements TestApplicationContextAware { private static final Log LOGGER = LogFactory.getLog(ReactiveStreamsConsumerTests.class); @@ -85,9 +85,9 @@ public void testReactiveStreamsConsumerFluxMessageChannel() throws InterruptedEx }; MessageHandler testSubscriber = new MethodInvokingMessageHandler(messageHandler, (String) null); - ((MethodInvokingMessageHandler) testSubscriber).setBeanFactory(mock(BeanFactory.class)); + ((MethodInvokingMessageHandler) testSubscriber).setBeanFactory(TEST_INTEGRATION_CONTEXT); ReactiveStreamsConsumer reactiveConsumer = new ReactiveStreamsConsumer(testChannel, testSubscriber); - reactiveConsumer.setBeanFactory(mock(BeanFactory.class)); + reactiveConsumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); reactiveConsumer.afterPropertiesSet(); reactiveConsumer.start(); @@ -144,7 +144,7 @@ public void onComplete() { }); ReactiveStreamsConsumer reactiveConsumer = new ReactiveStreamsConsumer(testChannel, testSubscriber); - reactiveConsumer.setBeanFactory(mock(BeanFactory.class)); + reactiveConsumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); reactiveConsumer.afterPropertiesSet(); reactiveConsumer.start(); @@ -199,7 +199,7 @@ public void testReactiveStreamsConsumerPollableChannel() throws InterruptedExcep publisher = publisher.log(Loggers.getLogger(ReactiveStreamsConsumerTests.class)); dfa.setPropertyValue("publisher", publisher); - reactiveConsumer.setBeanFactory(mock(BeanFactory.class)); + reactiveConsumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); reactiveConsumer.afterPropertiesSet(); reactiveConsumer.start(); @@ -306,7 +306,7 @@ public void testReactiveStreamsConsumerFluxMessageChannelReactiveMessageHandler( }; ReactiveStreamsConsumer reactiveConsumer = new ReactiveStreamsConsumer(testChannel, messageHandler); - reactiveConsumer.setBeanFactory(mock(BeanFactory.class)); + reactiveConsumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); reactiveConsumer.afterPropertiesSet(); reactiveConsumer.start(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java index 2037aca9365..a3328ec6847 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java @@ -23,6 +23,8 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.expression.MapAccessor; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.DefaultHeaderChannelRegistry; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.MessagePublishingErrorHandler; @@ -34,6 +36,7 @@ import org.springframework.integration.support.MessagingExceptionWrapper; import org.springframework.integration.support.channel.BeanFactoryChannelResolver; import org.springframework.integration.support.channel.HeaderChannelRegistry; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -41,11 +44,14 @@ import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -59,7 +65,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class HeaderChannelRegistryTests { +public class HeaderChannelRegistryTests implements TestApplicationContextAware { @Autowired MessageChannel input; @@ -92,6 +98,7 @@ public class HeaderChannelRegistryTests { public void testReplace() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.input); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message reply = template.sendAndReceive(new GenericMessage<>("foo")); assertThat(reply).isNotNull(); assertThat(reply.getPayload()).isEqualTo("echo:foo"); @@ -106,6 +113,7 @@ public void testReplace() { public void testReplaceTtl() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.inputTtl); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message reply = template.sendAndReceive(new GenericMessage<>("ttl")); assertThat(reply).isNotNull(); assertThat(reply.getPayload()).isEqualTo("echo:ttl"); @@ -120,6 +128,7 @@ public void testReplaceTtl() { public void testReplaceCustomTtl() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.inputCustomTtl); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message requestMessage = MessageBuilder.withPayload("ttl") .setHeader("channelTTL", 180000) .build(); @@ -164,6 +173,7 @@ public void testReplaceGatewayWithExplicitReplyChannel() { public void testReplaceError() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.inputPolled); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message reply = template.sendAndReceive(new GenericMessage<>("bar")); assertThat(reply).isNotNull(); assertThat(reply instanceof ErrorMessage).isTrue(); @@ -206,7 +216,7 @@ public void testExpire() throws Exception { @Test public void testBFCRWithRegistry() { BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(); - BeanFactory beanFactory = mock(BeanFactory.class); + BeanFactory beanFactory = createTestEvaluationContext(); when(beanFactory.getBean(IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME, HeaderChannelRegistry.class)) .thenReturn(mock(HeaderChannelRegistry.class)); @@ -223,7 +233,7 @@ public void testBFCRWithRegistry() { @Test public void testBFCRNoRegistry() { BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(); - BeanFactory beanFactory = mock(BeanFactory.class); + BeanFactory beanFactory = createTestEvaluationContext(); doAnswer(invocation -> { throw new NoSuchBeanDefinitionException("bar"); }).when(beanFactory).getBean("foo", MessageChannel.class); @@ -238,6 +248,7 @@ public void testBFCRNoRegistry() { @Test public void testRemoveOnGet() { DefaultHeaderChannelRegistry registry = new DefaultHeaderChannelRegistry(); + registry.setTaskScheduler(new SimpleAsyncTaskScheduler()); MessageChannel channel = new DirectChannel(); String foo = (String) registry.channelToChannelName(channel); Map map = TestUtils.getPropertyValue(registry, "channels", Map.class); @@ -271,6 +282,18 @@ protected Object handleRequestMessage(Message requestMessage) { } + private static BeanFactory createTestEvaluationContext() { + final String integrationEvaluationContextBeanName = "integrationEvaluationContext"; + BeanFactory beanFactory = mock(BeanFactory.class); + when(beanFactory.containsBean(eq(integrationEvaluationContextBeanName))) + .thenReturn(true); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + evaluationContext.addPropertyAccessor(new MapAccessor()); + when(beanFactory.getBean(eq(integrationEvaluationContextBeanName), any(Class.class))) + .thenReturn(evaluationContext); + return beanFactory; + } + public interface Gateway { String exchange(String foo); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java index 2580f3393c2..e71ab5f393c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java @@ -24,6 +24,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; @@ -41,7 +42,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class HeaderEnricherOverwriteTests { +public class HeaderEnricherOverwriteTests implements TestApplicationContextAware { @Autowired private ApplicationContext context; @@ -155,6 +156,7 @@ public void priorityExplicitOverwriteTrue() { MessageChannel channel = this.context.getBean("priorityExplicitOverwriteTrueInput", MessageChannel.class); MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(channel); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = template.sendAndReceive(new GenericMessage<>("test")); assertThat(result).isNotNull(); assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(42); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java index bc9b6401d3d..e20244a61bb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java @@ -32,6 +32,7 @@ import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.routingslip.ExpressionEvaluatingRoutingSlipRouteStrategy; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -51,7 +52,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class HeaderEnricherTests { +public class HeaderEnricherTests implements TestApplicationContextAware { @Autowired private ApplicationContext context; @@ -105,7 +106,7 @@ public void errorChannel() { @Test public void correlationIdValue() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("correlationIdValueInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -114,7 +115,7 @@ public void correlationIdValue() { @Test public void correlationIdValueWithType() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("correlationIdValueWithTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -125,7 +126,7 @@ public void correlationIdValueWithType() { @Test public void correlationIdRef() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("correlationIdRefInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -134,7 +135,7 @@ public void correlationIdRef() { @Test public void expirationDateValue() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("expirationDateValueInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -143,7 +144,7 @@ public void expirationDateValue() { @Test public void expirationDateRef() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("expirationDateRefInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -152,7 +153,7 @@ public void expirationDateRef() { @Test public void priority() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("priorityInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -161,7 +162,7 @@ public void priority() { @Test public void priorityExpression() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("priorityExpressionInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>(Collections.singletonMap("priority", "-10"))); @@ -171,7 +172,7 @@ public void priorityExpression() { @Test public void expressionUsingPayload() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("payloadExpressionInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>(new TestBean("foo"))); assertThat(result).isNotNull(); @@ -180,7 +181,7 @@ public void expressionUsingPayload() { @Test public void expressionUsingHeader() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("headerExpressionInput", MessageChannel.class); Message message = MessageBuilder.withPayload("test").setHeader("testHeader1", "foo").build(); Message result = template.sendAndReceive(channel, message); @@ -190,7 +191,7 @@ public void expressionUsingHeader() { @Test public void expressionWithDateType() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("expressionWithDateTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -202,7 +203,7 @@ public void expressionWithDateType() { @Test public void expressionWithLongType() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("expressionWithLongTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -212,7 +213,7 @@ public void expressionWithLongType() { @Test public void refWithMethod() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("refWithMethod", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -222,7 +223,7 @@ public void refWithMethod() { @Test public void ref() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("ref", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -233,7 +234,7 @@ public void ref() { @Test public void innerBean() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("innerBean", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -244,7 +245,7 @@ public void innerBean() { @Test public void innerBeanWithMethod() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("innerBeanWithMethod", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -263,7 +264,7 @@ public void testFailConfigUnexpectedSubElement() { @Test public void testRoutingSlip() { - MessagingTemplate template = new MessagingTemplate(); + MessagingTemplate template = createMessagingTemplate(); MessageChannel channel = context.getBean("routingSlipInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); @@ -280,6 +281,12 @@ public void testRoutingSlip() { assertThat(routingSlipPath.get(3)).isEqualTo("bazRoutingSlip"); } + private static MessagingTemplate createMessagingTemplate() { + MessagingTemplate template = new MessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); + return template; + } + public static class TestBean { private final String name; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java index a98813cb39e..7feb50ca364 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java @@ -26,6 +26,7 @@ import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; @@ -42,7 +43,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class ServiceActivatorParserTests { +public class ServiceActivatorParserTests implements TestApplicationContextAware { @Autowired private MessageChannel literalExpressionInput; @@ -214,6 +215,7 @@ public void testConsumerEndpointFactoryBeanDefaultPhase() { private Object sendAndReceive(MessageChannel channel, Object payload) { MessagingTemplate template = new MessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(channel); return template.convertSendAndReceive(payload, Object.class); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java index c6cb83814c5..59987286b7f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java @@ -118,6 +118,7 @@ import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.MutableMessageBuilder; import org.springframework.integration.support.SmartLifecycleRoleController; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.OnlyOnceTrigger; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.NoBeansOverrideAnnotationConfigContextLoader; @@ -162,7 +163,7 @@ @SpringJUnitConfig(classes = {EnableIntegrationTests.ContextConfiguration.class, EnableIntegrationTests.ContextConfiguration2.class}) @DirtiesContext -public class EnableIntegrationTests { +public class EnableIntegrationTests implements TestApplicationContextAware { @Autowired private ApplicationContext context; @@ -455,6 +456,7 @@ public void testAnnotatedServiceActivator() throws Exception { assertThat(message.getHeaders().get("foo")).isEqualTo("FOO"); MessagingTemplate messagingTemplate = new MessagingTemplate(this.controlBusChannel); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(messagingTemplate.convertSendAndReceive("pausable.isRunning", Boolean.class)).isEqualTo(false); this.controlBusChannel.send(new GenericMessage<>("pausable.start")); assertThat(messagingTemplate.convertSendAndReceive("pausable.isRunning", Boolean.class)).isEqualTo(true); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java index 261a70e8d57..5b3ca7648b0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java @@ -31,6 +31,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; @@ -46,7 +47,7 @@ * @author Artem Bilan * @since 2.0 */ -public class AsyncMessagingTemplateTests { +public class AsyncMessagingTemplateTests implements TestApplicationContextAware { @Test public void asyncSendWithDefaultChannel() throws Exception { @@ -256,6 +257,7 @@ public void asyncSendAndReceiveWithDefaultChannel() throws Exception { channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); template.setDefaultDestination(channel); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); assertThat(result.get()).isNotNull(); @@ -269,6 +271,7 @@ public void asyncSendAndReceiveWithExplicitChannel() throws Exception { DirectChannel channel = new DirectChannel(); channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future> result = template.asyncSendAndReceive(channel, new GenericMessage<>("test")); assertThat(result.get()).isNotNull(); @@ -302,6 +305,7 @@ public void asyncConvertSendAndReceiveWithDefaultChannel() throws Exception { channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); template.setDefaultDestination(channel); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive("test"); assertThat(result.get()).isNotNull(); @@ -316,6 +320,7 @@ public void asyncConvertSendAndReceiveWithExplicitChannel() throws Exception { DirectChannel channel = new DirectChannel(); channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(channel, "test"); assertThat(result.get()).isNotNull(); @@ -349,6 +354,7 @@ public void asyncConvertSendAndReceiveWithDefaultChannelAndMessagePostProcessor( channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); template.setDefaultDestination(channel); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(123, new TestMessagePostProcessor()); assertThat(result.get()).isNotNull(); @@ -363,6 +369,7 @@ public void asyncConvertSendAndReceiveWithExplicitChannelAndMessagePostProcessor DirectChannel channel = new DirectChannel(); channel.subscribe(new EchoHandler(200)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(channel, "test", new TestMessagePostProcessor()); assertThat(result.get()).isNotNull(); @@ -395,6 +402,7 @@ public void timeoutException() { DirectChannel channel = new DirectChannel(); channel.subscribe(new EchoHandler(10000)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(channel); Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); assertThatExceptionOfType(TimeoutException.class) @@ -406,6 +414,7 @@ public void executionException() { DirectChannel channel = new DirectChannel(); channel.subscribe(new EchoHandler(-1)); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(channel); Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); assertThatExceptionOfType(ExecutionException.class) @@ -419,6 +428,7 @@ public void cancellationException() throws Throwable { EchoHandler handler = new EchoHandler(10000); channel.subscribe(handler); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(channel); Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java index 0a7f81d75c8..662ade085d2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java @@ -22,10 +22,10 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.MessageRejectedException; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.message.TestHandlers; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; @@ -33,13 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Artem Bilan */ -public class FailOverDispatcherTests { +public class FailOverDispatcherTests implements TestApplicationContextAware { @Test public void singleMessage() throws InterruptedException { @@ -189,7 +188,7 @@ public void failoverStrategyRejects() { private static ServiceActivatingHandler createConsumer(Object object) { ServiceActivatingHandler handler = new ServiceActivatingHandler(object); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); return handler; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java index 269cdcd7ded..9e9e456f855 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java @@ -57,6 +57,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -130,6 +131,7 @@ void testReactiveFlow() throws Exception { @Test void testPollableReactiveFlow() throws Exception { assertThat(this.reactiveTransformer).isInstanceOf(ReactiveStreamsConsumer.class); + this.reactiveTransformer.setTaskScheduler(new SimpleAsyncTaskScheduler()); this.inputChannel.send(new GenericMessage<>("1,2,3,4,5")); CountDownLatch latch = new CountDownLatch(6); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java index 45646ebf1ae..03f8dbfc474 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java @@ -18,24 +18,23 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.splitter.MethodInvokingSplitter; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Marius Bogoevici */ -public class CorrelationIdTests { +public class CorrelationIdTests implements TestApplicationContextAware { @Test public void testCorrelationIdPassedIfAvailable() { @@ -46,7 +45,7 @@ public void testCorrelationIdPassedIfAvailable() { QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "upperCase"); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); @@ -63,7 +62,7 @@ public void testCorrelationIdCopiedFromMessageCorrelationIdIfAvailable() { QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "upperCase"); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); @@ -82,7 +81,7 @@ public void testCorrelationNotPassedFromRequestHeaderIfAlreadySetByHandler() { QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "createMessage"); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); @@ -98,7 +97,7 @@ public void testCorrelationNotCopiedFromRequestMessgeIdIfAlreadySetByHandler() t QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "createMessage"); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); @@ -114,7 +113,7 @@ public void testCorrelationIdWithSplitterWhenNotValueSetOnIncomingMessage() thro MethodInvokingSplitter splitter = new MethodInvokingSplitter( new TestBean(), TestBean.class.getMethod("split", String.class)); splitter.setOutputChannel(testChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); Message reply1 = testChannel.receive(100); @@ -133,7 +132,7 @@ public void testCorrelationIdWithSplitterWhenValueSetOnIncomingMessage() throws MethodInvokingSplitter splitter = new MethodInvokingSplitter( new TestBean(), TestBean.class.getMethod("split", String.class)); splitter.setOutputChannel(testChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); Message reply1 = testChannel.receive(100); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java index c3869b6617b..f81e5534daf 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java @@ -25,18 +25,17 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.config.ExpressionFactoryBean; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.PeriodicTrigger; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -45,7 +44,7 @@ * * @since 2.0 */ -public class ExpressionEvaluatingMessageSourceIntegrationTests { +public class ExpressionEvaluatingMessageSourceIntegrationTests implements TestApplicationContextAware { private static final AtomicInteger counter = new AtomicInteger(); @@ -64,7 +63,7 @@ public void test() throws Exception { Expression expression = factoryBean.getObject(); ExpressionEvaluatingMessageSource source = new ExpressionEvaluatingMessageSource<>(expression, Object.class); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setHeaderExpressions(headerExpressions); SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); adapter.setSource(source); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java index 7d85b86a83f..f566d17d061 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java @@ -18,29 +18,28 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.ConversionFailedException; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Gary Russell * @since 2.0 */ -public class ExpressionEvaluatingMessageSourceTests { +public class ExpressionEvaluatingMessageSourceTests implements TestApplicationContextAware { @Test public void literalExpression() { Expression expression = new LiteralExpression("foo"); ExpressionEvaluatingMessageSource source = new ExpressionEvaluatingMessageSource(expression, String.class); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = source.receive(); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("foo"); @@ -51,7 +50,7 @@ public void unexpectedType() { Expression expression = new LiteralExpression("foo"); ExpressionEvaluatingMessageSource source = new ExpressionEvaluatingMessageSource(expression, Integer.class); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatThrownBy(() -> source.receive()) .isInstanceOf(ConversionFailedException.class); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java index 01c68b4e648..7da960be2b5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java @@ -25,6 +25,7 @@ import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.PublishSubscribeChannel; import org.springframework.integration.handler.ServiceActivatingHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; @@ -44,7 +45,7 @@ * * @since 2.0.1 */ -public class MessageProducerSupportTests { +public class MessageProducerSupportTests implements TestApplicationContextAware { private final TestApplicationContext context = TestUtils.createTestApplicationContext(); @@ -103,7 +104,7 @@ public void validateSuccessfulErrorFlowDoesNotThrowErrors() { PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); SuccessfulErrorService errorService = new SuccessfulErrorService(); ServiceActivatingHandler handler = new ServiceActivatingHandler(errorService); - handler.setBeanFactory(this.context); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); errorChannel.subscribe(handler); MessageProducerSupport mps = new MessageProducerSupport() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java index 3b6f7f9a1d2..deb22e22861 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -30,6 +29,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.core.MessageSource; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transaction.DefaultTransactionSynchronizationFactory; import org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor; import org.springframework.integration.transaction.IntegrationResourceHolder; @@ -47,7 +47,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.mockito.Mockito.mock; /** * @author Gary Russell @@ -57,14 +56,14 @@ * @since 2.2 * */ -public class PseudoTransactionalMessageSourceTests { +public class PseudoTransactionalMessageSourceTests implements TestApplicationContextAware { @Test public void testCommit() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); PollableChannel queueChannel = new QueueChannel(); syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix")); syncProcessor.setBeforeCommitChannel(queueChannel); @@ -160,7 +159,7 @@ public void testRollback() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); PollableChannel queueChannel = new QueueChannel(); syncProcessor.setAfterRollbackChannel(queueChannel); syncProcessor.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#baz")); @@ -205,7 +204,7 @@ public void testCommitWithManager() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix")); syncProcessor.setBeforeCommitChannel(queueChannel); syncProcessor.setAfterCommitChannel(queueChannel); @@ -252,7 +251,7 @@ public void testRollbackWithManager() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); syncProcessor.setAfterRollbackChannel(queueChannel); syncProcessor.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#baz")); @@ -295,7 +294,7 @@ public void testRollbackWithManagerUsingStatus() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeanFactory(TEST_INTEGRATION_CONTEXT); syncProcessor.setAfterRollbackChannel(queueChannel); syncProcessor.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#baz")); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java index 1f269f43911..a491c4efad2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java @@ -25,6 +25,7 @@ import org.springframework.integration.handler.ReplyRequiredException; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; @@ -32,14 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Marius Bogoevici * @author Artem Bilan */ -public class ServiceActivatorEndpointTests { +public class ServiceActivatorEndpointTests implements TestApplicationContextAware { @Test public void outputChannel() { @@ -81,15 +81,13 @@ public void returnAddressHeader() { @Test public void returnAddressHeaderWithChannelName() { - TestUtils.TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); QueueChannel channel = new QueueChannel(1); channel.setBeanName("testChannel"); TestChannelResolver channelResolver = new TestChannelResolver(); channelResolver.addChannel("testChannel", channel); ServiceActivatingHandler endpoint = this.createEndpoint(); endpoint.setChannelResolver(channelResolver); - endpoint.setBeanFactory(testApplicationContext); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo") .setReplyChannelName("testChannel").build(); @@ -97,13 +95,10 @@ public void returnAddressHeaderWithChannelName() { Message reply = channel.receive(0); assertThat(reply).isNotNull(); assertThat(reply.getPayload()).isEqualTo("FOO"); - testApplicationContext.close(); } @Test public void dynamicReplyChannel() throws Exception { - TestUtils.TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); final QueueChannel replyChannel1 = new QueueChannel(); final QueueChannel replyChannel2 = new QueueChannel(); replyChannel2.setBeanName("replyChannel2"); @@ -118,7 +113,7 @@ public Message handle(Message message) { TestChannelResolver channelResolver = new TestChannelResolver(); channelResolver.addChannel("replyChannel2", replyChannel2); endpoint.setChannelResolver(channelResolver); - endpoint.setBeanFactory(testApplicationContext); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message testMessage1 = MessageBuilder.withPayload("bar") .setReplyChannel(replyChannel1).build(); @@ -136,7 +131,6 @@ public Message handle(Message message) { reply2 = replyChannel2.receive(0); assertThat(reply2).isNotNull(); assertThat(reply2.getPayload()).isEqualTo("foobar"); - testApplicationContext.close(); } @Test @@ -163,7 +157,7 @@ public void noReplyMessage() { QueueChannel channel = new QueueChannel(1); ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new TestNullReplyBean(), "handle"); endpoint.setOutputChannel(channel); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); @@ -176,7 +170,7 @@ public void noReplyMessageWithRequiresReply() { ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new TestNullReplyBean(), "handle"); endpoint.setRequiresReply(true); endpoint.setOutputChannel(channel); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").build(); assertThatThrownBy(() -> endpoint.handleMessage(message)) @@ -194,7 +188,7 @@ public Message handle(Message message) { return message; } }, "handle"); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("test") @@ -216,7 +210,7 @@ public Message handle(Message message) { .setCorrelationId("ABC-123").build(); } }, "handle"); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("test") @@ -231,7 +225,7 @@ public Message handle(Message message) { @Test public void testBeanFactoryPopulation() { ServiceActivatingHandler endpoint = this.createEndpoint(); - BeanFactory mock = mock(BeanFactory.class); + BeanFactory mock = TEST_INTEGRATION_CONTEXT; endpoint.setBeanFactory(mock); endpoint.afterPropertiesSet(); Object beanFactory = TestUtils.getPropertyValue(endpoint, "processor.beanFactory"); @@ -241,7 +235,7 @@ public void testBeanFactoryPopulation() { private ServiceActivatingHandler createEndpoint() { ServiceActivatingHandler handler = new ServiceActivatingHandler(new TestBean(), "handle"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); return handler; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java index 055daa73baf..5b294d55e57 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java @@ -20,11 +20,11 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.gateway.RequestReplyExchanger; import org.springframework.integration.handler.ServiceActivatingHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.handler.annotation.Payload; @@ -32,14 +32,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Gary Russell * @author Artem Bilan */ -public class ServiceActivatorMethodResolutionTests { +public class ServiceActivatorMethodResolutionTests implements TestApplicationContextAware { @Test public void singleAnnotationMatches() { @@ -47,7 +46,7 @@ public void singleAnnotationMatches() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); serviceActivator.handleMessage(new GenericMessage<>("foo")); @@ -68,7 +67,7 @@ public void singlePublicMethodMatches() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); serviceActivator.handleMessage(new GenericMessage<>("foo")); @@ -98,7 +97,7 @@ protected Object handleRequestMessage(Message message) { return null; } }; - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); serviceActivator.handleMessage(test); @@ -125,7 +124,7 @@ public String foo(String request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); @@ -158,7 +157,7 @@ public String foo(Message request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); @@ -196,7 +195,7 @@ public String bar(Message request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); @@ -234,7 +233,7 @@ public String bar(String request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); @@ -252,7 +251,7 @@ public void nullOk() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivator.afterPropertiesSet(); serviceActivator.handleMessage(new GenericMessage<>(new KafkaNull())); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java index bf5a92eb252..5472310f56d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java @@ -77,15 +77,11 @@ public void testEvaluationContextNoFactoryBean() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, new RootBeanDefinition(ConversionServiceFactoryBean.class)); + context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, + new RootBeanDefinition(StandardEvaluationContext.class)); context.refresh(); StandardEvaluationContext evalContext = ExpressionUtils.createStandardEvaluationContext(context); - assertThat(evalContext.getBeanResolver()).isNotNull(); - TypeConverter typeConverter = evalContext.getTypeConverter(); - assertThat(typeConverter).isNotNull(); - assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService", Supplier.class).get()) - .isNotSameAs(DefaultConversionService.getSharedInstance()); - assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService", Supplier.class).get()) - .isSameAs(context.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME)); + assertThat(evalContext.getBeanResolver()).isNull(); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java index 3fb6e392909..5d491e4b215 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java @@ -20,13 +20,12 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -34,12 +33,12 @@ * @author Gunnar Hillert * @author Artem Bilan */ -public class MethodInvokingSelectorTests { +public class MethodInvokingSelectorTests implements TestApplicationContextAware { @Test public void acceptedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>("should accept"))).isTrue(); } @@ -48,14 +47,14 @@ public void acceptedWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>("should accept"))).isTrue(); } @Test public void rejectedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>(99))).isFalse(); } @@ -64,14 +63,14 @@ public void rejectedWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>(99))).isFalse(); } @Test public void noArgMethodWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "noArgs"); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>("test"))).isTrue(); } @@ -80,14 +79,14 @@ public void noArgMethodWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method method = testBean.getClass().getMethod("noArgs"); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(selector.accept(new GenericMessage<>("test"))).isTrue(); } @Test public void voidReturningMethodWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "returnVoid"); - selector.setBeanFactory(mock(BeanFactory.class)); + selector.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(() -> selector.accept(new GenericMessage<>("test"))); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java index 8230f98596c..0e8b3a08961 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java @@ -29,24 +29,24 @@ import reactor.test.StepVerifier; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.MessageDispatchingException; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.GatewayHeader; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.NullChannel; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.GenericMessage; import org.springframework.messaging.support.MessageBuilder; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -56,16 +56,15 @@ * * @since 2.0 */ -public class AsyncGatewayTests { +public class AsyncGatewayTests implements TestApplicationContextAware { @Test public void futureWithMessageReturned() throws Exception { QueueChannel requestChannel = new QueueChannel(); + requestChannel.setBeanFactory(TEST_INTEGRATION_CONTEXT); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Future> f = service.returnMessage("foo"); @@ -86,9 +85,7 @@ protected boolean doSend(Message message, long timeout) { }; GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(channel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(channel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Future> f = service.returnMessage("foo"); @@ -104,9 +101,7 @@ public void listenableFutureWithMessageReturned() throws Exception { addThreadEnricher(requestChannel); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); CompletableFuture> f = service.returnMessageListenable("foo"); @@ -130,9 +125,7 @@ public void customFutureReturned() { addThreadEnricher(requestChannel); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); CustomFuture f = service.returnCustomFuture("foo"); @@ -147,10 +140,7 @@ public void nonAsyncFutureReturned() { addThreadEnricher(requestChannel); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); - + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.setAsyncExecutor(null); // Not async - user flow returns Future proxyFactory.afterPropertiesSet(); @@ -179,9 +169,7 @@ public void futureWithPayloadReturned() throws Exception { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Future f = service.returnString("foo"); @@ -195,9 +183,7 @@ public void futureWithWildcardReturned() throws Exception { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Future f = service.returnSomething("foo"); @@ -209,9 +195,7 @@ public void futureWithWildcardReturned() throws Exception { @Test public void futureVoid() throws Exception { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(new NullChannel()); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(new NullChannel(), proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Future f = service.asyncSendAndForget("test1"); @@ -249,9 +233,7 @@ public void futureVoidReply() throws Exception { } }).start(); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.setAsyncExecutor(null); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); @@ -266,9 +248,7 @@ public void monoWithMessageReturned() { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); - proxyFactory.setBeanName("testGateway"); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Mono> mono = service.returnMessagePromise("foo"); @@ -281,9 +261,7 @@ public void monoWithPayloadReturned() { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); - proxyFactory.setBeanName("testGateway"); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Mono mono = service.returnStringPromise("foo"); @@ -296,9 +274,7 @@ public void monoWithWildcardReturned() { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); - proxyFactory.setBeanName("testGateway"); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Mono mono = service.returnSomethingPromise("foo"); @@ -312,9 +288,7 @@ public void monoWithConsumer() { QueueChannel requestChannel = new QueueChannel(); startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); - proxyFactory.setBeanName("testGateway"); + setupProxyFactory(requestChannel, proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Mono mono = service.returnStringPromise("foo"); @@ -327,9 +301,7 @@ public void monoWithConsumer() { @Test public void monoVoid() throws InterruptedException { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestEchoService.class); - proxyFactory.setDefaultRequestChannel(new NullChannel()); - proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + setupProxyFactory(new NullChannel(), proxyFactory); proxyFactory.afterPropertiesSet(); TestEchoService service = proxyFactory.getObject(); Mono mono = service.monoVoid("test1"); @@ -402,6 +374,13 @@ private interface TestEchoService { } + private static void setupProxyFactory(MessageChannel messageChannel, GatewayProxyFactoryBean proxyFactory) { + proxyFactory.setDefaultRequestChannel(messageChannel); + proxyFactory.setBeanName("testGateway"); + proxyFactory.setTaskScheduler(new SimpleAsyncTaskScheduler()); + proxyFactory.setBeanFactory(TEST_INTEGRATION_CONTEXT); + } + private record CustomFuture(String result, Thread thread) implements Future { @Override diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java index 72eefb2be2d..2b97b42987d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java @@ -60,6 +60,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.MessageTimeoutException; import org.springframework.integration.annotation.AnnotationConstants; import org.springframework.integration.annotation.BridgeTo; @@ -89,6 +90,7 @@ import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.MessageHeaderAccessor; +import org.springframework.scheduling.TaskScheduler; import org.springframework.stereotype.Component; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; @@ -340,6 +342,8 @@ public void testWithServiceEquals() { bf.registerSingleton("requestChannelBar", channel); bf.registerSingleton("requestChannelBaz", channel); bf.registerSingleton("requestChannelFoo", channel); + bf.registerSingleton("taskScheduler", mock(TaskScheduler.class)); + bf.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); fb.setBeanFactory(bf); fb.afterPropertiesSet(); assertThat(fb.getObject()).isNotSameAs(bar); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java index cab7bf480e3..5bd3a596312 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java @@ -22,13 +22,13 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.expression.FunctionExpression; import org.springframework.integration.mapping.MessageMappingException; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; @@ -37,20 +37,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Gary Russell * @author Artem Bilan */ -public class GatewayMethodInboundMessageMapperToMessageTests { +public class GatewayMethodInboundMessageMapperToMessageTests implements TestApplicationContextAware { @Test public void toMessageWithPayload() throws Exception { Method method = TestService.class.getMethod("sendPayload", String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test"}); assertThat(message.getPayload()).isEqualTo("test"); } @@ -59,7 +58,7 @@ public void toMessageWithPayload() throws Exception { public void toMessageWithTooManyParameters() throws Exception { Method method = TestService.class.getMethod("sendPayload", String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(() -> mapper.toMessage(new Object[] {"test", "oops"})); } @@ -68,7 +67,7 @@ public void toMessageWithTooManyParameters() throws Exception { public void toMessageWithEmptyParameterArray() throws Exception { Method method = TestService.class.getMethod("sendPayload", String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(() -> mapper.toMessage(new Object[] {})); } @@ -78,7 +77,7 @@ public void toMessageWithPayloadAndHeader() throws Exception { Method method = TestService.class.getMethod( "sendPayloadAndHeader", String.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test", "bar"}); assertThat(message.getPayload()).isEqualTo("test"); assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); @@ -89,7 +88,7 @@ public void toMessageWithPayloadAndRequiredHeaderButNullValue() throws Exception Method method = TestService.class.getMethod( "sendPayloadAndHeader", String.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageMappingException.class) .isThrownBy(() -> mapper.toMessage(new Object[] {"test", null})); } @@ -99,7 +98,7 @@ public void toMessageWithPayloadAndOptionalHeaderWithValueProvided() throws Exce Method method = TestService.class.getMethod( "sendPayloadAndOptionalHeader", String.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test", "bar"}); assertThat(message.getPayload()).isEqualTo("test"); assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); @@ -110,7 +109,7 @@ public void toMessageWithPayloadAndOptionalHeaderWithNullValue() throws Exceptio Method method = TestService.class.getMethod( "sendPayloadAndOptionalHeader", String.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test", null}); assertThat(message.getPayload()).isEqualTo("test"); assertThat(message.getHeaders().get("foo")).isNull(); @@ -121,7 +120,7 @@ public void toMessageWithPayloadAndHeadersMap() throws Exception { Method method = TestService.class.getMethod( "sendPayloadAndHeadersMap", String.class, Map.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Map headers = new HashMap<>(); headers.put("abc", 123); headers.put("def", 456); @@ -136,7 +135,7 @@ public void toMessageWithPayloadAndNullHeadersMap() throws Exception { Method method = TestService.class.getMethod( "sendPayloadAndHeadersMap", String.class, Map.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test", null}); assertThat(message.getPayload()).isEqualTo("test"); } @@ -146,7 +145,7 @@ public void toMessageWithPayloadAndHeadersMapWithNonStringKey() throws Exception Method method = TestService.class.getMethod( "sendPayloadAndHeadersMap", String.class, Map.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Map headers = new HashMap<>(); headers.put(123, "abc"); assertThatExceptionOfType(MessageMappingException.class) @@ -157,7 +156,7 @@ public void toMessageWithPayloadAndHeadersMapWithNonStringKey() throws Exception public void toMessageWithMessageParameter() throws Exception { Method method = TestService.class.getMethod("sendMessage", Message.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] {inputMessage}); assertThat(message.getPayload()).isEqualTo("test message"); @@ -167,7 +166,7 @@ public void toMessageWithMessageParameter() throws Exception { public void toMessageWithMessageParameterAndHeader() throws Exception { Method method = TestService.class.getMethod("sendMessageAndHeader", Message.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] {inputMessage, "bar"}); assertThat(message.getPayload()).isEqualTo("test message"); @@ -178,7 +177,7 @@ public void toMessageWithMessageParameterAndHeader() throws Exception { public void toMessageWithMessageParameterAndRequiredHeaderButNullValue() throws Exception { Method method = TestService.class.getMethod("sendMessageAndHeader", Message.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message inputMessage = MessageBuilder.withPayload("test message").build(); assertThatExceptionOfType(MessageMappingException.class) .isThrownBy(() -> mapper.toMessage(new Object[] {inputMessage, null})); @@ -188,7 +187,7 @@ public void toMessageWithMessageParameterAndRequiredHeaderButNullValue() throws public void toMessageWithMessageParameterAndOptionalHeaderWithValue() throws Exception { Method method = TestService.class.getMethod("sendMessageAndOptionalHeader", Message.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] {inputMessage, "bar"}); assertThat(message.getPayload()).isEqualTo("test message"); @@ -199,7 +198,7 @@ public void toMessageWithMessageParameterAndOptionalHeaderWithValue() throws Exc public void toMessageWithMessageParameterAndOptionalHeaderWithNull() throws Exception { Method method = TestService.class.getMethod("sendMessageAndOptionalHeader", Message.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] {inputMessage, null}); assertThat(message.getPayload()).isEqualTo("test message"); @@ -210,7 +209,7 @@ public void toMessageWithMessageParameterAndOptionalHeaderWithNull() throws Exce public void noArgs() throws Exception { Method method = TestService.class.getMethod("noArgs"); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageMappingException.class) .isThrownBy(() -> mapper.toMessage(new Object[] {})); } @@ -219,7 +218,7 @@ public void noArgs() throws Exception { public void onlyHeaders() throws Exception { Method method = TestService.class.getMethod("onlyHeaders", String.class, String.class); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageMappingException.class) .isThrownBy(() -> mapper.toMessage(new Object[] {"abc", "def"})); } @@ -232,7 +231,7 @@ public void toMessageWithPayloadAndHeaders() throws Exception { headers.put("bar", new SpelExpressionParser().parseExpression("6 * 7")); headers.put("baz", new LiteralExpression("hello")); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method, headers); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {"test"}); assertThat(message.getPayload()).isEqualTo("test"); assertThat(message.getHeaders().get("foo")).isEqualTo("foo"); @@ -246,7 +245,7 @@ public void toMessageWithNonHeaderMapPayloadExpressionA() throws Exception { map.put(1, "One"); map.put(2, "Two"); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); mapper.setPayloadExpression(new LiteralExpression("hello")); Message message = mapper.toMessage(new Object[] {map}); assertThat(message.getPayload()).isEqualTo("hello"); @@ -259,7 +258,7 @@ public void toMessageWithNonHeaderMapPayloadExpressionB() throws Exception { map.put(1, "One"); map.put(2, "Two"); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); mapper.setPayloadExpression(new FunctionExpression((methodArgs) -> methodArgs.getArgs()[0])); Message message = mapper.toMessage(new Object[] {map}); assertThat(message.getPayload()).isEqualTo(map); @@ -272,7 +271,7 @@ public void toMessageWithNonHeaderMapPayloadAnnotation() throws Exception { map.put(1, "One"); map.put(2, "Two"); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = mapper.toMessage(new Object[] {map}); assertThat(message.getPayload()).isEqualTo(map); } @@ -287,7 +286,7 @@ public void toMessageWithTwoMapsOneNonHeaderPayloadExpression() throws Exception mapB.put("1", "ONE"); mapB.put("2", "TWO"); GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); - mapper.setBeanFactory(mock(BeanFactory.class)); + mapper.setBeanFactory(TEST_INTEGRATION_CONTEXT); mapper.setPayloadExpression(new FunctionExpression((methodArgs) -> methodArgs.getArgs()[0])); Message message = mapper.toMessage(new Object[] {mapA, mapB}); assertThat(message.getPayload()).isEqualTo(mapA); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java index 80fd8fd7c09..551128e62d9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java @@ -36,12 +36,14 @@ import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.expression.MapAccessor; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.annotation.AliasFor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.expression.common.LiteralExpression; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.IntegrationPatternType; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.GatewayHeader; @@ -52,6 +54,7 @@ import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.handler.BridgeHandler; import org.springframework.integration.support.utils.IntegrationUtils; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; @@ -59,15 +62,19 @@ import org.springframework.messaging.PollableChannel; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.TaskScheduler; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; /** * @author Mark Fisher @@ -77,7 +84,7 @@ * @author Artem Bilan * @author JingPeng Xie */ -public class GatewayProxyFactoryBeanTests { +public class GatewayProxyFactoryBeanTests implements TestApplicationContextAware { @Test public void testRequestReplyWithAnonymousChannel() { @@ -85,7 +92,7 @@ public void testRequestReplyWithAnonymousChannel() { startResponder(requestChannel); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.setBeanName("testGateway"); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); @@ -113,7 +120,9 @@ public byte[] convert(String source) { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, cs); - + bf.registerSingleton("taskScheduler", mock(TaskScheduler.class)); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + bf.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, evaluationContext); proxyFactory.setBeanFactory(bf); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); @@ -121,7 +130,7 @@ public byte[] convert(String source) { TestService service = proxyFactory.getObject(); byte[] result = service.requestReplyInBytes("foo"); assertThat(result.length).isEqualTo(6); - Mockito.verify(stringToByteConverter, Mockito.times(1)).convert(Mockito.any(String.class)); + Mockito.verify(stringToByteConverter, Mockito.times(1)).convert(any(String.class)); } @Test @@ -130,7 +139,7 @@ public void testOneWay() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); service.oneWay("test"); @@ -142,7 +151,18 @@ public void testOneWay() { @Test public void testOneWayIgnoreReply() { DirectChannel requestChannel = new DirectChannel(); - BeanFactory beanFactory = mock(BeanFactory.class); + BeanFactory beanFactory = mock(); + TaskScheduler taskScheduler = mock(TaskScheduler.class); + when(beanFactory.getBean(eq("taskScheduler"), any(Class.class))) + .thenReturn(taskScheduler); + when(beanFactory.containsBean("taskScheduler")).thenReturn(true); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + evaluationContext.addPropertyAccessor(new MapAccessor()); + when(beanFactory.containsBean(eq("integrationEvaluationContext"))) + .thenReturn(true); + when(beanFactory.getBean(eq("integrationEvaluationContext"), any(Class.class))) + .thenReturn(evaluationContext); + QueueChannel nullChannel = new QueueChannel(); willReturn(nullChannel) .given(beanFactory) @@ -173,7 +193,7 @@ public void testSolicitResponse() { proxyFactory.setDefaultRequestChannel(new DirectChannel()); proxyFactory.setDefaultReplyChannel(replyChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); String result = service.solicitResponse(); @@ -188,7 +208,7 @@ public void testReceiveMessage() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultReplyChannel(replyChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); Message message = service.getMessage(); @@ -210,7 +230,7 @@ public void testReactiveReplyChannel() { proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setDefaultReplyChannel(replyChannel); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); @@ -229,7 +249,7 @@ public void testRequestReplyWithTypeConversion() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); Integer result = service.requestReplyWithIntegers(123); @@ -300,7 +320,7 @@ public void testMessageAsMethodArgument() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); String result = service.requestReplyWithMessageParameter(new GenericMessage<>("foo")); @@ -314,7 +334,7 @@ public void testNoArgMethodWithPayloadAnnotation() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); String result = service.requestReplyWithPayloadAnnotation(); @@ -338,7 +358,7 @@ public void testMessageAsReturnValue() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(requestChannel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestService service = proxyFactory.getObject(); Message result = service.requestReplyWithMessageReturnValue("foo"); @@ -356,7 +376,7 @@ public void testProxiedToStringMethod() { GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean<>(TestService.class); proxyFactory.setDefaultRequestChannel(new DirectChannel()); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); Object proxy = proxyFactory.getObject(); String expected = "gateway proxy for"; @@ -380,7 +400,7 @@ public void handleMessage(Message message) { consumer.start(); proxyFactory.setDefaultRequestChannel(channel); proxyFactory.setBeanName("testGateway"); - proxyFactory.setBeanFactory(mock(BeanFactory.class)); + proxyFactory.setBeanFactory(getBeanFactory()); proxyFactory.afterPropertiesSet(); TestExceptionThrowingInterface proxy = proxyFactory.getObject(); assertThatExceptionOfType(TestException.class) @@ -398,7 +418,7 @@ private static void startResponder(final PollableChannel requestChannel) { @Test public void testProgrammaticWiring() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(TestEchoService.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(getBeanFactory()); QueueChannel drc = new QueueChannel(); gpfb.setDefaultRequestChannel(drc); gpfb.setDefaultReplyTimeout(0L); @@ -414,10 +434,16 @@ public void testProgrammaticWiring() { assertThat(bar).isEqualTo("bar"); } + private BeanFactory getBeanFactory() { + TaskScheduler taskScheduler = mock(TaskScheduler.class); + TEST_INTEGRATION_CONTEXT.registerBean("taskScheduler", taskScheduler); + return TEST_INTEGRATION_CONTEXT; + } + @Test public void testIdHeaderOverrideHeaderExpression() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(TEST_INTEGRATION_CONTEXT); GatewayMethodMetadata meta = new GatewayMethodMetadata(); meta.setHeaderExpressions(Collections.singletonMap(MessageHeaders.ID, new LiteralExpression("bar"))); @@ -432,7 +458,7 @@ public void testIdHeaderOverrideHeaderExpression() { public void testIdHeaderOverrideGatewayHeaderAnnotation() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(HeadersOverwriteService.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(BeanInitializationException.class) .isThrownBy(gpfb::afterPropertiesSet) @@ -442,7 +468,7 @@ public void testIdHeaderOverrideGatewayHeaderAnnotation() { @Test public void testTimeStampHeaderOverrideParamHeaderAnnotation() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(HeadersParamService.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(BeanInitializationException.class) .isThrownBy(gpfb::afterPropertiesSet) @@ -495,7 +521,7 @@ public void autowiredGateway() { @Test public void testOverriddenMethod() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(InheritChild.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(getBeanFactory()); gpfb.afterPropertiesSet(); Map gateways = gpfb.getGateways(); assertThat(gateways.size()).isEqualTo(2); @@ -508,6 +534,8 @@ public void testAliasForSupport() throws NoSuchMethodException { beanFactory.registerSingleton("requestChannel", requestChannel); GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>( CompositedGatewayService.class); + beanFactory.registerSingleton("taskScheduler", mock(TaskScheduler.class)); + beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); gpfb.setBeanFactory(beanFactory); gpfb.afterPropertiesSet(); Map gateways = gpfb.getGateways(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java index 8424e331275..ea9100d2039 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java @@ -32,9 +32,11 @@ import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.scheduling.TaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -58,6 +60,8 @@ public void initializeGateway() { context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class)); context.refresh(); + context.getBeanFactory().registerSingleton("taskScheduler", mock(TaskScheduler.class)); + factoryBean.setBeanFactory(context); factoryBean.afterPropertiesSet(); this.gateway = factoryBean.getObject(); @@ -144,6 +148,7 @@ public void payloadAnnotationAtMethodLevelUsingBeanResolver() { context.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class)); + context.getBeanFactory().registerSingleton("taskScheduler", mock(TaskScheduler.class)); context.refresh(); TestGateway gateway = context.getBean("testGateway", TestGateway.class); gateway.payloadAnnotationAtMethodLevelUsingBeanResolver("foo"); @@ -171,6 +176,7 @@ public void payloadAnnotationWithExpressionUsingBeanResolver() { context.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class)); + context.getBeanFactory().registerSingleton("taskScheduler", mock(TaskScheduler.class)); context.refresh(); TestGateway gateway = context.getBean("testGateway", TestGateway.class); gateway.payloadAnnotationWithExpressionUsingBeanResolver("foo"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java index f0c682eeafd..68e9fa382f5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java @@ -28,10 +28,10 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.PublishSubscribeChannel; import org.springframework.integration.handler.ServiceActivatingHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; @@ -44,7 +44,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Iwein Fuld @@ -53,7 +52,7 @@ * @author Gary Russell */ @SuppressWarnings("unchecked") -public class MessagingGatewayTests { +public class MessagingGatewayTests implements TestApplicationContextAware { private final TestApplicationContext applicationContext = TestUtils.createTestApplicationContext(); @@ -283,7 +282,7 @@ public void validateErrorChannelWithSuccessfulReply() throws InterruptedExceptio this.messagingGateway.setRequestChannel(reqChannel); this.messagingGateway.setErrorChannel(errorChannel); this.messagingGateway.setReplyChannel(null); - this.messagingGateway.setBeanFactory(mock(BeanFactory.class)); + this.messagingGateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.messagingGateway.afterPropertiesSet(); this.messagingGateway.start(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/graph/IntegrationGraphServerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/graph/IntegrationGraphServerTests.java index 139c49a5f44..9fd6b7b2c7a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/graph/IntegrationGraphServerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/graph/IntegrationGraphServerTests.java @@ -265,6 +265,7 @@ void testIncludesDynamic() { @Test void timersViaObservationArePopulated() { MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(beanFactory); assertThat(messagingTemplate.convertSendAndReceive(this.filterInputChannel, "test", String.class)) .isEqualTo("test"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java index a01b4073086..9f2869d3623 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java @@ -34,6 +34,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.gateway.GatewayProxyFactoryBean; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; @@ -41,6 +42,7 @@ import org.springframework.messaging.core.DestinationResolutionException; import org.springframework.messaging.support.GenericMessage; import org.springframework.messaging.support.MessageBuilder; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -55,7 +57,7 @@ * @since 4.3 * */ -public class AsyncHandlerTests { +public class AsyncHandlerTests implements TestApplicationContextAware { private final QueueChannel output = new QueueChannel(); @@ -218,14 +220,17 @@ public void testMessagingExceptionNoErrorChannel() throws Exception { public void testGateway() { this.whichTest = 0; GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(Foo.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(mock()); + gpfb.setTaskScheduler(new SimpleAsyncTaskScheduler()); DirectChannel input = new DirectChannel(); gpfb.setDefaultRequestChannel(input); gpfb.setDefaultReplyTimeout(10000L); + gpfb.setBeanFactory(TEST_INTEGRATION_CONTEXT); gpfb.afterPropertiesSet(); Foo foo = gpfb.getObject(); this.handler.setOutputChannel(null); EventDrivenConsumer consumer = new EventDrivenConsumer(input, this.handler); + consumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); consumer.afterPropertiesSet(); consumer.start(); this.latch.countDown(); @@ -237,14 +242,17 @@ public void testGateway() { public void testGatewayWithException() { this.whichTest = 0; GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean<>(Foo.class); - gpfb.setBeanFactory(mock(BeanFactory.class)); + gpfb.setBeanFactory(mock()); + gpfb.setTaskScheduler(new SimpleAsyncTaskScheduler()); DirectChannel input = new DirectChannel(); gpfb.setDefaultRequestChannel(input); gpfb.setDefaultReplyTimeout(10000L); + gpfb.setBeanFactory(TEST_INTEGRATION_CONTEXT); gpfb.afterPropertiesSet(); Foo foo = gpfb.getObject(); this.handler.setOutputChannel(null); EventDrivenConsumer consumer = new EventDrivenConsumer(input, this.handler); + consumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); consumer.afterPropertiesSet(); consumer.start(); this.latch.countDown(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java index 97002eea692..3c17660ed51 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java @@ -32,7 +32,6 @@ import org.mockito.Mockito; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.StaticApplicationContext; import org.springframework.expression.Expression; @@ -46,6 +45,7 @@ import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; @@ -59,7 +59,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -69,7 +68,7 @@ * * @since 1.0.3 */ -public class DelayHandlerTests { +public class DelayHandlerTests implements TestApplicationContextAware { private static final String DELAYER_MESSAGE_GROUP_ID = "testDelayer.messageGroupId"; @@ -95,7 +94,7 @@ public void setup() { taskScheduler.afterPropertiesSet(); delayHandler = new DelayHandler(DELAYER_MESSAGE_GROUP_ID, taskScheduler); delayHandler.setOutputChannel(output); - delayHandler.setBeanFactory(mock(BeanFactory.class)); + delayHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); input.subscribe(delayHandler); output.subscribe(resultHandler); } @@ -443,7 +442,7 @@ public void testReschedulePersistedMessagesOnStartup() throws Exception { this.delayHandler.setOutputChannel(output); this.delayHandler.setDefaultDelay(200); this.delayHandler.setMessageStore(messageGroupStore); - this.delayHandler.setBeanFactory(mock(BeanFactory.class)); + this.delayHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); startDelayerHandler(); waitForLatch(10000); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java index 8f70f68f890..ac53c8de84c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.AbstractApplicationContext; @@ -36,6 +35,7 @@ import org.springframework.integration.config.IntegrationEvaluationContextFactoryBean; import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; @@ -43,7 +43,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Dave Syer @@ -54,7 +53,7 @@ * * @since 2.0 */ -public class ExpressionEvaluatingMessageProcessorTests { +public class ExpressionEvaluatingMessageProcessorTests implements TestApplicationContextAware { private static final ExpressionParser expressionParser = new SpelExpressionParser(); @@ -63,7 +62,7 @@ public void testProcessMessage() { Expression expression = expressionParser.parseExpression("payload"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(processor.processMessage(new GenericMessage<>("foo"))).isEqualTo("foo"); } @@ -81,7 +80,7 @@ public String stringify(int number) { Expression expression = expressionParser.parseExpression("#target.stringify(payload)"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.afterPropertiesSet(); EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext", EvaluationContext.class); @@ -102,7 +101,7 @@ public void ping(String input) { Expression expression = expressionParser.parseExpression("#target.ping(payload)"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.afterPropertiesSet(); EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext", EvaluationContext.class); @@ -146,7 +145,7 @@ public void testProcessMessageWithDollarInBrackets() { Expression expression = expressionParser.parseExpression("headers['$foo_id']"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo").setHeader("$foo_id", "abc").build(); assertThat(processor.processMessage(message)).isEqualTo("abc"); } @@ -156,7 +155,7 @@ public void testProcessMessageWithDollarPropertyAccess() { Expression expression = expressionParser.parseExpression("headers.$foo_id"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo").setHeader("$foo_id", "xyz").build(); assertThat(processor.processMessage(message)).isEqualTo("xyz"); } @@ -165,7 +164,7 @@ public void testProcessMessageWithDollarPropertyAccess() { public void testProcessMessageWithStaticKey() { Expression expression = expressionParser.parseExpression("headers[headers.ID]"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); GenericMessage message = new GenericMessage<>("foo"); assertThat(processor.processMessage(message)).isEqualTo(message.getHeaders().getId()); } @@ -213,7 +212,7 @@ public void testProcessMessageBadExpression() { Expression expression = expressionParser.parseExpression("payload.fixMe()"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) .withCauseInstanceOf(EvaluationException.class); @@ -224,7 +223,7 @@ public void testProcessMessageExpressionThrowsRuntimeException() { Expression expression = expressionParser.parseExpression("payload.throwRuntimeException()"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>(new TestPayload()))) .withCauseInstanceOf(UnsupportedOperationException.class); @@ -235,7 +234,7 @@ public void testProcessMessageExpressionThrowsCheckedException() { Expression expression = expressionParser.parseExpression("payload.throwCheckedException()"); ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>(new TestPayload()))) .withCauseInstanceOf(CheckedException.class); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java index 7f9b126d112..c9b49fb494b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java @@ -18,17 +18,16 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.MessageTransformingHandler; import org.springframework.integration.transformer.MethodInvokingTransformer; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -37,14 +36,14 @@ * * @since 2.0 */ -public class HeaderAnnotationTransformerTests { +public class HeaderAnnotationTransformerTests implements TestApplicationContextAware { @Test // INT-1082 public void headerAnnotationWithPrefixedHeader() { Object target = new TestTransformer(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(target, "appendCorrelationId"); MessageTransformingHandler handler = new MessageTransformingHandler(transformer); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); @@ -60,7 +59,7 @@ public void headerAnnotationWithPrefixedHeaderAndRelativeExpression() { Object target = new TestTransformer(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(target, "evalCorrelationId"); MessageTransformingHandler handler = new MessageTransformingHandler(transformer); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); @@ -76,7 +75,7 @@ public void headerAnnotationWithUnprefixedHeader() { Object target = new TestTransformer(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(target, "appendFoo"); MessageTransformingHandler handler = new MessageTransformingHandler(transformer); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); @@ -92,7 +91,7 @@ public void headerAnnotationWithUnprefixedHeaderAndRelativeExpression() { Object target = new TestTransformer(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(target, "evalFoo"); MessageTransformingHandler handler = new MessageTransformingHandler(transformer); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); @@ -108,7 +107,7 @@ public void testNotPropagatedHeaders() { Object target = new TestTransformer(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(target, "evalFoo"); MessageTransformingHandler handler = new MessageTransformingHandler(transformer); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setNotPropagatedHeaders(IntegrationMessageHeaderAccessor.CORRELATION_ID); handler.afterPropertiesSet(); QueueChannel outputChannel = new QueueChannel(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java index 41659eee307..3d13a1500f0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java @@ -23,7 +23,6 @@ import org.mockito.ArgumentMatchers; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.log.LogAccessor; @@ -32,6 +31,7 @@ import org.springframework.integration.handler.LoggingHandler.Level; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -41,7 +41,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -58,7 +57,7 @@ @SpringJUnitConfig @DirtiesContext @LogLevels(categories = "test.logging.handler") -public class LoggingHandlerTests { +public class LoggingHandlerTests implements TestApplicationContextAware { @Autowired @Qualifier("input.handler") @@ -101,7 +100,7 @@ public void assertMutuallyExclusive() { public void testDontEvaluateIfNotEnabled() { LoggingHandler loggingHandler = new LoggingHandler("INFO"); loggingHandler.setLoggerName("test.logging.handler"); - loggingHandler.setBeanFactory(mock(BeanFactory.class)); + loggingHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); loggingHandler.afterPropertiesSet(); LogAccessor logAccessor = TestUtils.getPropertyValue(loggingHandler, "messageLogger", LogAccessor.class); @@ -120,7 +119,7 @@ public void testDontEvaluateIfNotEnabled() { @SuppressWarnings("unchecked") public void testChangeLevel() { LoggingHandler loggingHandler = new LoggingHandler(Level.INFO); - loggingHandler.setBeanFactory(mock(BeanFactory.class)); + loggingHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); loggingHandler.afterPropertiesSet(); DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java index 94c0e5da0b3..e3908ea2e09 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java @@ -22,9 +22,9 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.HeaderEnricher; import org.springframework.integration.transformer.support.StaticHeaderValueMessageProcessor; import org.springframework.messaging.Message; @@ -33,7 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -41,14 +40,14 @@ * * @since 2.0 */ -public class MethodInvokingHeaderEnricherTests { +public class MethodInvokingHeaderEnricherTests implements TestApplicationContextAware { @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void emptyHeadersOnRequest() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(true); @@ -63,7 +62,7 @@ public void emptyHeadersOnRequest() { public void overwriteFalseByDefault() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); Message message = MessageBuilder.withPayload("test").setHeader("bar", "XYZ").build(); @@ -77,7 +76,7 @@ public void overwriteFalseByDefault() { public void overwriteFalseExplicit() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(false); @@ -92,7 +91,7 @@ public void overwriteFalseExplicit() { public void overwriteTrue() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(true); @@ -109,6 +108,7 @@ public void overwriteId() { new StaticHeaderValueMessageProcessor<>("foo"))); try { + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); fail("BeanInitializationException expected"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java index 9b87616c0cf..e146085c15d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java @@ -31,8 +31,8 @@ import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; @@ -45,7 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -55,7 +54,7 @@ * @author Artem Bilan */ @SuppressWarnings({"rawtypes", "unchecked"}) -public class MethodInvokingMessageProcessorAnnotationTests { +public class MethodInvokingMessageProcessorAnnotationTests implements TestApplicationContextAware { private final TestService testService = new TestService(); @@ -67,7 +66,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { public void multiThreadsUUIDToStringConversion() throws Exception { Method method = TestService.class.getMethod("headerId", String.class, String.class); final MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); ExecutorService exec = Executors.newFixedThreadPool(100); processor.processMessage(new GenericMessage<>("foo")); for (int i = 0; i < 100; i++) { @@ -82,7 +81,7 @@ public void multiThreadsUUIDToStringConversion() throws Exception { public void optionalHeader() throws Exception { Method method = TestService.class.getMethod("optionalHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("foo")); assertThat(result).isNull(); } @@ -91,7 +90,7 @@ public void optionalHeader() throws Exception { public void requiredHeaderNotProvided() throws Exception { Method method = TestService.class.getMethod("requiredHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))); } @@ -100,7 +99,7 @@ public void requiredHeaderNotProvided() throws Exception { public void requiredHeaderNotProvidedOnSecondMessage() throws Exception { Method method = TestService.class.getMethod("requiredHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message messageWithHeader = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); GenericMessage messageWithoutHeader = new GenericMessage<>("foo"); @@ -116,7 +115,7 @@ public void fromMessageWithRequiredHeaderProvided() throws Exception { Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(message); assertThat(result).isEqualTo(123); } @@ -125,7 +124,7 @@ public void fromMessageWithRequiredHeaderProvided() throws Exception { public void fromMessageWithOptionalAndRequiredHeaderAndOnlyOptionalHeaderProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("prop", "bar").build(); @@ -137,7 +136,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndOnlyOptionalHeaderProvide public void fromMessageWithOptionalAndRequiredHeaderAndOnlyRequiredHeaderProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); Object result = processor.processMessage(message); @@ -148,7 +147,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndOnlyRequiredHeaderProvide public void fromMessageWithOptionalAndRequiredHeaderAndBothHeadersProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123) .setHeader("prop", "bar") @@ -161,7 +160,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndBothHeadersProvided() thr public void fromMessageWithPropertiesMethodAndHeadersAnnotation() throws Exception { Method method = TestService.class.getMethod("propertiesHeaders", Properties.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)).isFalse(); @@ -186,7 +185,7 @@ public void fromMessageWithPropertiesMethodAndHeadersAnnotation() throws Excepti public void fromMessageWithPropertiesAndObjectMethod() throws Exception { Method method = TestService.class.getMethod("propertiesHeadersAndPayload", Properties.class, Object.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Object result = processor.processMessage(message); @@ -200,7 +199,7 @@ public void fromMessageWithPropertiesAndObjectMethod() throws Exception { public void fromMessageWithMapAndObjectMethod() throws Exception { Method method = TestService.class.getMethod("mapHeadersAndPayload", Map.class, Object.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Map result = (Map) processor.processMessage(message); @@ -216,7 +215,7 @@ public void fromMessageWithMapAndObjectMethod() throws Exception { public void fromMessageWithPropertiesMethodAndPropertiesPayload() throws Exception { Method method = TestService.class.getMethod("propertiesPayload", Properties.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Properties payload = new Properties(); payload.setProperty("prop1", "foo"); payload.setProperty("prop2", "bar"); @@ -232,7 +231,7 @@ public void fromMessageWithPropertiesMethodAndPropertiesPayload() throws Excepti public void fromMessageWithMapMethodAndHeadersAnnotation() throws Exception { Method method = TestService.class.getMethod("mapHeaders", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test") .setHeader("attrib1", 123) .setHeader("attrib2", 456).build(); @@ -245,7 +244,7 @@ public void fromMessageWithMapMethodAndHeadersAnnotation() throws Exception { public void fromMessageWithMapMethodAndMapPayload() throws Exception { Method method = TestService.class.getMethod("mapPayload", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Map payload = new HashMap<>(); payload.put("attrib1", 88); payload.put("attrib2", 99); @@ -263,7 +262,7 @@ public void headerAnnotationWithExpression() throws Exception { Message message = this.getMessage(); Method method = TestService.class.getMethod("headerAnnotationWithExpression", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(message); assertThat(result).isEqualTo("monday"); } @@ -273,7 +272,7 @@ public void irrelevantAnnotation() throws Exception { Message message = MessageBuilder.withPayload("foo").build(); Method method = TestService.class.getMethod("irrelevantAnnotation", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(message); assertThat(result).isEqualTo("foo"); } @@ -288,7 +287,7 @@ public void multipleAnnotatedArgs() throws Exception { String.class, Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object[] parameters = (Object[]) processor.processMessage(message); assertThat(parameters).isNotNull(); assertThat(parameters.length).isEqualTo(5); @@ -303,7 +302,7 @@ public void multipleAnnotatedArgs() throws Exception { public void fromMessageToPayload() throws Exception { Method method = TestService.class.getMethod("mapOnly", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); assertThat(result instanceof Map).isTrue(); @@ -314,7 +313,7 @@ public void fromMessageToPayload() throws Exception { public void fromMessageToPayloadArg() throws Exception { Method method = TestService.class.getMethod("payloadAnnotationFirstName", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); assertThat(result instanceof String).isTrue(); @@ -325,7 +324,7 @@ public void fromMessageToPayloadArg() throws Exception { public void fromMessageToPayloadArgs() throws Exception { Method method = TestService.class.getMethod("payloadAnnotationFullName", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); assertThat(result).isEqualTo("oleg zhurakousky"); @@ -335,7 +334,7 @@ public void fromMessageToPayloadArgs() throws Exception { public void fromMessageToPayloadArgsHeaderArgs() throws Exception { Method method = TestService.class.getMethod("payloadArgAndHeaderArg", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload(employee).setHeader("day", "monday").build(); Object result = processor.processMessage(message); assertThat(result).isEqualTo("olegmonday"); @@ -352,7 +351,7 @@ public void fromMessageInvalidMethodWithMultipleMappingAnnotations() throws Exce public void fromMessageToHeadersWithExpressions() throws Exception { Method method = TestService.class.getMethod("headersWithExpressions", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Employee employee = new Employee("John", "Doe"); Message message = MessageBuilder.withPayload("payload").setHeader("emp", employee).build(); Object result = processor.processMessage(message); @@ -363,7 +362,7 @@ public void fromMessageToHeadersWithExpressions() throws Exception { public void fromMessageToHyphenatedHeaderName() throws Exception { Method method = TestService.class.getMethod("headerNameWithHyphen", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("payload").setHeader("foo-bar", "abc").build(); Object result = processor.processMessage(message); assertThat(result).isEqualTo("ABC"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java index db00844a123..f587ae2d43f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java @@ -41,13 +41,13 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.Lifecycle; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.MapAccessor; import org.springframework.core.MethodParameter; import org.springframework.expression.Expression; import org.springframework.expression.spel.SpelCompilerMode; @@ -64,6 +64,7 @@ import org.springframework.integration.gateway.RequestReplyExchanger; import org.springframework.integration.handler.support.MessagingMethodInvokerHelper; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -79,6 +80,7 @@ import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory; import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; @@ -87,9 +89,12 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * @author Mark Fisher @@ -101,7 +106,7 @@ * @author Artem Bilan */ @SuppressWarnings({"rawtypes", "unchecked"}) -public class MethodInvokingMessageProcessorTests { +public class MethodInvokingMessageProcessorTests implements TestApplicationContextAware { private static final Log logger = LogFactory.getLog(MethodInvokingMessageProcessorTests.class); @@ -188,7 +193,7 @@ class C extends B { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertThat(message.getHeaders().get("A")).isEqualTo("A"); } @@ -219,7 +224,7 @@ class C extends B { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertThat(message.getHeaders().get("B")).isEqualTo("B"); } @@ -254,7 +259,7 @@ public Message myMethod(Message msg) { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new C(), "myMethod"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertThat(message.getHeaders().get("C")).isEqualTo("C"); } @@ -284,7 +289,7 @@ public Message myMethod(Message msg) { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new C(), "myMethod"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertThat(message.getHeaders().get("C")).isEqualTo("C"); } @@ -293,7 +298,7 @@ public Message myMethod(Message msg) { public void payloadAsMethodParameterAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnObject"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("testing")); assertThat(result).isEqualTo("testing-1"); } @@ -302,7 +307,7 @@ public void payloadAsMethodParameterAndObjectAsReturnValue() { public void testPayloadCoercedToString() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnObject"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>(123456789)); assertThat(result).isEqualTo("123456789-1"); } @@ -311,7 +316,7 @@ public void testPayloadCoercedToString() { public void payloadAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnMessage"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertThat(result.getPayload()).isEqualTo("testing-2"); } @@ -320,7 +325,7 @@ public void payloadAsMethodParameterAndMessageAsReturnValue() { public void messageAsMethodParameterAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageAndReturnObject"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("testing")); assertThat(result).isEqualTo("testing-3"); } @@ -329,7 +334,7 @@ public void messageAsMethodParameterAndObjectAsReturnValue() { public void messageAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageAndReturnMessage"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertThat(result.getPayload()).isEqualTo("testing-4"); } @@ -338,7 +343,7 @@ public void messageAsMethodParameterAndMessageAsReturnValue() { public void messageSubclassAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageSubclassAndReturnMessage"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertThat(result.getPayload()).isEqualTo("testing-5"); } @@ -347,7 +352,7 @@ public void messageSubclassAsMethodParameterAndMessageAsReturnValue() { public void messageSubclassAsMethodParameterAndMessageSubclassAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageSubclassAndReturnMessageSubclass"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertThat(result.getPayload()).isEqualTo("testing-6"); } @@ -356,7 +361,7 @@ public void messageSubclassAsMethodParameterAndMessageSubclassAsReturnValue() { public void payloadAndHeaderAnnotationMethodParametersAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndHeaderAndReturnObject"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message request = MessageBuilder.withPayload("testing").setHeader("number", 123).build(); Object result = processor.processMessage(request); assertThat(result).isEqualTo("testing-123"); @@ -366,7 +371,7 @@ public void payloadAndHeaderAnnotationMethodParametersAndObjectAsReturnValue() { public void testVoidMethodsIncludedByDefault() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "testVoidReturningMethods"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(processor.processMessage(MessageBuilder.withPayload("Something").build())).isNull(); assertThat(processor.processMessage(MessageBuilder.withPayload(12).build())).isEqualTo(12); } @@ -376,7 +381,7 @@ public void messageOnlyWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageOnly", Message.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("foo")); assertThat(result).isEqualTo("foo"); } @@ -386,7 +391,7 @@ public void payloadWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>(123)); assertThat(result).isEqualTo(123); } @@ -396,7 +401,7 @@ public void convertedPayloadWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("456")); assertThat(result).isEqualTo(456); } @@ -406,7 +411,7 @@ public void conversionFailureWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageConversionException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))); } @@ -415,7 +420,7 @@ public void conversionFailureWithAnnotatedMethod() throws Exception { public void filterSelectsAnnotationMethodsOnly() { OverloadedMethodBean bean = new OverloadedMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, ServiceActivator.class); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.processMessage(MessageBuilder.withPayload(123).build()); assertThat(bean.lastArg).isNotNull(); assertThat(bean.lastArg.getClass()).isEqualTo(String.class); @@ -427,7 +432,7 @@ public void testProcessMessageBadExpression() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageConversionException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) .withMessageContaining("Failed to convert message payload 'foo' to 'java.lang.Integer'"); @@ -438,7 +443,7 @@ public void testProcessMessageRuntimeException() throws Exception { TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("error", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) .withCauseInstanceOf(UnsupportedOperationException.class); @@ -449,7 +454,7 @@ public void testProcessMessageCheckedException() throws Exception { TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) .withRootCauseInstanceOf(CheckedException.class); @@ -462,7 +467,7 @@ public void testProcessMessageMethodNotFound() throws Exception { Method method = TestErrorService.class.getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) .withCauseInstanceOf(SpelEvaluationException.class); @@ -473,7 +478,7 @@ public void messageAndHeaderWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageAndHeader", Message.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo").setHeader("number", 42).build(); Object result = processor.processMessage(message); assertThat(result).isEqualTo("foo-42"); @@ -484,7 +489,7 @@ public void multipleHeadersWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("twoHeaders", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("prop", "bar") @@ -518,7 +523,7 @@ public void compiledOptionalAndRequiredWithAnnotatedMethod() throws Exception { private void optionalAndRequiredWithAnnotatedMethodGuts(MethodInvokingMessageProcessor processor) { - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 42) .build(); @@ -566,7 +571,7 @@ public void compiledOptionalAndRequiredDottedWithAnnotatedMethod() throws Except private void optionalAndRequiredDottedWithAnnotatedMethodGuts(MethodInvokingMessageProcessor processor) { - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("hello") .setHeader("dot2", new DotBean()) .setHeader("dotted.literal", "dotted") @@ -595,7 +600,7 @@ private void optionalAndRequiredDottedWithAnnotatedMethodGuts(MethodInvokingMess public void testOverloadedNonVoidReturningMethodsWithExactMatchForType() { AmbiguousMethodBean bean = new AmbiguousMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.processMessage(MessageBuilder.withPayload("true").build()); assertThat(bean.lastArg).isNotNull(); assertThat(bean.lastArg.getClass()).isEqualTo(String.class); @@ -605,7 +610,9 @@ public void testOverloadedNonVoidReturningMethodsWithExactMatchForType() { @Test public void gatewayTest() throws Exception { GatewayProxyFactoryBean gwFactoryBean = new GatewayProxyFactoryBean<>(); - gwFactoryBean.setBeanFactory(mock(BeanFactory.class)); + gwFactoryBean.setTaskScheduler(new SimpleAsyncTaskScheduler()); + gwFactoryBean.setBeanFactory(TEST_INTEGRATION_CONTEXT); + gwFactoryBean.afterPropertiesSet(); Object target = gwFactoryBean.getObject(); // just instantiate a helper with a simple target; we're going to invoke getTargetClass with reflection @@ -640,7 +647,7 @@ public String voidMethod() { } MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(new Foo(), (String) null, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(helper.process(new GenericMessage(2L))).isEqualTo("4"); assertThat(helper.process(new GenericMessage(1))).isEqualTo("1"); assertThat(helper.process(new GenericMessage(new Date()))).isEqualTo("foo"); @@ -693,7 +700,7 @@ public Object m3(Message message) { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); assertThat(helper.process(new GenericMessage(1))).isEqualTo(1); assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo(targetObject); @@ -724,7 +731,7 @@ public Object m3(Object payload) { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); assertThat(helper.process(new GenericMessage(1))).isEqualTo(1); assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo(targetObject); @@ -756,7 +763,7 @@ public Object m3() { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo("FOO"); } @@ -765,7 +772,7 @@ public Object m3() { public void testIneligible() { IneligibleMethodBean bean = new IneligibleMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.processMessage(MessageBuilder.withPayload("true").build()); assertThat(bean.lastArg).isNotNull(); assertThat(bean.lastArg.getClass()).isEqualTo(String.class); @@ -791,7 +798,7 @@ public void optionalHeaders(Optional foo, @Header(value = "foo", require Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(new GenericMessage<>(Optional.empty())); assertThat(targetObject.arguments.get("foo")).isNull(); @@ -817,7 +824,7 @@ private String service(String payload) { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(new Foo(), ServiceActivator.class, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(helper.process(new GenericMessage<>("foo"))).isEqualTo("FOO"); assertThat(helper.process(new GenericMessage<>("bar"))).isEqualTo("BAR"); @@ -830,7 +837,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload(42).build(); @@ -845,7 +852,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { @@ -857,7 +864,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { @@ -881,7 +888,7 @@ public void myMethod(Object payload) { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new A(), "myMethod"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { processor.processMessage(new GenericMessage<>("foo")); } @@ -917,7 +924,7 @@ public void handleMessage(Message message) throws MessagingException { service = (MessageHandler) proxyFactory.getProxy(getClass().getClassLoader()); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, "handleMessage"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.processMessage(new GenericMessage<>("foo")); @@ -952,7 +959,7 @@ public void handle(@Header(MessageHeaders.ID) UUID id, @Payload Object payload) GenericMessage testMessage = new GenericMessage<>("foo"); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, "handle"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); processor.processMessage(testMessage); @@ -967,7 +974,7 @@ public void testUseSpelInvoker() throws Exception { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(bean, UseSpelInvokerBean.class.getDeclaredMethod("foo", String.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("Test"); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) @@ -975,28 +982,28 @@ public void testUseSpelInvoker() throws Exception { helper = new MessagingMethodInvokerHelper(bean, UseSpelInvokerBean.class.getDeclaredMethod("bar", String.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) .isEqualTo(SpelCompilerMode.IMMEDIATE); helper = new MessagingMethodInvokerHelper(bean, UseSpelInvokerBean.class.getDeclaredMethod("baz", String.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) .isEqualTo(SpelCompilerMode.MIXED); helper = new MessagingMethodInvokerHelper(bean, UseSpelInvokerBean.class.getDeclaredMethod("qux", String.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) .isEqualTo(SpelCompilerMode.OFF); helper = new MessagingMethodInvokerHelper(bean, UseSpelInvokerBean.class.getDeclaredMethod("fiz", String.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { helper.process(message); } @@ -1009,6 +1016,12 @@ public void testUseSpelInvoker() throws Exception { UseSpelInvokerBean.class.getDeclaredMethod("buz", String.class), false); ConfigurableListableBeanFactory bf = mock(ConfigurableListableBeanFactory.class); willAnswer(returnsFirstArg()).given(bf).resolveEmbeddedValue(anyString()); + when(bf.containsBean(eq(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME))) + .thenReturn(true); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + evaluationContext.addPropertyAccessor(new MapAccessor()); + when(bf.getBean(eq(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME), any(Class.class))) + .thenReturn(evaluationContext); helper.setBeanFactory(bf); try { helper.process(message); @@ -1020,13 +1033,13 @@ public void testUseSpelInvoker() throws Exception { // Check other CTORs helper = new MessagingMethodInvokerHelper(bean, "bar", false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) .isEqualTo(SpelCompilerMode.IMMEDIATE); helper = new MessagingMethodInvokerHelper(bean, ServiceActivator.class, false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); helper.process(message); assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) .isEqualTo(SpelCompilerMode.MIXED); @@ -1040,7 +1053,7 @@ public void testSingleMethodJson() throws Exception { SingleMethodJsonWithSpELBean.class.getDeclaredMethod("foo", SingleMethodJsonWithSpELBean.Foo.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); @@ -1053,7 +1066,7 @@ public void testSingleMethodBadJson() throws Exception { SingleMethodJsonWithSpELMessageWildBean bean = new SingleMethodJsonWithSpELMessageWildBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(bean, SingleMethodJsonWithSpELMessageWildBean.class.getDeclaredMethod("foo", Message.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("baz", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); @@ -1065,7 +1078,7 @@ public void testSingleMethodJsonMessageFoo() throws Exception { SingleMethodJsonWithSpELMessageFooBean bean = new SingleMethodJsonWithSpELMessageFooBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(bean, SingleMethodJsonWithSpELMessageFooBean.class.getDeclaredMethod("foo", Message.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); @@ -1078,7 +1091,7 @@ public void testSingleMethodJsonMessageWild() throws Exception { SingleMethodJsonWithSpELMessageWildBean bean = new SingleMethodJsonWithSpELMessageWildBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(bean, SingleMethodJsonWithSpELMessageWildBean.class.getDeclaredMethod("foo", Message.class), false); - helper.setBeanFactory(mock(BeanFactory.class)); + helper.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("{\"bar\":\"baz\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); @@ -1157,7 +1170,7 @@ void lifecycleOnly() { void lifecycleOnlyExplicitMethod() { LifecycleBean targetObject = new LifecycleBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(targetObject, "start"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("testing")); assertThat(targetObject.startCalled).isTrue(); } @@ -1166,7 +1179,7 @@ void lifecycleOnlyExplicitMethod() { void lifecycleWithValidStartMethod() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new LifeCycleWithCustomStart(), (String) null); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object result = processor.processMessage(new GenericMessage<>("testing")); assertThat(result).isEqualTo("TESTING"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/ReactiveMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/ReactiveMessageHandlerTests.java index b32e7efbafd..0555eadeec9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/ReactiveMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/ReactiveMessageHandlerTests.java @@ -24,6 +24,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.history.MessageHistory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; @@ -35,7 +36,7 @@ * * @since 5.3 */ -class ReactiveMessageHandlerTests { +class ReactiveMessageHandlerTests implements TestApplicationContextAware { private AtomicBoolean handled = new AtomicBoolean(); @@ -50,6 +51,7 @@ void setUp() { void messageHandledOnSubscribe() { assertThat(handled.get()).isFalse(); TestReactiveMessageHandler handler = new TestReactiveMessageHandler(); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>(""); handler.handleMessage(message).subscribe(); @@ -62,6 +64,7 @@ void messageTracked() { TestReactiveMessageHandler handler = new TestReactiveMessageHandler(); handler.setShouldTrack(true); handler.setComponentName("test-message-handler"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>(""); handler.handleMessage(message).subscribe(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java index 88aec3f0f19..9b2266c04e0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java @@ -40,7 +40,6 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.log.LogAccessor; import org.springframework.integration.channel.QueueChannel; @@ -49,6 +48,7 @@ import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException; import org.springframework.integration.message.AdviceMessage; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.ErrorHandlingTaskExecutor; import org.springframework.messaging.Message; @@ -86,7 +86,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class AdvisedMessageHandlerTests { +public class AdvisedMessageHandlerTests implements TestApplicationContextAware { @Autowired private MessageChannel input; @@ -131,7 +131,7 @@ protected Object handleRequestMessage(Message requestMessage) { PollableChannel successChannel = new QueueChannel(); PollableChannel failureChannel = new QueueChannel(); ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice(); - advice.setBeanFactory(mock(BeanFactory.class)); + advice.setBeanFactory(TEST_INTEGRATION_CONTEXT); advice.setSuccessChannel(successChannel); advice.setFailureChannel(failureChannel); advice.setOnSuccessExpressionString("'foo'"); @@ -151,7 +151,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message }); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); // advice with success @@ -227,7 +227,7 @@ protected Object handleRequestMessage(Message requestMessage) { PollableChannel successChannel = new QueueChannel(); PollableChannel failureChannel = new QueueChannel(); ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice(); - advice.setBeanFactory(mock(BeanFactory.class)); + advice.setBeanFactory(TEST_INTEGRATION_CONTEXT); advice.setSuccessChannel(successChannel); advice.setFailureChannel(failureChannel); advice.setOnSuccessExpressionString("1/0"); @@ -236,7 +236,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); // failing advice with success @@ -288,7 +288,7 @@ protected Object handleRequestMessage(Message requestMessage) { PollableChannel successChannel = new QueueChannel(); PollableChannel failureChannel = new QueueChannel(); ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice(); - advice.setBeanFactory(mock(BeanFactory.class)); + advice.setBeanFactory(TEST_INTEGRATION_CONTEXT); advice.setSuccessChannel(successChannel); advice.setFailureChannel(failureChannel); advice.setOnSuccessExpressionString("1/0"); @@ -297,7 +297,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); // failing advice with failure @@ -362,7 +362,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); doFail.set(true); @@ -436,7 +436,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -469,7 +469,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -539,7 +539,7 @@ private void defaultStatefulRetryRecoverAfterThirdTryGuts(final AtomicInteger co List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -573,7 +573,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -607,13 +607,13 @@ public boolean canRetry(RetryContext context) { } }); advice.setRetryTemplate(retryTemplate); - advice.setBeanFactory(mock(BeanFactory.class)); + advice.setBeanFactory(TEST_INTEGRATION_CONTEXT); advice.afterPropertiesSet(); List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -646,7 +646,7 @@ protected Object handleRequestMessage(Message requestMessage) { throw new RuntimeException("intentional"); }); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setAdviceChain(adviceChain); handler.afterPropertiesSet(); @@ -676,7 +676,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); ExpressionEvaluatingRequestHandlerAdvice expressionAdvice = new ExpressionEvaluatingRequestHandlerAdvice(); - expressionAdvice.setBeanFactory(mock(BeanFactory.class)); + expressionAdvice.setBeanFactory(TEST_INTEGRATION_CONTEXT); // MessagingException / RuntimeException expressionAdvice.setOnFailureExpressionString("#exception.cause.message"); expressionAdvice.setReturnFailureExpressionResult(true); @@ -696,7 +696,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message }); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("test")); @@ -723,7 +723,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); ExpressionEvaluatingRequestHandlerAdvice expressionAdvice = new ExpressionEvaluatingRequestHandlerAdvice(); - expressionAdvice.setBeanFactory(mock(BeanFactory.class)); + expressionAdvice.setBeanFactory(TEST_INTEGRATION_CONTEXT); expressionAdvice.setOnFailureExpressionString("#exception.message"); expressionAdvice.setFailureChannel(errors); @@ -734,7 +734,7 @@ protected Object handleRequestMessage(Message requestMessage) { }); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); assertThatException() @@ -803,7 +803,7 @@ public void throwableProperlyPropagatedAndReported() { QueueChannel errors = new QueueChannel(); ExpressionEvaluatingRequestHandlerAdvice expressionAdvice = new ExpressionEvaluatingRequestHandlerAdvice(); - expressionAdvice.setBeanFactory(mock(BeanFactory.class)); + expressionAdvice.setBeanFactory(TEST_INTEGRATION_CONTEXT); expressionAdvice.setOnFailureExpressionString("'foo'"); expressionAdvice.setFailureChannel(errors); @@ -840,7 +840,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message ExecutorService exec = Executors.newSingleThreadExecutor(); consumer.setTaskExecutor(new ErrorHandlingTaskExecutor(exec, t -> { })); - consumer.setBeanFactory(mock(BeanFactory.class)); + consumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); consumer.afterPropertiesSet(); consumer.setTaskScheduler(mock(TaskScheduler.class)); consumer.start(); @@ -893,7 +893,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message } }); filter.setAdviceChain(adviceChain); - filter.setBeanFactory(mock(BeanFactory.class)); + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); filter.afterPropertiesSet(); filter.handleMessage(new GenericMessage<>("foo")); assertThat(discardedWithinAdvice.get()).isNotNull(); @@ -920,7 +920,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message }); filter.setAdviceChain(adviceChain); filter.setDiscardWithinAdvice(false); - filter.setBeanFactory(mock(BeanFactory.class)); + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); filter.afterPropertiesSet(); filter.handleMessage(new GenericMessage<>("foo")); assertThat(adviceCalled.get()).isTrue(); @@ -971,7 +971,7 @@ protected Object handleRequestMessage(Message requestMessage) { List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); @@ -1013,14 +1013,14 @@ protected Object handleRequestMessage(Message requestMessage) { RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.registerListener(new MetricsRetryListener(meterRegistry)); advice.setRetryTemplate(retryTemplate); - advice.setBeanFactory(mock(BeanFactory.class)); + advice.setBeanFactory(TEST_INTEGRATION_CONTEXT); advice.afterPropertiesSet(); List adviceChain = new ArrayList<>(); adviceChain.add(advice); handler.setAdviceChain(adviceChain); handler.setBeanName("testEndpoint"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("Hello, world!"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java index de5ddd79fb9..a85a060e02f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java @@ -20,7 +20,6 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.BeanFactory; @@ -33,6 +32,7 @@ import org.springframework.integration.metadata.MetadataStore; import org.springframework.integration.metadata.SimpleMetadataStore; import org.springframework.integration.selector.MetadataStoreSelector; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -52,7 +52,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class IdempotentReceiverTests { +public class IdempotentReceiverTests implements TestApplicationContextAware { @Autowired private MessageChannel input; @@ -80,7 +80,7 @@ public void testIdempotentReceiverInterceptor() { ConcurrentMetadataStore store = new SimpleMetadataStore(); ExpressionEvaluatingMessageProcessor idempotentKeyStrategy = new ExpressionEvaluatingMessageProcessor<>(new SpelExpressionParser().parseExpression("payload")); - BeanFactory beanFactory = Mockito.mock(BeanFactory.class); + BeanFactory beanFactory = TEST_INTEGRATION_CONTEXT; idempotentKeyStrategy.setBeanFactory(beanFactory); IdempotentReceiverInterceptor idempotentReceiverInterceptor = new IdempotentReceiverInterceptor(new MetadataStoreSelector(idempotentKeyStrategy, store)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/LockRequestHandlerAdviceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/LockRequestHandlerAdviceTests.java index a8c2ef43815..b47fe58d3b3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/LockRequestHandlerAdviceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/LockRequestHandlerAdviceTests.java @@ -35,6 +35,7 @@ import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.locks.DefaultLockRegistry; import org.springframework.integration.support.locks.LockRegistry; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.core.MessagePostProcessor; @@ -51,7 +52,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class LockRequestHandlerAdviceTests { +public class LockRequestHandlerAdviceTests implements TestApplicationContextAware { private static final String LOCK_KEY_HEADER = "lock-key-header"; @@ -76,7 +77,7 @@ void verifyLockAroundHandler() throws ExecutionException, InterruptedException, messagingTemplate.asyncConvertSendAndReceive(this.inputChannel, "test1", messagePostProcessor); Future test2 = messagingTemplate.asyncConvertSendAndReceive(this.inputChannel, "test2", messagePostProcessor); - + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(test1.get(10, TimeUnit.SECONDS)).isEqualTo("test1-1"); assertThat(test2.get(10, TimeUnit.SECONDS)).isEqualTo("test2-1"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests-context.xml b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests-context.xml index 7a7834543ea..8b9041d032e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests-context.xml +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests-context.xml @@ -7,4 +7,6 @@ + + diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java index 2233aba0cf5..ad72c9fb727 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java @@ -21,24 +21,23 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.handler.ExpressionEvaluatingMessageHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Artem Bilan * @author Gary Russell * @since 2.1 */ -public class ExpressionEvaluatingMessageHandlerTests { +public class ExpressionEvaluatingMessageHandlerTests implements TestApplicationContextAware { private ExpressionParser parser; @@ -51,7 +50,7 @@ public void setup() { public void validExpression() { Expression expression = parser.parseExpression("T(System).out.println(payload)"); ExpressionEvaluatingMessageHandler handler = new ExpressionEvaluatingMessageHandler(expression); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage("test")); } @@ -60,7 +59,7 @@ public void validExpression() { public void validExpressionWithNoArgs() { Expression expression = parser.parseExpression("T(System).out.println()"); ExpressionEvaluatingMessageHandler handler = new ExpressionEvaluatingMessageHandler(expression); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage("test")); } @@ -69,7 +68,7 @@ public void validExpressionWithNoArgs() { public void validExpressionWithSomeArgs() { Expression expression = parser.parseExpression("T(System).out.write(payload.bytes, 0, headers.offset)"); ExpressionEvaluatingMessageHandler handler = new ExpressionEvaluatingMessageHandler(expression); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); HashMap headers = new HashMap(); headers.put("offset", 4); @@ -81,7 +80,7 @@ public void expressionWithReturnValue() { Message message = new GenericMessage(.1f); Expression expression = parser.parseExpression("T(System).out.printf('$%4.2f', payload)"); ExpressionEvaluatingMessageHandler handler = new ExpressionEvaluatingMessageHandler(expression); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> handler.handleMessage(message)) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests-context.xml b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests-context.xml index c8bfd1d53dd..5abdaaf3953 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests-context.xml +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests-context.xml @@ -23,4 +23,6 @@ + + diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java index 3600548e723..1f358f5f914 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.endpoint.PollingConsumer; import org.springframework.integration.handler.MethodInvokingMessageHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; @@ -38,19 +38,18 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Oleg Zhurakousky * @author Artem Bilan */ -public class MethodInvokingMessageHandlerTests { +public class MethodInvokingMessageHandlerTests implements TestApplicationContextAware { @Test public void validMethod() { MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(new TestSink(), "validMethod"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatNoException() .isThrownBy(() -> handler.handleMessage(new GenericMessage<>("test"))); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java index 6bac9591297..91e74b6d529 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java @@ -21,28 +21,27 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.endpoint.MethodInvokingMessageSource; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Gary Russell */ -public class MethodInvokingMessageSourceTests { +public class MethodInvokingMessageSourceTests implements TestApplicationContextAware { @Test public void testValidMethod() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("validMethod"); Message result = source.receive(); @@ -57,7 +56,7 @@ public void testHeaderExpressions() { headerExpressions.put("foo", new LiteralExpression("abc")); headerExpressions.put("bar", new SpelExpressionParser().parseExpression("new Integer(123)")); MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("validMethod"); source.setHeaderExpressions(headerExpressions); @@ -72,7 +71,7 @@ public void testHeaderExpressions() { @Test public void testNoMatchingMethodName() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("noMatchingMethod"); assertThatThrownBy(() -> source.receive()) @@ -82,7 +81,7 @@ public void testNoMatchingMethodName() { @Test public void testInvalidMethodWithArg() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("invalidMethodWithArg"); assertThatThrownBy(() -> source.receive()) @@ -92,7 +91,7 @@ public void testInvalidMethodWithArg() { @Test public void testInvalidMethodWithNoReturnValue() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("invalidMethodWithNoReturnValue"); assertThatThrownBy(() -> source.receive()) @@ -102,7 +101,7 @@ public void testInvalidMethodWithNoReturnValue() { @Test public void testNullReturningMethodReturnsNullMessage() { MethodInvokingMessageSource source = new MethodInvokingMessageSource(); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setObject(new TestBean()); source.setMethodName("nullReturningMethod"); Message message = source.receive(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java index 8ac63133d1c..a2104b171ed 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java @@ -21,15 +21,12 @@ import java.util.Map; import java.util.Properties; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.support.MessageBuilder; -import org.springframework.integration.test.util.TestUtils; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.handler.annotation.Header; @@ -47,22 +44,10 @@ * @since 1.0.3 */ @SuppressWarnings({"rawtypes", "unchecked"}) -public class PayloadAndHeaderMappingTests { - - private static final ConfigurableApplicationContext applicationContext = TestUtils.createTestApplicationContext(); +public class PayloadAndHeaderMappingTests implements TestApplicationContextAware { private TestBean bean; - @BeforeAll - public static void start() { - applicationContext.refresh(); - } - - @AfterAll - public static void stop() { - applicationContext.close(); - } - @BeforeEach public void setup() { bean = new TestBean(); @@ -707,7 +692,7 @@ public void twoPayloadExpressions() throws Exception { private ServiceActivatingHandler getHandler(String methodName, Class... types) throws Exception { ServiceActivatingHandler serviceActivatingHandler = new ServiceActivatingHandler(bean, TestBean.class.getMethod(methodName, types)); - serviceActivatingHandler.setBeanFactory(applicationContext); + serviceActivatingHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); serviceActivatingHandler.afterPropertiesSet(); return serviceActivatingHandler; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java index b7f15baf101..b984be23693 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java @@ -24,6 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.integration.MessageRejectedException; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; @@ -40,7 +41,7 @@ * @author Oleg Zhurakousky * @author Artem Bilan */ -public class ErrorMessageExceptionTypeRouterTests { +public class ErrorMessageExceptionTypeRouterTests implements TestApplicationContextAware { private final TestUtils.TestApplicationContext context = TestUtils.createTestApplicationContext(); @@ -147,6 +148,7 @@ public void fallbackToDefaultChannel() { ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); router.setApplicationContext(this.context); + router.setBeanFactory(TestUtils.createTestApplicationContext()); router.setDefaultOutputChannel(defaultChannel); router.afterPropertiesSet(); @@ -167,6 +169,7 @@ public void noMatchAndNoDefaultChannel() { ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); router.setApplicationContext(this.context); + router.setBeanFactory(TestUtils.createTestApplicationContext()); router.setChannelMapping(MessageDeliveryException.class.getName(), "messageDeliveryExceptionChannel"); router.setResolutionRequired(true); router.setBeanName("fooRouter"); @@ -252,6 +255,7 @@ public void testHierarchicalMapping() { public void testInvalidMapping() { ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); router.setApplicationContext(this.context); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); try { router.setChannelMapping("foo", "fooChannel"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java index 72036afa914..18a53fbc8b7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java @@ -22,10 +22,10 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.channel.TestChannelResolver; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageDeliveryException; @@ -37,13 +37,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Artem Bilan */ -public class MethodInvokingRouterTests { +public class MethodInvokingRouterTests implements TestApplicationContextAware { @Test public void channelNameResolutionByPayloadConfiguredByMethodReference() throws Exception { @@ -53,7 +52,7 @@ public void channelNameResolutionByPayloadConfiguredByMethodReference() throws E SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routePayload", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); router.setChannelResolver(channelResolver); Message message = new GenericMessage<>("bar"); @@ -71,7 +70,7 @@ public void channelNameResolutionByPayloadConfiguredByMethodName() { SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routePayload"); router.setChannelResolver(channelResolver); - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); Message message = new GenericMessage<>("bar"); router.handleMessage(message); @@ -91,7 +90,7 @@ public void channelNameResolutionByHeader() throws Exception { Method routingMethod = testBean.getClass().getMethod("routeByHeader", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); router.setChannelResolver(channelResolver); - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); Message message = MessageBuilder.withPayload("bar") .setHeader("targetChannel", "foo").build(); @@ -128,7 +127,7 @@ public void channelNameResolutionByMessageConfiguredByMethodName() { } private void doTestChannelNameResolutionByMessage(MethodInvokingRouter router) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -177,7 +176,7 @@ public void channelInstanceResolutionByPayloadConfiguredByMethodName() { private void doTestChannelInstanceResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); Message fooMessage = new GenericMessage<>("foo"); Message barMessage = new GenericMessage<>("bar"); @@ -226,7 +225,7 @@ public void channelInstanceResolutionByMessageConfiguredByMethodName() { private void doTestChannelInstanceResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -275,7 +274,7 @@ public void multiChannelNameResolutionByPayloadConfiguredByMethodName() { private void doTestMultiChannelNameResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -329,7 +328,7 @@ public void multiChannelNameResolutionByMessageConfiguredByMethodName() { private void doTestMultiChannelNameResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -383,7 +382,7 @@ public void multiChannelNameArrayResolutionByMessageConfiguredByMethodName() { private void doTestMultiChannelNameArrayResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -437,7 +436,7 @@ public void multiChannelListResolutionByPayloadConfiguredByMethodName() { private void doTestMultiChannelListResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -492,7 +491,7 @@ public void multiChannelListResolutionByMessageConfiguredByMethodName() { private void doTestMultiChannelListResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -547,7 +546,7 @@ public void multiChannelArrayResolutionByMessageConfiguredByMethodName() { private void doTestMultiChannelArrayResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); @@ -594,7 +593,7 @@ public void testClassAsKeyResolution() { router.setChannelResolver(channelResolver); router.setChannelMapping(String.class.getName(), "stringsChannel"); router.setChannelMapping(Integer.class.getName(), "numbersChannel"); - router.setBeanFactory(mock(BeanFactory.class)); + router.setBeanFactory(TEST_INTEGRATION_CONTEXT); router.afterPropertiesSet(); Message message = new GenericMessage<>("bar"); router.handleMessage(message); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java index 445b89f9b74..ad1f4bdbf06 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java @@ -37,7 +37,7 @@ public class RouterFactoryBeanTests { private boolean routeAttempted; @Test - public void testOutputChannelName() throws Exception { + public void testOutputChannelName() { TestUtils.TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); testApplicationContext.refresh(); RouterFactoryBean fb = new RouterFactoryBean(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java index 84680d4b4bf..7fe6f5f0bc9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java @@ -28,26 +28,25 @@ import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.annotation.Splitter; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.support.AbstractIntegrationMessageBuilder; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Artem Bilan * @author Gary Russell */ -public class MethodInvokingSplitterTests { +public class MethodInvokingSplitterTests implements TestApplicationContextAware { private final SplitterTestBean testBean = new SplitterTestBean(); @@ -155,7 +154,7 @@ public void splitMessageToMessageBuilderList() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToMessageBuilderList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -242,7 +241,7 @@ public void splitMessageToStringArrayConfiguredByMethodName() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToStringArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -324,7 +323,7 @@ public void splitStringToMessageListConfiguredByMethodName() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "stringToMessageList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -351,7 +350,7 @@ public List split(List list) { MethodInvokingSplitter splitter = new MethodInvokingSplitter(new ListSplitter(), "split"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -390,7 +389,7 @@ public Stream split(Stream stream) { MethodInvokingSplitter splitter = new MethodInvokingSplitter(new StreamSplitter(), "split"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -471,7 +470,7 @@ public void splitPayloadAndHeader() throws Exception { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, splittingMethod); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -496,7 +495,7 @@ public void singleAnnotation() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(annotatedBean); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -521,7 +520,7 @@ public void singlePublicMethod() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); @@ -543,7 +542,7 @@ private MethodInvokingSplitter getSplitter(String methodName) throws Exception { Class paramType = methodName.startsWith("message") ? Message.class : String.class; Method splittingMethod = this.testBean.getClass().getMethod(methodName, paramType); MethodInvokingSplitter methodInvokingSplitter = new MethodInvokingSplitter(this.testBean, splittingMethod); - methodInvokingSplitter.setBeanFactory(mock(BeanFactory.class)); + methodInvokingSplitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); methodInvokingSplitter.afterPropertiesSet(); return methodInvokingSplitter; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java index 557a8054161..2c6bede3cd3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java @@ -25,19 +25,18 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.annotation.Splitter; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Alex Peters @@ -46,7 +45,7 @@ * * @since 4.1 */ -public class StreamingSplitterTests { +public class StreamingSplitterTests implements TestApplicationContextAware { private Message message; @@ -59,7 +58,7 @@ public void setUp() { public void splitToIterator_sequenceSizeInLastMessageHeader() { int messageQuantity = 5; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); @@ -82,7 +81,7 @@ public void splitToIterator_sourceMessageHeadersIncluded() { .build(); int messageQuantity = 5; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); @@ -103,7 +102,7 @@ public void splitToIterator_sourceMessageHeadersIncluded() { public void splitToIterator_allMessagesSent() { int messageQuantity = 5; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); @@ -115,7 +114,7 @@ public void splitToIterator_allMessagesSent() { public void splitToIterable_allMessagesSent() { int messageQuantity = 5; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IterableTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); @@ -127,7 +126,7 @@ public void splitToIterable_allMessagesSent() { public void splitToIterator_allMessagesContainSequenceNumber() { final int messageQuantity = 5; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); DirectChannel replyChannel = new DirectChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); @@ -142,7 +141,7 @@ public void splitToIterator_allMessagesContainSequenceNumber() { public void splitWithMassiveReplyMessages_allMessagesSent() { final int messageQuantity = 100000; MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); DirectChannel replyChannel = new DirectChannel(); splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java index 1edc95721e5..c8453ce5f60 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java @@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; @@ -38,6 +37,7 @@ import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.handler.ReplyRequiredException; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.support.StaticHeaderValueMessageProcessor; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; @@ -51,7 +51,6 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -62,7 +61,7 @@ * * @since 2.1 */ -public class ContentEnricherTests { +public class ContentEnricherTests implements TestApplicationContextAware { /** * In this test a {@link Target} message is passed into a {@link ContentEnricher}. @@ -102,7 +101,7 @@ public void replyChannelReplyTimingOut() throws Exception { enricher.setPropertyExpressions(expressions); enricher.setRequiresReply(true); enricher.setBeanName("Enricher"); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); final AbstractReplyProducingMessageHandler handler = @@ -121,7 +120,7 @@ protected Object handleRequestMessage(Message requestMessage) { }; - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); final PollingConsumer consumer = new PollingConsumer(requestChannel, handler); @@ -135,7 +134,7 @@ protected Object handleRequestMessage(Message requestMessage) { taskScheduler.afterPropertiesSet(); consumer.setTaskScheduler(taskScheduler); - consumer.setBeanFactory(mock(BeanFactory.class)); + consumer.setBeanFactory(TEST_INTEGRATION_CONTEXT); consumer.afterPropertiesSet(); consumer.start(); @@ -162,7 +161,7 @@ public void requestChannelSendTimingOut() { ContentEnricher enricher = new ContentEnricher(); enricher.setRequestChannel(requestChannel); enricher.setRequestTimeout(requestTimeout); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); Target target = new Target("replace me"); @@ -194,7 +193,7 @@ protected Object handleRequestMessage(Message requestMessage) { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("name", parser.parseExpression("payload.lastName + ', ' + payload.firstName")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); Target target = new Target("replace me"); @@ -210,7 +209,7 @@ public void setReplyChannelWithoutRequestChannel() { ContentEnricher enricher = new ContentEnricher(); enricher.setReplyChannel(replyChannel); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalStateException() .isThrownBy(enricher::afterPropertiesSet) @@ -220,7 +219,7 @@ public void setReplyChannelWithoutRequestChannel() { @Test public void setNullReplyTimeout() { ContentEnricher enricher = new ContentEnricher(); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(() -> enricher.setReplyTimeout(null)) @@ -230,7 +229,7 @@ public void setNullReplyTimeout() { @Test public void setNullRequestTimeout() { ContentEnricher enricher = new ContentEnricher(); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(() -> enricher.setRequestTimeout(null)) @@ -245,7 +244,7 @@ public void testSimplePropertyWithoutUsingRequestChannel() { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("name", parser.parseExpression("'just a static string'")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); Target target = new Target("replace me"); Message requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build(); @@ -258,7 +257,7 @@ public void testSimplePropertyWithoutUsingRequestChannel() { public void testContentEnricherWithNullRequestChannel() { ContentEnricher enricher = new ContentEnricher(); enricher.setReplyChannel(new QueueChannel()); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalStateException() .isThrownBy(enricher::afterPropertiesSet) @@ -283,7 +282,7 @@ protected Object handleRequestMessage(Message requestMessage) { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("child.name", parser.parseExpression("payload.lastName + ', ' + payload.firstName")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); Target target = new Target("test"); @@ -314,7 +313,7 @@ protected Object handleRequestMessage(Message requestMessage) { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("name", parser.parseExpression("payload.lastName + ', ' + payload.firstName")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); Target target = new Target("replace me"); @@ -345,7 +344,7 @@ protected Object handleRequestMessage(Message requestMessage) { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("name", parser.parseExpression("payload.lastName + ', ' + payload.firstName")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); TargetUser target = new TargetUser(); @@ -379,7 +378,7 @@ protected Object handleRequestMessage(Message requestMessage) { Map propertyExpressions = new HashMap<>(); propertyExpressions.put("name", parser.parseExpression("payload.lastName + ', ' + payload.firstName")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); UncloneableTargetUser target = new UncloneableTargetUser(); @@ -395,7 +394,7 @@ protected Object handleRequestMessage(Message requestMessage) { @Test public void testLifeCycleMethodsWithoutRequestChannel() { ContentEnricher enricher = new ContentEnricher(); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); @@ -417,7 +416,7 @@ protected Object handleRequestMessage(Message requestMessage) { ContentEnricher enricher = new ContentEnricher(); enricher.setRequestChannel(requestChannel); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); @@ -470,7 +469,7 @@ protected Object handleRequestMessage(Message requestMessage) { propertyExpressions.put("name", parser.parseExpression("payload.name + ' target'")); enricher.setPropertyExpressions(propertyExpressions); - enricher.setBeanFactory(mock(BeanFactory.class)); + enricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); enricher.afterPropertiesSet(); final Target target = new Target("replace me"); @@ -488,7 +487,7 @@ public void testOverwriteTimestamp() { contentEnricher.setHeaderExpressions( Collections.singletonMap(MessageHeaders.TIMESTAMP, new StaticHeaderValueMessageProcessor<>("foo"))); - contentEnricher.setBeanFactory(mock(BeanFactory.class)); + contentEnricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(BeanInitializationException.class) .isThrownBy(contentEnricher::afterPropertiesSet) @@ -501,7 +500,7 @@ public void testOverwriteIdNullResult() { contentEnricher.setNullResultHeaderExpressions( Collections.singletonMap(MessageHeaders.ID, new StaticHeaderValueMessageProcessor<>("foo"))); - contentEnricher.setBeanFactory(mock(BeanFactory.class)); + contentEnricher.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatExceptionOfType(BeanInitializationException.class) .isThrownBy(contentEnricher::afterPropertiesSet) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java index 124bb262257..7e58daa9feb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java @@ -26,6 +26,7 @@ import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; @@ -40,7 +41,7 @@ * * @since 2.0 */ -public class HeaderFilterTests { +public class HeaderFilterTests implements TestApplicationContextAware { @Test public void testFilterDirectly() { @@ -83,6 +84,7 @@ public void testFilterWithinHandler() { @Test public void testIdHeaderRemoval() { HeaderFilter filter = new HeaderFilter("foo", MessageHeaders.ID); + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { filter.afterPropertiesSet(); fail("BeanInitializationException expected"); @@ -96,6 +98,7 @@ public void testIdHeaderRemoval() { @Test public void testTimestampHeaderRemoval() { HeaderFilter filter = new HeaderFilter(MessageHeaders.TIMESTAMP); + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { filter.afterPropertiesSet(); fail("BeanInitializationException expected"); @@ -109,6 +112,7 @@ public void testTimestampHeaderRemoval() { @Test public void testIdPatternRemoval() { HeaderFilter filter = new HeaderFilter("*", MessageHeaders.ID); + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); filter.setPatternMatch(true); try { filter.afterPropertiesSet(); @@ -124,7 +128,7 @@ public void testIdPatternRemoval() { public void testPatternRemoval() { HeaderFilter filter = new HeaderFilter("time*"); filter.setPatternMatch(true); - + filter.setBeanFactory(TEST_INTEGRATION_CONTEXT); filter.afterPropertiesSet(); Message message = MessageBuilder.withPayload("test") .setHeader("time", new Date()) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java index d278621ec3c..04c82f8ef2f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java @@ -21,10 +21,10 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.annotation.Transformer; import org.springframework.integration.handler.MethodInvokingMessageProcessor; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.handler.annotation.Header; @@ -32,20 +32,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Artem Bilan */ -class MethodInvokingTransformerTests { +class MethodInvokingTransformerTests implements TestApplicationContextAware { @Test void simplePayloadConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("exclaim", String.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>("foo"); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("FOO!"); @@ -55,7 +54,7 @@ void simplePayloadConfiguredWithMethodReference() throws Exception { void simplePayloadConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "exclaim"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage("foo"); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("FOO!"); @@ -66,7 +65,7 @@ void typeConversionConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("exclaim", String.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>(123); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("123!"); @@ -76,7 +75,7 @@ void typeConversionConfiguredWithMethodReference() throws Exception { void typeConversionConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "exclaim"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = new GenericMessage<>(123); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("123!"); @@ -87,7 +86,7 @@ void headerAnnotationConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("headerTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); @@ -98,7 +97,7 @@ void headerAnnotationConfiguredWithMethodReference() throws Exception { void headerAnnotationConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "headerTest"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); @@ -121,7 +120,7 @@ void optionalHeaderAnnotation() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo").setHeader("number", 99).build(); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("foo99"); @@ -132,7 +131,7 @@ void optionalHeaderValueNotProvided() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("foo").build(); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("foonull"); @@ -143,7 +142,7 @@ void messageReturnValueConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("messageReturnValueTest", Message.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("test"); @@ -153,7 +152,7 @@ void messageReturnValueConfiguredWithMethodReference() throws Exception { void messageReturnValueConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "messageReturnValueTest"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); assertThat(result.getPayload()).isEqualTo("test"); @@ -165,7 +164,7 @@ void propertiesPayloadConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("propertyPayloadTest", Properties.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Properties props = new Properties(); props.setProperty("prop1", "bad"); props.setProperty("prop3", "baz"); @@ -186,7 +185,7 @@ void propertiesPayloadConfiguredWithMethodReference() throws Exception { void propertiesPayloadConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "propertyPayloadTest"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); Properties props = new Properties(); props.setProperty("prop1", "bad"); props.setProperty("prop3", "baz"); @@ -206,7 +205,7 @@ void propertiesPayloadConfiguredWithMethodName() { void nullReturningMethod() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "nullReturnValueTest"); - transformer.setBeanFactory(mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); GenericMessage message = new GenericMessage<>("test"); Message result = transformer.transform(message); assertThat(result).isNull(); @@ -221,7 +220,7 @@ void headerEnricherConfiguredWithMethodReference() throws Exception { HeaderEnricher transformer = new HeaderEnricher(); transformer.setDefaultOverwrite(true); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, testMethod); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.setMessageProcessor(processor); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "bad") @@ -241,7 +240,7 @@ void headerEnricherConfiguredWithMethodName() { HeaderEnricher transformer = new HeaderEnricher(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "propertyEnricherTest"); - processor.setBeanFactory(mock(BeanFactory.class)); + processor.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.setMessageProcessor(processor); transformer.setDefaultOverwrite(true); Message message = MessageBuilder.withPayload("test") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java index 6558aefad20..dcadaff2b1a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java @@ -42,7 +42,9 @@ import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.handler.MethodInvokingMessageProcessor; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.history.MessageHistory; @@ -199,6 +201,7 @@ public Bar convert(Foo source) { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); processor.setConversionService(conversionService); processor.setUseSpelInvoker(true); + beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); processor.setBeanFactory(beanFactory); ServiceActivatingHandler handler = new ServiceActivatingHandler(processor); QueueChannel replyChannel = new QueueChannel(); @@ -222,6 +225,7 @@ public Bar convert(Foo source) { }); BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(conversionService); beanFactory.setConversionService(conversionService); + beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); typeConverter.setBeanFactory(beanFactory); Service service = new Service(); diff --git a/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt b/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt index f75f0101be1..c29c56a439d 100644 --- a/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt +++ b/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt @@ -36,6 +36,8 @@ import org.springframework.integration.handler.LoggingHandler import org.springframework.integration.scheduling.PollerMetadata import org.springframework.integration.selector.UnexpiredMessageSelector import org.springframework.integration.support.MessageBuilder +import org.springframework.integration.test.context.TestApplicationContextAware +import org.springframework.integration.test.context.TestApplicationContextAware.TEST_INTEGRATION_CONTEXT import org.springframework.integration.test.util.OnlyOnceTrigger import org.springframework.messaging.Message import org.springframework.messaging.MessageChannel @@ -57,7 +59,7 @@ import java.util.function.Function */ @SpringJUnitConfig @DirtiesContext -class KotlinDslTests { +class KotlinDslTests : TestApplicationContextAware { @Autowired private lateinit var beanFactory: BeanFactory @@ -121,7 +123,9 @@ class KotlinDslTests { @Test fun `fixed subscriber channel`() { - assertThat(MessagingTemplate().convertSendAndReceive(this.fixedSubscriberInput, "test", String::class.java)) + var messagingTemplate = MessagingTemplate() + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT) + assertThat(messagingTemplate.convertSendAndReceive(this.fixedSubscriberInput, "test", String::class.java)) .isEqualTo("test") } diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java index 41856df4527..959cd92d0d1 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java @@ -39,8 +39,10 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.ResolvableType; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.event.core.MessagingEvent; import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.test.util.TestUtils; @@ -144,9 +146,7 @@ public void payloadExpressionEvaluatedAgainstApplicationEvent() { GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); - beanFactory.registerSingleton(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, - new SimpleApplicationEventMulticaster(beanFactory)); - + populateBeanFactory(beanFactory); adapter.setBeanFactory(beanFactory); beanFactory.registerSingleton("testListenerMessageProducer", adapter); adapter.afterPropertiesSet(); @@ -294,6 +294,12 @@ public void testInt2935CheckRetrieverCache() { ctx.close(); } + private static void populateBeanFactory(ConfigurableListableBeanFactory beanFactory) { + beanFactory.registerSingleton(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, + new SimpleApplicationEventMulticaster(beanFactory)); + beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, new StandardEvaluationContext()); + } + @Test public void testPayloadEvents() { GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/applicationEventInboundChannelAdapterTests.xml b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/applicationEventInboundChannelAdapterTests.xml index 125496a300a..40ea2f9d9b2 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/applicationEventInboundChannelAdapterTests.xml +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/applicationEventInboundChannelAdapterTests.xml @@ -6,6 +6,9 @@ + + diff --git a/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java b/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java index a0b61e7024a..6b8966a2f3a 100644 --- a/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java +++ b/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java @@ -26,15 +26,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.UrlResource; import org.springframework.integration.metadata.PropertiesPersistingMetadataStore; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.Mockito.mock; /** * @author Oleg Zhurakousky @@ -45,7 +44,7 @@ * * @since 2.0 */ -public class FeedEntryMessageSourceTests { +public class FeedEntryMessageSourceTests implements TestApplicationContextAware { static File metadataStoreFile; @@ -88,7 +87,7 @@ protected void customizeConnection(HttpURLConnection connection) throws IOExcept }; FeedEntryMessageSource feedEntrySource = new FeedEntryMessageSource(urlResource, "foo"); feedEntrySource.setBeanName("feedReader"); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); assertThat(feedEntrySource.receive()).isNull(); } @@ -98,7 +97,7 @@ public void testReceiveFeedWithEntriesSorted() { ClassPathResource resource = new ClassPathResource("org/springframework/integration/feed/sample.rss"); FeedEntryMessageSource source = new FeedEntryMessageSource(resource, "foo"); source.setBeanName("feedReader"); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); Message message1 = source.receive(); Message message2 = source.receive(); @@ -121,7 +120,7 @@ public void testEntryHavingBeenUpdatedAfterPublishAndRepeat() { PropertiesPersistingMetadataStore metadataStore = new PropertiesPersistingMetadataStore(); metadataStore.afterPropertiesSet(); feedEntrySource.setMetadataStore(metadataStore); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); SyndEntry entry1 = feedEntrySource.receive().getPayload(); @@ -140,7 +139,7 @@ public void testEntryHavingBeenUpdatedAfterPublishAndRepeat() { metadataStore = new PropertiesPersistingMetadataStore(); metadataStore.afterPropertiesSet(); feedEntrySource.setMetadataStore(metadataStore); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); assertThat(feedEntrySource.receive()).isNull(); } @@ -155,7 +154,7 @@ public void testReceiveFeedWithRealEntriesAndRepeatWithPersistentMetadataStore() PropertiesPersistingMetadataStore metadataStore = new PropertiesPersistingMetadataStore(); metadataStore.afterPropertiesSet(); feedEntrySource.setMetadataStore(metadataStore); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); SyndEntry entry1 = feedEntrySource.receive().getPayload(); SyndEntry entry2 = feedEntrySource.receive().getPayload(); @@ -180,7 +179,7 @@ public void testReceiveFeedWithRealEntriesAndRepeatWithPersistentMetadataStore() metadataStore = new PropertiesPersistingMetadataStore(); metadataStore.afterPropertiesSet(); feedEntrySource.setMetadataStore(metadataStore); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); assertThat(feedEntrySource.receive()).isNull(); assertThat(feedEntrySource.receive()).isNull(); @@ -194,7 +193,7 @@ public void testReceiveFeedWithRealEntriesAndRepeatNoPersistentMetadataStore() { ClassPathResource resource = new ClassPathResource("org/springframework/integration/feed/sample.rss"); FeedEntryMessageSource feedEntrySource = new FeedEntryMessageSource(resource, "foo"); feedEntrySource.setBeanName("feedReader"); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); SyndEntry entry1 = feedEntrySource.receive().getPayload(); SyndEntry entry2 = feedEntrySource.receive().getPayload(); @@ -214,7 +213,7 @@ public void testReceiveFeedWithRealEntriesAndRepeatNoPersistentMetadataStore() { // now test that what's been read is read AGAIN feedEntrySource = new FeedEntryMessageSource(resource, "foo"); feedEntrySource.setBeanName("feedReader"); - feedEntrySource.setBeanFactory(mock(BeanFactory.class)); + feedEntrySource.setBeanFactory(TEST_INTEGRATION_CONTEXT); feedEntrySource.afterPropertiesSet(); entry1 = feedEntrySource.receive().getPayload(); entry2 = feedEntrySource.receive().getPayload(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java index b61d7734569..3446979c523 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java @@ -22,11 +22,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -35,7 +34,7 @@ * * @since 1.0.3 */ -public class AutoCreateDirectoryTests { +public class AutoCreateDirectoryTests implements TestApplicationContextAware { private static final String BASE_PATH = System.getProperty("java.io.tmpdir") + File.separator + "AutoCreateDirectoryTests"; @@ -65,7 +64,7 @@ public void clearDirectories() { public void autoCreateForInboundEnabledByDefault() { FileReadingMessageSource source = new FileReadingMessageSource(); source.setDirectory(new File(INBOUND_PATH)); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); source.start(); assertThat(new File(INBOUND_PATH).exists()).isTrue(); @@ -77,7 +76,7 @@ public void autoCreateForInboundDisabled() { FileReadingMessageSource source = new FileReadingMessageSource(); source.setDirectory(new File(INBOUND_PATH)); source.setAutoCreateDirectory(false); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); assertThatIllegalArgumentException() .isThrownBy(source::start); @@ -87,7 +86,7 @@ public void autoCreateForInboundDisabled() { public void autoCreateForOutboundEnabledByDefault() { FileWritingMessageHandler handler = new FileWritingMessageHandler( new File(OUTBOUND_PATH)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); assertThat(new File(OUTBOUND_PATH).exists()).isTrue(); } @@ -96,7 +95,7 @@ public void autoCreateForOutboundEnabledByDefault() { public void autoCreateForOutboundDisabled() { FileWritingMessageHandler handler = new FileWritingMessageHandler( new File(OUTBOUND_PATH)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setAutoCreateDirectory(false); assertThatIllegalArgumentException() .isThrownBy(handler::afterPropertiesSet); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java index 71b7fd52433..2de6dee7b99 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java @@ -20,24 +20,23 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher * @author Gary Russell * @author Artem Bilan */ -public class DefaultFileNameGeneratorTests { +public class DefaultFileNameGeneratorTests implements TestApplicationContextAware { @Test public void defaultHeaderNamePresent() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, "foo").build(); String filename = generator.generateFileName(message); assertThat(filename).isEqualTo("foo"); @@ -46,7 +45,7 @@ public void defaultHeaderNamePresent() { @Test public void defaultHeaderNameNotPresent() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test").build(); String filename = generator.generateFileName(message); assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); @@ -55,7 +54,7 @@ public void defaultHeaderNameNotPresent() { @Test public void defaultHeaderNameNotString() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, 123) .build(); String filename = generator.generateFileName(message); @@ -65,7 +64,7 @@ public void defaultHeaderNameNotString() { @Test public void customHeaderNamePresent() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").setHeader("foo", "bar").build(); String filename = generator.generateFileName(message); @@ -75,7 +74,7 @@ public void customHeaderNamePresent() { @Test public void customHeaderNameNotPresent() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").build(); String filename = generator.generateFileName(message); @@ -85,7 +84,7 @@ public void customHeaderNameNotPresent() { @Test public void customHeaderNameNotString() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").setHeader("foo", 123).build(); String filename = generator.generateFileName(message); @@ -95,7 +94,7 @@ public void customHeaderNameNotString() { @Test public void filePayloadPresent() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); File payload = new File("/some/path/foo"); Message message = MessageBuilder.withPayload(payload).build(); String filename = generator.generateFileName(message); @@ -105,7 +104,7 @@ public void filePayloadPresent() { @Test public void defaultHeaderNameTakesPrecedenceOverFilePayload() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).setHeader(FileHeaders.FILENAME, "foo").build(); String filename = generator.generateFileName(message); @@ -115,7 +114,7 @@ public void defaultHeaderNameTakesPrecedenceOverFilePayload() { @Test public void customHeaderNameTakesPrecedenceOverFilePayload() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).setHeader("foo", "bar").build(); @@ -126,7 +125,7 @@ public void customHeaderNameTakesPrecedenceOverFilePayload() { @Test public void customExpressionTakesPrecedenceOverFilePayload() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setExpression("'foobar'"); File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).build(); @@ -137,7 +136,7 @@ public void customExpressionTakesPrecedenceOverFilePayload() { @Test public void customHeaderNameTakesPrecedenceOverDefault() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, "ignore") .setHeader("foo", "bar").build(); @@ -148,7 +147,7 @@ public void customHeaderNameTakesPrecedenceOverDefault() { @Test public void customHeaderNameTakesPrecedenceOverFilePayloadAndDefault() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); - generator.setBeanFactory(mock(BeanFactory.class)); + generator.setBeanFactory(TEST_INTEGRATION_CONTEXT); generator.setHeaderName("foo"); File payload = new File("/some/path/ignore1"); Message message = MessageBuilder.withPayload(payload).setHeader(FileHeaders.FILENAME, "ignore2") diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests-context.xml b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests-context.xml index 4c7645eeb99..787331e9a49 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests-context.xml +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests-context.xml @@ -10,6 +10,8 @@ p:directory="#{T(org.springframework.integration.file.FileReadingMessageSourceIntegrationTests).inputDir}" p:filter-ref="compositeFilter"/> + + diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests-context.xml b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests-context.xml index a33feb87b79..86b73c71195 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests-context.xml +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests-context.xml @@ -10,6 +10,8 @@ p:directory="#{T(org.springframework.integration.file.FileReadingMessageSourcePersistentFilterIntegrationTests).inputDir}" p:filter-ref="persistentFilter"/> + + diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java index 985f4047139..8640676edac 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java @@ -23,6 +23,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; @@ -39,7 +40,7 @@ * @author Artem Bilan * @author Gary Russell */ -class FileReadingMessageSourceTests { +class FileReadingMessageSourceTests implements TestApplicationContextAware { private FileReadingMessageSource source; @@ -63,7 +64,7 @@ public void initialize() { this.source = new FileReadingMessageSource(comparator); this.source.setDirectory(inputDirectoryMock); this.source.setLocker(locker); - this.source.setBeanFactory(mock()); + this.source.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.source.afterPropertiesSet(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java index 5f5d091c71d..8d388f72331 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java @@ -41,7 +41,6 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.log.LogAccessor; import org.springframework.expression.Expression; @@ -50,6 +49,7 @@ import org.springframework.integration.file.support.FileExistsMode; import org.springframework.integration.file.support.FileUtils; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; @@ -81,7 +81,7 @@ * @author Artem Bilan * @author Alen Turkovic */ -public class FileWritingMessageHandlerTests { +public class FileWritingMessageHandlerTests implements TestApplicationContextAware { static final String DEFAULT_ENCODING = "UTF-8"; @@ -104,7 +104,7 @@ void setup() throws IOException { new FileOutputStream(sourceFile, false)); this.handler = new FileWritingMessageHandler(this.outputDirectory); - this.handler.setBeanFactory(mock(BeanFactory.class)); + this.handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.handler.setApplicationContext(new GenericApplicationContext()); this.handler.afterPropertiesSet(); @@ -274,7 +274,7 @@ public void inputStreamPayloadCopiedToNewFileWithNewLines() throws Exception { public void testCreateDirFail() { File dir = new File("/foo"); FileWritingMessageHandler handler = new FileWritingMessageHandler(dir); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(handler::afterPropertiesSet) .withMessageContaining("[/foo] could not be created"); @@ -498,7 +498,7 @@ public void noFlushAppend() throws Exception { taskScheduler.afterPropertiesSet(); handler.setTaskScheduler(taskScheduler); handler.setOutputChannel(new NullChannel()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setFlushInterval(30000); handler.afterPropertiesSet(); handler.start(); @@ -583,7 +583,7 @@ protected BufferedOutputStream createOutputStream(File fileToWriteTo, boolean ap taskScheduler.afterPropertiesSet(); handler.setTaskScheduler(taskScheduler); handler.setOutputChannel(new NullChannel()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setFlushInterval(10); handler.setFlushWhenIdle(false); handler.afterPropertiesSet(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java index 95fc104aa4b..9624f5f9939 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java @@ -29,16 +29,15 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.file.filters.ChainFileListFilter; import org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter; import org.springframework.integration.file.filters.LastModifiedFileListFilter; import org.springframework.integration.metadata.SimpleMetadataStore; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Gary Russell @@ -47,7 +46,7 @@ * @since 4.2 * */ -public class WatchServiceDirectoryScannerTests { +public class WatchServiceDirectoryScannerTests implements TestApplicationContextAware { @TempDir public File rootDir; @@ -89,7 +88,7 @@ public void testWatchServiceDirectoryScanner() throws Exception { FileReadingMessageSource.WatchEventType.MODIFY, FileReadingMessageSource.WatchEventType.DELETE); fileReadingMessageSource.setWatchDirPredicate(path -> !path.getFileName().toString().equals("skipped")); - fileReadingMessageSource.setBeanFactory(mock(BeanFactory.class)); + fileReadingMessageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); final CountDownLatch removeFileLatch = new CountDownLatch(1); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java index 458ee03c914..3a88e5c537d 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java @@ -31,6 +31,7 @@ import org.springframework.integration.file.DefaultFileNameGenerator; import org.springframework.integration.file.FileWritingMessageHandler; import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -52,7 +53,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class FileOutboundGatewayParserTests { +public class FileOutboundGatewayParserTests implements TestApplicationContextAware { @TempDir public static File tempFolder; @@ -139,6 +140,7 @@ public void testOutboundGatewayWithDirectoryExpression() { public void gatewayWithIgnoreMode() throws Exception { final MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultDestination(this.gatewayWithIgnoreModeChannel); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); final String expectedFileContent = "Initial File Content:"; final File testFile = new File(tempFolder, "fileToAppend.txt"); @@ -170,6 +172,7 @@ public void gatewayWithIgnoreMode() throws Exception { public void gatewayWithFailMode() throws Exception { final MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultDestination(this.gatewayWithFailModeChannel); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); String expectedFileContent = "Initial File Content:"; @@ -197,6 +200,7 @@ public void gatewayWithFailMode() throws Exception { public void gatewayWithFailModeLowercase() throws Exception { final MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultDestination(this.gatewayWithFailModeLowercaseChannel); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); String expectedFileContent = "Initial File Content:"; @@ -225,6 +229,7 @@ public void gatewayWithFailModeLowercase() throws Exception { @Test public void gatewayWithAppendMode() throws Exception { final MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); messagingTemplate.setDefaultDestination(this.gatewayWithAppendModeChannel); String expectedFileContent = "Initial File Content:String content:"; @@ -261,6 +266,7 @@ public void gatewayWithReplaceMode() throws Exception { final MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultDestination(this.gatewayWithReplaceModeChannel); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); String expectedFileContent = "String content:"; diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests-context.xml b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests-context.xml index 98d482f008e..c6fa8f28327 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests-context.xml +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests-context.xml @@ -1,24 +1,26 @@ - - + + - + - + - - + + + diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileStreamingMessageSourceTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileStreamingMessageSourceTests.java index 1e2726c29c7..8fe81d3ce70 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileStreamingMessageSourceTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileStreamingMessageSourceTests.java @@ -25,15 +25,21 @@ import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.context.expression.MapAccessor; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.file.filters.FileListFilter; import org.springframework.integration.file.remote.session.CachingSessionFactory; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -46,7 +52,7 @@ * @since 5.2.2 * */ -public class RemoteFileStreamingMessageSourceTests { +public class RemoteFileStreamingMessageSourceTests implements TestApplicationContextAware { @Test public void fetchFilesFromRemoteAfterClearingFetchedCache() throws IOException { @@ -61,7 +67,7 @@ public void fetchFilesFromRemoteAfterClearingFetchedCache() throws IOException { new TestRemoteFileStreamingMessageSource(remoteFileTemplate, comparator); testRemoteFileStreamingMessageSource.setRemoteDirectory("remoteDirectory"); - testRemoteFileStreamingMessageSource.setBeanFactory(mock()); + testRemoteFileStreamingMessageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); testRemoteFileStreamingMessageSource.start(); assertThat(testRemoteFileStreamingMessageSource.doReceive(2)) @@ -95,7 +101,7 @@ public void filterOutFilesNotAcceptedByFilter() throws IOException { testRemoteFileStreamingMessageSource.setFilter(fileListFilter); testRemoteFileStreamingMessageSource.setRemoteDirectory("remoteDirectory"); - testRemoteFileStreamingMessageSource.setBeanFactory(mock()); + testRemoteFileStreamingMessageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); testRemoteFileStreamingMessageSource.start(); assertThat(testRemoteFileStreamingMessageSource.doReceive(-1)).isNull(); @@ -117,7 +123,7 @@ public void sessionReturnedToCacheProperlyOnDoReceive() throws IOException { new TestRemoteFileStreamingMessageSource(remoteFileTemplate, null); testRemoteFileStreamingMessageSource.setRemoteDirectory("remoteDirectory"); - testRemoteFileStreamingMessageSource.setBeanFactory(mock()); + testRemoteFileStreamingMessageSource.setBeanFactory(createTestEvaluationContext()); testRemoteFileStreamingMessageSource.start(); assertThatExceptionOfType(UncheckedIOException.class) @@ -126,6 +132,18 @@ public void sessionReturnedToCacheProperlyOnDoReceive() throws IOException { assertThat(cachingSessionFactory.getSession()).isNotNull(); } + private static BeanFactory createTestEvaluationContext() { + final String integrationEvaluationContextBeanName = "integrationEvaluationContext"; + BeanFactory beanFactory = mock(BeanFactory.class); + when(beanFactory.containsBean(eq(integrationEvaluationContextBeanName))) + .thenReturn(true); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + evaluationContext.addPropertyAccessor(new MapAccessor()); + when(beanFactory.getBean(eq(integrationEvaluationContextBeanName), any(Class.class))) + .thenReturn(evaluationContext); + return beanFactory; + } + static class TestRemoteFileStreamingMessageSource extends AbstractRemoteFileStreamingMessageSource { TestRemoteFileStreamingMessageSource(RemoteFileTemplate template, Comparator comparator) { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java index c713b18a09e..59ecb5fca4e 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java @@ -28,12 +28,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.ByteArrayResource; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.file.support.FileExistsMode; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; @@ -56,7 +56,7 @@ * @since 4.1.7 * */ -public class RemoteFileTemplateTests { +public class RemoteFileTemplateTests implements TestApplicationContextAware { private RemoteFileTemplate template; @@ -73,7 +73,7 @@ public void setUp() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); this.template = new RemoteFileTemplate<>(sessionFactory); this.template.setRemoteDirectoryExpression(new LiteralExpression("/foo")); - this.template.setBeanFactory(mock(BeanFactory.class)); + this.template.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.template.afterPropertiesSet(); this.session = mock(Session.class); when(sessionFactory.getSession()).thenReturn(this.session); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java index 2ec4591aecd..2ad75b75159 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java @@ -31,7 +31,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.StaticMessageHeaderAccessor; import org.springframework.integration.channel.QueueChannel; @@ -44,6 +43,7 @@ import org.springframework.integration.file.splitter.FileSplitter; import org.springframework.integration.metadata.ConcurrentMetadataStore; import org.springframework.integration.metadata.SimpleMetadataStore; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.transformer.StreamTransformer; import org.springframework.messaging.Message; @@ -64,7 +64,7 @@ * @since 4.3 * */ -public class StreamingInboundTests { +public class StreamingInboundTests implements TestApplicationContextAware { private final StreamTransformer transformer = new StreamTransformer(); @@ -87,7 +87,7 @@ public void testAllDataBulkOnlyFilter() throws IOException { private void testAllData(FileListFilter filter, boolean nullFilter) throws IOException { StringSessionFactory sessionFactory = new StringSessionFactory(); Streamer streamer = new Streamer(new StringRemoteFileTemplate(sessionFactory), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/foo"); if (filter != null) { streamer.setFilter(filter); @@ -145,7 +145,7 @@ private void testAllData(FileListFilter filter, boolean nullFilter) thro public void testAllDataMaxFetch() throws Exception { StringSessionFactory sessionFactory = new StringSessionFactory(); Streamer streamer = new Streamer(new StringRemoteFileTemplate(sessionFactory), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/foo"); streamer.setFilter(new AcceptOnceFileListFilter<>()); streamer.afterPropertiesSet(); @@ -177,7 +177,7 @@ public void testAllDataMaxFetch() throws Exception { public void testExceptionOnFetch() { StringSessionFactory sessionFactory = new StringSessionFactory(); Streamer streamer = new Streamer(new StringRemoteFileTemplate(sessionFactory), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/bad"); streamer.afterPropertiesSet(); streamer.start(); @@ -188,13 +188,13 @@ public void testExceptionOnFetch() { @Test public void testLineByLine() throws Exception { Streamer streamer = new Streamer(new StringRemoteFileTemplate(new StringSessionFactory()), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/foo"); streamer.afterPropertiesSet(); streamer.start(); QueueChannel out = new QueueChannel(); FileSplitter splitter = new FileSplitter(); - splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.setBeanFactory(TEST_INTEGRATION_CONTEXT); splitter.setOutputChannel(out); splitter.afterPropertiesSet(); Message receivedStream = streamer.receive(); @@ -236,7 +236,7 @@ public void testLineByLine() throws Exception { @Test public void testStopAdapterRemovesUnprocessed() { Streamer streamer = new Streamer(new StringRemoteFileTemplate(new StringSessionFactory()), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/foo"); streamer.afterPropertiesSet(); streamer.start(); @@ -251,7 +251,7 @@ public void testStopAdapterRemovesUnprocessed() { @Test public void testFilterReversedOnBadFetch() { Streamer streamer = new Streamer(new StringRemoteFileTemplate(new StringSessionFactory()), null); - streamer.setBeanFactory(mock(BeanFactory.class)); + streamer.setBeanFactory(TEST_INTEGRATION_CONTEXT); streamer.setRemoteDirectory("/bad"); streamer.afterPropertiesSet(); streamer.start(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java index af4b5166079..4b41da1df92 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java @@ -36,7 +36,6 @@ import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.file.FileHeaders; @@ -48,6 +47,7 @@ import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.file.support.FileExistsMode; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandlingException; @@ -76,7 +76,7 @@ * @since 2.1 */ @SuppressWarnings("rawtypes") -public class RemoteFileOutboundGatewayTests { +public class RemoteFileOutboundGatewayTests implements TestApplicationContextAware { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); @@ -841,12 +841,12 @@ public boolean exists(String path) { }; template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpressionString("'foo/'"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); @@ -872,12 +872,12 @@ public void testPutExists() throws Exception { .exists(anyString()); RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); @@ -932,12 +932,12 @@ public void testPutExistsExpression() throws Exception { .exists(anyString()); RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); gw.afterPropertiesSet(); gw.setFileExistsModeExpressionString("headers[\"file.exists.mode\"]"); @@ -992,7 +992,7 @@ public void testMput() throws Exception { Session session = mock(Session.class); RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", "payload"); gw.afterPropertiesSet(); @@ -1019,7 +1019,7 @@ public void testMputRecursive() throws Exception { Session session = mock(Session.class); RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", null); gw.setOptions("-R"); @@ -1177,14 +1177,14 @@ static class TestRemoteFileOutboundGateway extends AbstractRemoteFileOutboundGat TestRemoteFileOutboundGateway(SessionFactory sessionFactory, String command, String expression) { super(sessionFactory, Command.toCommand(command), expression); - this.setBeanFactory(mock(BeanFactory.class)); + this.setBeanFactory(TEST_INTEGRATION_CONTEXT); remoteFileTemplateExplicitlySet(false); } TestRemoteFileOutboundGateway(RemoteFileTemplate remoteFileTemplate, String command, String expression) { super(remoteFileTemplate, command, expression); - this.setBeanFactory(mock(BeanFactory.class)); + this.setBeanFactory(TEST_INTEGRATION_CONTEXT); } @Override diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java index 6741aa0ae94..1406831c238 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.ExpressionParser; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; @@ -32,6 +31,7 @@ import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.SimplePool; import org.springframework.messaging.Message; @@ -54,7 +54,7 @@ * @author Gunnar Hillert * @author Artem Bilan */ -public class FileTransferringMessageHandlerTests { +public class FileTransferringMessageHandlerTests implements TestApplicationContextAware { @SuppressWarnings("unchecked") @Test @@ -71,7 +71,7 @@ public void testRemoteDirWithEmptyString() throws Exception { ExpressionParser parser = new SpelExpressionParser(); FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sf); handler.setRemoteDirectoryExpression(parser.parseExpression("''")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage("hello")); verify(session, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); @@ -94,7 +94,7 @@ public void testTemporaryRemoteDir() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sf); handler.setRemoteDirectoryExpression(new LiteralExpression("foo")); handler.setTemporaryRemoteDirectoryExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage("hello")); verify(session, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); @@ -117,7 +117,7 @@ public void testRemoteDirWithNull() throws Exception { ExpressionParser parser = new SpelExpressionParser(); FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sf); handler.setRemoteDirectoryExpression(parser.parseExpression("headers['path']")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload("hello").setHeader("path", null).build(); handler.handleMessage(message); @@ -131,7 +131,7 @@ public void testEmptyTemporaryFileSuffixCannotBeNull() throws Exception { Session session = mock(Session.class); when(sf.getSession()).thenReturn(session); FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sf); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setRemoteDirectoryExpressionString("headers['path']"); assertThatIllegalArgumentException() .isThrownBy(() -> handler.setTemporaryFileSuffix(null)); @@ -149,7 +149,7 @@ public void testUseTemporaryFileNameFalse() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sf); handler.setRemoteDirectoryExpression(parser.parseExpression("headers['path']")); handler.setUseTemporaryFileName(false); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload("hello").setHeader("path", null).build(); handler.handleMessage(message); @@ -163,7 +163,7 @@ public void testServerException() throws Exception { SessionFactory sf = mock(SessionFactory.class); CachingSessionFactory csf = new CachingSessionFactory(sf, 2); FileTransferringMessageHandler handler = new FileTransferringMessageHandler(csf); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); Session session1 = newSession(); Session session2 = newSession(); Session session3 = newSession(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java index 362075f0194..13274fa40af 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java @@ -22,9 +22,9 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.file.remote.RemoteFileTemplate; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; @@ -42,7 +42,7 @@ * @since 3.0 * */ -public class CachingSessionFactoryTests { +public class CachingSessionFactoryTests implements TestApplicationContextAware { @Test public void testCacheAndReset() { @@ -87,7 +87,7 @@ public void testDirtySession() throws Exception { CachingSessionFactory ccf = new CachingSessionFactory<>(factory); RemoteFileTemplate template = new RemoteFileTemplate<>(ccf); template.setFileNameExpression(new LiteralExpression("foo")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); assertThatExceptionOfType(MessagingException.class) diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java index 3aadcbd4bc1..e6cf01128b2 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java @@ -31,7 +31,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.EvaluationContext; import org.springframework.integration.expression.SupplierExpression; import org.springframework.integration.file.HeadDirectoryScanner; @@ -39,6 +38,7 @@ import org.springframework.integration.file.filters.ChainFileListFilter; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.MessagingException; import static org.assertj.core.api.Assertions.assertThat; @@ -54,7 +54,7 @@ * @since 4.0.4 * */ -public class AbstractRemoteFileSynchronizerTests { +public class AbstractRemoteFileSynchronizerTests implements TestApplicationContextAware { @Test public void testRollback() throws Exception { @@ -144,6 +144,7 @@ public void testMaxFetchSizeSource() { public void testDefaultFilter() { final AtomicInteger count = new AtomicInteger(); AbstractInboundFileSynchronizingMessageSource source = createSource(count); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); source.start(); source.receive(); @@ -162,6 +163,7 @@ public void testNoFilter() { AbstractInboundFileSynchronizer sync = createLimitingSynchronizer(count); sync.setFilter(null); AbstractInboundFileSynchronizingMessageSource source = createSource(sync); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); source.start(); source.receive(); @@ -259,7 +261,7 @@ protected String protocol() { remoteDirs.add("dir2"); sync.setRemoteDirectoryExpression(new SupplierExpression<>(remoteDirs::poll)); sync.setLocalFilenameGeneratorExpressionString("#remoteDirectory+'/'+#root"); - sync.setBeanFactory(mock(BeanFactory.class)); + sync.setBeanFactory(TEST_INTEGRATION_CONTEXT); sync.afterPropertiesSet(); sync.synchronizeToLocalDirectory(localDir); @@ -292,7 +294,7 @@ public String getComponentType() { source.setMaxFetchSize(1); source.setLocalDirectory(new File(System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID())); source.setAutoCreateLocalDirectory(true); - source.setBeanFactory(mock(BeanFactory.class)); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.setBeanName("fooSource"); return source; } @@ -333,7 +335,7 @@ protected boolean copyFileToLocalDirectory(String remoteDirectoryPath, }; sync.setFilter(new AcceptOnceFileListFilter<>()); sync.setRemoteDirectory("foo"); - sync.setBeanFactory(mock(BeanFactory.class)); + sync.setBeanFactory(TEST_INTEGRATION_CONTEXT); return sync; } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java index 113c1f7d258..7e0507790aa 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java @@ -36,6 +36,7 @@ import org.springframework.integration.file.FileHeaders; import org.springframework.integration.file.tail.FileTailingMessageProducerSupport.FileTailingEvent; import org.springframework.integration.file.tail.FileTailingMessageProducerSupport.FileTailingIdleEvent; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; @@ -52,7 +53,7 @@ * * @since 3.0 */ -public class FileTailingMessageProducerTests { +public class FileTailingMessageProducerTests implements TestApplicationContextAware { private static final String TAIL_OPTIONS_FOLLOW_NAME_ALL_LINES = "-F -n +0"; @@ -166,6 +167,7 @@ public boolean exists() { adapter.setOutputChannel(new NullChannel()); adapter.setIdleEventInterval(10); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpInboundRemoteFileSystemSynchronizerTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpInboundRemoteFileSystemSynchronizerTests.java index 54c5f637a4e..b0882430bbc 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpInboundRemoteFileSystemSynchronizerTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpInboundRemoteFileSystemSynchronizerTests.java @@ -32,7 +32,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelParserConfiguration; @@ -49,6 +48,7 @@ import org.springframework.integration.metadata.MetadataStore; import org.springframework.integration.metadata.PropertiesPersistingMetadataStore; import org.springframework.integration.metadata.SimpleMetadataStore; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; @@ -67,7 +67,7 @@ * * @since 2.0 */ -public class FtpInboundRemoteFileSystemSynchronizerTests { +public class FtpInboundRemoteFileSystemSynchronizerTests implements TestApplicationContextAware { private static FTPClient ftpClient = mock(FTPClient.class); @@ -107,14 +107,14 @@ public void testCopyFileToLocalDir() throws Exception { ExpressionParser expressionParser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression expression = expressionParser.parseExpression("'subdir/' + #this.toUpperCase() + '.a'"); synchronizer.setLocalFilenameGeneratorExpression(expression); - synchronizer.setBeanFactory(mock(BeanFactory.class)); + synchronizer.setBeanFactory(TEST_INTEGRATION_CONTEXT); synchronizer.afterPropertiesSet(); FtpInboundFileSynchronizingMessageSource ms = new FtpInboundFileSynchronizingMessageSource(synchronizer); ms.setAutoCreateLocalDirectory(true); ms.setLocalDirectory(localDirectory); - ms.setBeanFactory(mock(BeanFactory.class)); + ms.setBeanFactory(TEST_INTEGRATION_CONTEXT); CompositeFileListFilter localFileListFilter = new CompositeFileListFilter<>(); localFileListFilter.addFilter(new RegexPatternFileListFilter(".*\\.TEST\\.a$")); AcceptOnceFileListFilter localAcceptOnceFilter = new AcceptOnceFileListFilter<>(); @@ -179,7 +179,7 @@ public void testSyncRemoteFileOnlyOnceByDefault() { FtpInboundFileSynchronizer synchronizer = spy(new FtpInboundFileSynchronizer(ftpSessionFactory)); synchronizer.setRemoteDirectory("remote-test-dir"); - synchronizer.setBeanFactory(mock(BeanFactory.class)); + synchronizer.setBeanFactory(TEST_INTEGRATION_CONTEXT); synchronizer.afterPropertiesSet(); synchronizer.synchronizeToLocalDirectory(localDirectory); diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpMessageSourceTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpMessageSourceTests.java index 3d1a8c46be2..8b30decaa8e 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpMessageSourceTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/inbound/FtpMessageSourceTests.java @@ -20,7 +20,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.file.FileHeaders; import org.springframework.integration.ftp.FtpTestSupport; import org.springframework.messaging.Message; @@ -65,6 +67,11 @@ private FtpInboundFileSynchronizingMessageSource buildSource() throws Exception @Configuration public static class Config { + @Bean + StandardEvaluationContext integrationEvaluationContext() { + return new StandardEvaluationContext(); + } + } } diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpOutboundTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpOutboundTests.java index f350f10e1cb..3b085be84e1 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpOutboundTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpOutboundTests.java @@ -37,7 +37,6 @@ import org.mockito.Mockito; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.expression.common.LiteralExpression; @@ -46,6 +45,7 @@ import org.springframework.integration.file.remote.handler.FileTransferringMessageHandler; import org.springframework.integration.ftp.session.AbstractFtpSessionFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -66,7 +66,7 @@ * @author Gunnar Hillert * @author Gary Russell */ -public class FtpOutboundTests { +public class FtpOutboundTests implements TestApplicationContextAware { private static FTPClient ftpClient; @@ -92,7 +92,7 @@ public void testHandleFileContentMessage() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); handler.setFileNameGenerator(message -> "handlerContent.test"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("String data")); assertThat(file.exists()).isTrue(); @@ -111,7 +111,7 @@ public void testHandleFileAsByte() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); handler.setFileNameGenerator(message -> "handlerContent.test"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("byte[] data".getBytes())); assertThat(file.exists()).isTrue(); @@ -128,7 +128,7 @@ public void testHandleFileMessage() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression(targetDir.getName())); handler.setFileNameGenerator(message -> ((File) message.getPayload()).getName() + ".test"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); File srcFile = File.createTempFile("testHandleFileMessage", ".tmp"); @@ -149,7 +149,7 @@ public void testHandleMissingFileMessage() { FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression(targetDir.getName())); handler.setFileNameGenerator(message -> ((File) message.getPayload()).getName() + ".test"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); File srcFile = new File(UUID.randomUUID() + ".txt"); diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpServerOutboundTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpServerOutboundTests.java index 9a9f5cff6a2..bf727500a84 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpServerOutboundTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/outbound/FtpServerOutboundTests.java @@ -42,7 +42,6 @@ import org.mockito.Mockito; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; @@ -72,6 +71,7 @@ import org.springframework.integration.ftp.session.FtpRemoteFileTemplate; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.PartialSuccessException; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; @@ -87,7 +87,6 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -100,7 +99,7 @@ */ @SpringJUnitConfig @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class FtpServerOutboundTests extends FtpTestSupport { +public class FtpServerOutboundTests extends FtpTestSupport implements TestApplicationContextAware { @Autowired private SessionFactory ftpSessionFactory; @@ -378,7 +377,7 @@ public void testInt3100RawGET() throws Exception { public void testRawGETWithTemplate() { RemoteFileTemplate template = new RemoteFileTemplate<>(this.ftpSessionFactory); template.setFileNameExpression(new SpelExpressionParser().parseExpression("payload")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); final ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); assertThat(template.get(new GenericMessage<>("ftpSource/ ftpSource1.txt"), diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/session/FtpRemoteFileTemplateTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/session/FtpRemoteFileTemplateTests.java index d07f4997e65..d92aed878b9 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/session/FtpRemoteFileTemplateTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/session/FtpRemoteFileTemplateTests.java @@ -26,7 +26,6 @@ import org.apache.commons.net.ftp.FTPFile; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -38,6 +37,7 @@ import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.file.support.FileExistsMode; import org.springframework.integration.ftp.FtpTestSupport; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.SimplePool; import org.springframework.messaging.MessagingException; @@ -58,7 +58,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class FtpRemoteFileTemplateTests extends FtpTestSupport { +public class FtpRemoteFileTemplateTests extends FtpTestSupport implements TestApplicationContextAware { @Autowired private SessionFactory sessionFactory; @@ -67,12 +67,12 @@ public class FtpRemoteFileTemplateTests extends FtpTestSupport { public void testINT3412AppendStatRmdir() { FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(sessionFactory); DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); - fileNameGenerator.setBeanFactory(mock(BeanFactory.class)); + fileNameGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); fileNameGenerator.setExpression("'foobar.txt'"); template.setFileNameGenerator(fileNameGenerator); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setUseTemporaryFileName(false); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); template.execute(session -> { session.mkdir("foo/"); @@ -125,7 +125,7 @@ public void testConnectionClosedAfterExists() throws Exception { FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(this.sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("/")); template.setExistsMode(FtpRemoteFileTemplate.ExistsMode.NLST_AND_DIRS); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); File file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); FileOutputStream fileOutputStream = new FileOutputStream(file); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingControllerTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingControllerTests.java index dbe711c4812..0481342f177 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingControllerTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingControllerTests.java @@ -27,7 +27,6 @@ import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.http.HttpStatus; @@ -36,6 +35,7 @@ import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; import org.springframework.integration.http.AbstractHttpInboundTests; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -57,13 +57,13 @@ * * @since 2.0 */ -public class HttpRequestHandlingControllerTests extends AbstractHttpInboundTests { +public class HttpRequestHandlingControllerTests extends AbstractHttpInboundTests implements TestApplicationContextAware { @Test public void sendOnly() { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingController controller = new HttpRequestHandlingController(false); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.afterPropertiesSet(); @@ -90,7 +90,7 @@ public void sendOnly() { public void sendOnlyViewExpression() { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingController controller = new HttpRequestHandlingController(false); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); Expression viewExpression = new SpelExpressionParser().parseExpression("'baz'"); controller.setViewExpression(viewExpression); @@ -126,7 +126,7 @@ protected Object handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.afterPropertiesSet(); @@ -162,7 +162,7 @@ protected Message handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); Expression viewExpression = new SpelExpressionParser().parseExpression("headers['bar']"); controller.setViewExpression(viewExpression); @@ -196,7 +196,7 @@ protected Message handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); Expression viewExpression = new SpelExpressionParser().parseExpression("headers['bar']"); controller.setViewExpression(viewExpression); @@ -228,7 +228,7 @@ protected Object handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.setReplyKey("myReply"); @@ -264,7 +264,7 @@ protected Object handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.setExtractReplyPayload(false); @@ -299,7 +299,7 @@ protected boolean doSend(Message message, long timeout) { } }; HttpRequestHandlingController controller = new HttpRequestHandlingController(false); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.afterPropertiesSet(); controller.start(); @@ -341,7 +341,7 @@ protected Object handleRequestMessage(Message requestMessage) { }; requestChannel.subscribe(handler); final HttpRequestHandlingController controller = new HttpRequestHandlingController(true); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.setRequestChannel(requestChannel); controller.setViewName("foo"); controller.afterPropertiesSet(); @@ -410,7 +410,7 @@ protected Object handleRequestMessage(Message requestMessage) { controller.setReplyKey("cookiesReply"); controller.setExtractReplyPayload(true); controller.setPayloadExpression(new SpelExpressionParser().parseExpression("#cookies['c1'][0].value")); - controller.setBeanFactory(mock(BeanFactory.class)); + controller.setBeanFactory(TEST_INTEGRATION_CONTEXT); controller.afterPropertiesSet(); controller.start(); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayTests.java index 7e81b0c1f8e..b65eca4c1d4 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayTests.java @@ -29,7 +29,6 @@ import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ResolvableType; import org.springframework.expression.common.LiteralExpression; @@ -50,6 +49,7 @@ import org.springframework.integration.http.HttpHeaders; import org.springframework.integration.http.converter.SerializingHttpMessageConverter; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import org.springframework.mock.web.MockHttpServletRequest; @@ -72,14 +72,14 @@ * * @since 2.0 */ -public class HttpRequestHandlingMessagingGatewayTests extends AbstractHttpInboundTests { +public class HttpRequestHandlingMessagingGatewayTests extends AbstractHttpInboundTests implements TestApplicationContextAware { @Test @SuppressWarnings("unchecked") public void getRequestGeneratesMapPayload() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.afterPropertiesSet(); gateway.start(); @@ -101,7 +101,7 @@ public void getRequestGeneratesMapPayload() throws Exception { public void stringExpectedWithoutReply() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestPayloadTypeClass(String.class); gateway.setRequestChannel(requestChannel); gateway.afterPropertiesSet(); @@ -140,7 +140,7 @@ protected Object handleRequestMessage(Message requestMessage) { }); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); gateway.setStatusCodeExpression(new LiteralExpression("foo")); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestPayloadTypeClass(String.class); gateway.setRequestChannel(requestChannel); gateway.afterPropertiesSet(); @@ -169,7 +169,7 @@ protected Object handleRequestMessage(Message requestMessage) { } }); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestPayloadTypeClass(String.class); gateway.setRequestChannel(requestChannel); gateway.afterPropertiesSet(); @@ -197,7 +197,7 @@ protected boolean doSend(Message message, long timeout) { }; HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.setConvertExceptions(true); gateway.setMessageConverters(Collections.singletonList(new TestHttpMessageConverter())); @@ -217,7 +217,7 @@ protected boolean doSend(Message message, long timeout) { public void multiValueParameterMap() throws Exception { QueueChannel channel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(channel); gateway.afterPropertiesSet(); gateway.start(); @@ -244,7 +244,7 @@ public void multiValueParameterMap() throws Exception { public void serializableRequestBody() throws Exception { QueueChannel channel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestPayloadTypeClass(TestBean.class); gateway.setRequestChannel(channel); @@ -278,7 +278,7 @@ public void serializableRequestBody() throws Exception { public void testJsonRequestBody() throws Exception { QueueChannel channel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); ParameterizedTypeReference> parameterizedTypeReference = new ParameterizedTypeReference<>() { @@ -338,7 +338,7 @@ protected Object handleRequestMessage(Message requestMessage) { messageConverters.add(messageConverter); final HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setMessageConverters(messageConverters); gateway.setRequestChannel(requestChannel); gateway.start(); @@ -364,7 +364,7 @@ protected Object handleRequestMessage(Message requestMessage) { public void timeoutDefault() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.setReplyTimeout(0); gateway.afterPropertiesSet(); @@ -382,7 +382,7 @@ public void timeoutDefault() throws Exception { public void timeoutStatusExpression() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.setReplyTimeout(0); gateway.setStatusCodeExpression(new LiteralExpression("501")); @@ -402,7 +402,7 @@ public void timeoutStatusExpression() throws Exception { public void timeoutErrorFlow() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.setReplyTimeout(0); DirectChannel errorChannel = new DirectChannel(); @@ -432,7 +432,7 @@ protected Object handleRequestMessage(Message requestMessage) { public void timeoutErrorFlowTimeout() throws Exception { QueueChannel requestChannel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(requestChannel); gateway.setReplyTimeout(0); QueueChannel errorChannel = new QueueChannel(); @@ -454,7 +454,7 @@ public void timeoutErrorFlowTimeout() throws Exception { @Test public void testMultipart() throws Exception { HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); MultipartResolver multipartResolver = mock(MultipartResolver.class); gateway.setMultipartResolver(multipartResolver); gateway.setRequestChannel(new NullChannel()); @@ -476,7 +476,7 @@ public void testMultipart() throws Exception { public void deleteRequestBodyIgnored() throws Exception { QueueChannel channel = new QueueChannel(); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(false); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setRequestChannel(channel); gateway.afterPropertiesSet(); gateway.start(); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java index 5a474e99f82..f38f2f78ee1 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java @@ -20,13 +20,13 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.http.RequestEntity; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.http.AbstractHttpInboundTests; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.mock.web.MockHttpServletRequest; @@ -35,7 +35,6 @@ import org.springframework.web.servlet.HandlerMapping; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Oleg Zhurakousky @@ -45,7 +44,7 @@ * @author Artem Bilan * @author Biju Kunjummen */ -public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends AbstractHttpInboundTests { +public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends AbstractHttpInboundTests implements TestApplicationContextAware { private static final ExpressionParser PARSER = new SpelExpressionParser(); @@ -66,7 +65,7 @@ public void withoutExpression() { request.setRequestURI("/fname/bill/lname/clinton"); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); @@ -108,7 +107,7 @@ public void withPayloadExpressionPointingToPathVariable() { request.setRequestURI(requestURI); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); @@ -154,7 +153,7 @@ public void withoutPayloadExpressionPointingToUriVariables() { request.setRequestURI(requestURI); HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/MultipartAsRawByteArrayTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/MultipartAsRawByteArrayTests.java index 2b4a101feec..6efd8be6c8a 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/MultipartAsRawByteArrayTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/MultipartAsRawByteArrayTests.java @@ -24,9 +24,9 @@ import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; @@ -43,7 +43,7 @@ * * @since 4.2 */ -public class MultipartAsRawByteArrayTests { +public class MultipartAsRawByteArrayTests implements TestApplicationContextAware { @SuppressWarnings("unchecked") @Test @@ -53,7 +53,7 @@ public void testMultiPass() throws Exception { gw.setMergeWithDefaultConverters(false); QueueChannel requestChannel = new QueueChannel(); gw.setRequestChannel(requestChannel); - gw.setBeanFactory(mock(BeanFactory.class)); + gw.setBeanFactory(TEST_INTEGRATION_CONTEXT); gw.setRequestPayloadTypeClass(byte[].class); gw.afterPropertiesSet(); gw.start(); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/HttpRequestExecutingMessageHandlerTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/HttpRequestExecutingMessageHandlerTests.java index 90743def70d..82e854c1201 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/HttpRequestExecutingMessageHandlerTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/HttpRequestExecutingMessageHandlerTests.java @@ -29,16 +29,17 @@ import javax.xml.transform.Source; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.ParameterizedTypeReference; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.SimpleEvaluationContext; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -52,6 +53,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.http.converter.SerializingHttpMessageConverter; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; @@ -82,7 +84,7 @@ * @author Gunnar Hillert * @author Florian Schöffl */ -public class HttpRequestExecutingMessageHandlerTests { +public class HttpRequestExecutingMessageHandlerTests implements TestApplicationContextAware { // Used in the HttpOutboundWithinChainTests-context.xml public static ParameterizedTypeReference> testParameterizedTypeReference() { @@ -92,6 +94,13 @@ public static ParameterizedTypeReference> testParameterizedTypeRefe } + @BeforeEach + void setUp() { + TEST_INTEGRATION_CONTEXT.registerBean("integrationSimpleEvaluationContext", SimpleEvaluationContext + .forReadOnlyDataBinding() + .build()); + } + @Test public void simpleStringKeyStringValueFormData() { HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler( @@ -867,7 +876,7 @@ protected T doExecute(URI url, @Nullable String uriTemplate, @Nullable HttpM } private void setBeanFactory(HttpRequestExecutingMessageHandler handler) { - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); } private HttpHeaders setUpMocksToCaptureSentHeaders(RestTemplate restTemplate) throws IOException { diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java index 46e2c973495..f60e6306b50 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java @@ -22,23 +22,24 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.SimpleEvaluationContext; import org.springframework.integration.config.IntegrationRegistrar; import org.springframework.integration.expression.ExpressionEvalMap; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Dave Syer @@ -49,7 +50,14 @@ * * @since 2.0 */ -public class UriVariableExpressionTests { +public class UriVariableExpressionTests implements TestApplicationContextAware { + + @BeforeEach + void setUp() { + TEST_INTEGRATION_CONTEXT.registerBean("integrationSimpleEvaluationContext", SimpleEvaluationContext + .forReadOnlyDataBinding() + .build()); + } @Test public void testFromMessageWithExpressions() { @@ -62,7 +70,7 @@ public void testFromMessageWithExpressions() { uriHolder.set(uri); throw new RuntimeException("intentional"); }); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("bar"); try { @@ -92,7 +100,7 @@ public void testFromMessageWithSuperfluousExpressionsInt3054() { uriHolder.set(uri); throw new RuntimeException("intentional"); }); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); try { handler.handleMessage(new GenericMessage("bar")); diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/ThreadAffinityClientConnectionFactory.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/ThreadAffinityClientConnectionFactory.java index e3c335f2924..c0a87b86417 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/ThreadAffinityClientConnectionFactory.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/ThreadAffinityClientConnectionFactory.java @@ -111,6 +111,7 @@ public String getComponentType() { @Override public void setBeanFactory(BeanFactory beanFactory) { + super.setBeanFactory(beanFactory); this.connectionFactory.setBeanFactory(beanFactory); } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/ConnectionFactoryTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/ConnectionFactoryTests.java index 0bcec7f69f3..f6057a72b48 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/ConnectionFactoryTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/ConnectionFactoryTests.java @@ -34,10 +34,12 @@ import org.springframework.integration.ip.tcp.connection.TcpSocketFactorySupport; import org.springframework.integration.ip.tcp.connection.TcpSocketSupport; import org.springframework.integration.ip.util.TestingUtilities; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.transformer.ObjectToStringTransformer; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -50,13 +52,14 @@ * @since 5.0 * */ -public class ConnectionFactoryTests { +public class ConnectionFactoryTests implements TestApplicationContextAware { @Test public void test() throws Exception { ApplicationEventPublisher publisher = e -> { }; AbstractServerConnectionFactory server = Tcp.netServer(0).backlog(2).soTimeout(5000).getObject(); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); final AtomicReference> received = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); server.registerListener(m -> { @@ -65,11 +68,13 @@ public void test() throws Exception { return false; }); server.setApplicationEventPublisher(publisher); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.start(); TestingUtilities.waitListening(server, null); AbstractClientConnectionFactory client = Tcp.netClient("localhost", server.getPort()).getObject(); client.setApplicationEventPublisher(publisher); + client.setBeanFactory(TEST_INTEGRATION_CONTEXT); client.afterPropertiesSet(); client.start(); client.getConnection().send(new GenericMessage<>("foo")); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/IpIntegrationTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/IpIntegrationTests.java index d5003f1d9aa..1a042b749a5 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/IpIntegrationTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/dsl/IpIntegrationTests.java @@ -63,11 +63,13 @@ import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter; import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.ReflectionUtils; @@ -83,7 +85,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class IpIntegrationTests { +public class IpIntegrationTests implements TestApplicationContextAware { @Autowired private ConfigurableApplicationContext applicationContext; @@ -134,16 +136,19 @@ void testTcpAdapters() { AbstractServerConnectionFactory server = Tcp.netServer(0).backlog(2).soTimeout(5000).id("server").getObject(); assertThat(server.getComponentName()).isEqualTo("server"); server.setApplicationEventPublisher(publisher); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); TcpReceivingChannelAdapter inbound = Tcp.inboundAdapter(server).getObject(); QueueChannel received = new QueueChannel(); inbound.setOutputChannel(received); + inbound.setBeanFactory(TEST_INTEGRATION_CONTEXT); inbound.afterPropertiesSet(); inbound.start(); TestingUtilities.waitListening(server, null); AbstractClientConnectionFactory client = Tcp.netClient("localhost", server.getPort()).id("client").getObject(); assertThat(client.getComponentName()).isEqualTo("client"); client.setApplicationEventPublisher(publisher); + client.setBeanFactory(TEST_INTEGRATION_CONTEXT); client.afterPropertiesSet(); TcpSendingMessageHandler handler = Tcp.outboundAdapter(client).getObject(); handler.start(); @@ -163,6 +168,7 @@ void testTcpGateways() { this.client1.start(); MessagingTemplate messagingTemplate = new MessagingTemplate(this.clientTcpFlowInput); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(messagingTemplate.convertSendAndReceive("foo", String.class)).isEqualTo("FOO"); assertThat(messagingTemplate.convertSendAndReceive("junk", String.class)).isEqualTo("error:non-convertible"); @@ -182,6 +188,7 @@ void testUdp() throws Exception { .setHeader("udp_dest", "udp://localhost:" + this.udpInbound.getPort()) .build(); this.udpOut.send(outMessage); + this.udpIn.setTaskScheduler(new SimpleAsyncTaskScheduler()); Message received = this.udpIn.receive(10000); assertThat(received).isNotNull(); assertThat(Transformers.objectToString().transform(received).getPayload()).isEqualTo("foo"); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java index 4a7000ddffa..2e1814192fc 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java @@ -52,6 +52,7 @@ import org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer; import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; @@ -67,7 +68,7 @@ * * @since 2.0 */ -public class TcpInboundGatewayTests { +public class TcpInboundGatewayTests implements TestApplicationContextAware { @Test public void testNetSingle() throws Exception { @@ -75,7 +76,7 @@ public void testNetSingle() throws Exception { scf.setSingleUse(true); TcpInboundGateway gateway = new TcpInboundGateway(); gateway.setConnectionFactory(scf); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); scf.start(); TestingUtilities.waitListening(scf, 20000L); int port = scf.getPort(); @@ -83,7 +84,7 @@ public void testNetSingle() throws Exception { gateway.setRequestChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); handler.setChannelResolver(channelName -> channel); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", port); socket1.getOutputStream().write("Test1\r\n".getBytes()); @@ -111,9 +112,9 @@ public void testNetNotSingle() throws Exception { int port = scf.getPort(); final QueueChannel channel = new QueueChannel(); gateway.setRequestChannel(channel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); socket.getOutputStream().write("Test1\r\n".getBytes()); @@ -172,10 +173,10 @@ public void testNetClientMode() throws Exception { gateway.setRequestChannel(channel); gateway.setClientMode(true); gateway.setRetryInterval(10000); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(1); @@ -207,10 +208,10 @@ public void testNioSingle() throws Exception { int port = scf.getPort(); final QueueChannel channel = new QueueChannel(); gateway.setRequestChannel(channel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); handler.setChannelResolver(channelName -> channel); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", port); socket1.getOutputStream().write("Test1\r\n".getBytes()); @@ -238,9 +239,9 @@ public void testNioNotSingle() throws Exception { int port = scf.getPort(); final QueueChannel channel = new QueueChannel(); gateway.setRequestChannel(channel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); socket.getOutputStream().write("Test1\r\n".getBytes()); @@ -277,7 +278,7 @@ public void testErrorFlow() throws Exception { int port = scf.getPort(); final SubscribableChannel channel = new DirectChannel(); gateway.setRequestChannel(channel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService()); channel.subscribe(handler); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", port); @@ -314,14 +315,14 @@ private void testCloseStream(AbstractServerConnectionFactory scf, TcpInboundGateway gateway = new TcpInboundGateway(); gateway.setConnectionFactory(scf); BeanFactory bf = mock(ConfigurableBeanFactory.class); - gateway.setBeanFactory(bf); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.start(); TestingUtilities.waitListening(scf, 20000L); int port = scf.getPort(); final DirectChannel channel = new DirectChannel(); gateway.setRequestChannel(channel); BridgeHandler bridge = new BridgeHandler(); - bridge.setBeanFactory(bf); + bridge.setBeanFactory(TEST_INTEGRATION_CONTEXT); bridge.afterPropertiesSet(); ConsumerEndpointFactoryBean consumer = new ConsumerEndpointFactoryBean(); consumer.setInputChannel(channel); @@ -335,6 +336,7 @@ private void testCloseStream(AbstractServerConnectionFactory scf, latch.countDown(); return false; }); + client.setBeanFactory(TEST_INTEGRATION_CONTEXT); client.afterPropertiesSet(); client.start(); TcpConnectionSupport connection = client.getConnection(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java index cb6ffb0cd31..918d01a5736 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java @@ -53,8 +53,11 @@ import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory; import org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer; import org.springframework.integration.ip.util.TestingUtilities; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.SubscribableChannel; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; @@ -64,11 +67,11 @@ * @author Gary Russell * @author Artem Bilan */ -public class TcpReceivingChannelAdapterTests extends AbstractTcpChannelAdapterTests { +public class TcpReceivingChannelAdapterTests extends AbstractTcpChannelAdapterTests implements TestApplicationContextAware { @Test public void testNet() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -80,7 +83,8 @@ public void testNet() throws Exception { int port = scf.getPort(); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(mock()); + adapter.setTaskScheduler(new SimpleAsyncTaskScheduler()); adapter.afterPropertiesSet(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); socket.getOutputStream().write("Test1\r\n".getBytes()); @@ -155,7 +159,7 @@ public void testNetClientMode() throws Exception { @Test public void testNio() throws Exception { - TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -186,7 +190,7 @@ public void testNio() throws Exception { @Test public void testNetShared() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -220,7 +224,7 @@ public void testNetShared() throws Exception { @Test public void testNioShared() throws Exception { - TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -254,7 +258,7 @@ public void testNioShared() throws Exception { @Test public void testNetSingleNoOutbound() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -286,7 +290,7 @@ public void testNetSingleNoOutbound() throws Exception { @Test public void testNioSingleNoOutbound() throws Exception { - TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -328,7 +332,7 @@ private void readFully(InputStream is, byte[] buff) throws IOException { @Test public void testNetSingleShared() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -365,7 +369,7 @@ public void testNetSingleShared() throws Exception { @Test public void testNioSingleShared() throws Exception { - TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -402,7 +406,7 @@ public void testNioSingleShared() throws Exception { @Test public void testNioSingleSharedMany() throws Exception { - TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); @@ -442,7 +446,7 @@ public void testNioSingleSharedMany() throws Exception { @Test public void testNetInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); interceptorsGuts(scf); scf.stop(); @@ -450,7 +454,7 @@ public void testNetInterceptors() throws Exception { @Test public void testNetSingleNoOutboundInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); singleNoOutboundInterceptorsGuts(scf); scf.stop(); @@ -458,7 +462,7 @@ public void testNetSingleNoOutboundInterceptors() throws Exception { @Test public void testNetSingleSharedInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); singleSharedInterceptorsGuts(scf); scf.stop(); @@ -466,7 +470,7 @@ public void testNetSingleSharedInterceptors() throws Exception { @Test public void testNioInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); interceptorsGuts(scf); scf.stop(); @@ -474,7 +478,7 @@ public void testNioInterceptors() throws Exception { @Test public void testNioSingleNoOutboundInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); singleNoOutboundInterceptorsGuts(scf); scf.stop(); @@ -482,7 +486,7 @@ public void testNioSingleNoOutboundInterceptors() throws Exception { @Test public void testNioSingleSharedInterceptors() throws Exception { - AbstractServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory scf = getDefaultServerConnectionFactory(); noopPublisher(scf); singleSharedInterceptorsGuts(scf); scf.stop(); @@ -623,15 +627,18 @@ public void testException() throws Exception { ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); scf.setDeserializer(serializer); + scf.setTaskScheduler(mock(TaskScheduler.class)); + TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(scf); + adapter.setTaskScheduler(mock(TaskScheduler.class)); scf.start(); TestingUtilities.waitListening(scf, null); int port = scf.getPort(); SubscribableChannel channel = new DirectChannel(); adapter.setOutputChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); channel.subscribe(handler); QueueChannel errorChannel = new QueueChannel(); @@ -648,6 +655,12 @@ public void testException() throws Exception { scf.stop(); } + private static AbstractServerConnectionFactory getDefaultServerConnectionFactory() { + AbstractServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + scf.setTaskScheduler(new SimpleAsyncTaskScheduler()); + return scf; + } + private class FailingService { @SuppressWarnings("unused") diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpSendingMessageHandlerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpSendingMessageHandlerTests.java index e30ab96a3b6..540fb191a84 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpSendingMessageHandlerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpSendingMessageHandlerTests.java @@ -73,6 +73,7 @@ import org.springframework.messaging.MessagingException; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; @@ -1203,6 +1204,7 @@ public void testConnectionException() throws Exception { public void testInterceptedConnection() throws Exception { final CountDownLatch latch = new CountDownLatch(1); AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + scf.setTaskScheduler(new SimpleAsyncTaskScheduler()); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); scf.setDeserializer(serializer); @@ -1236,6 +1238,7 @@ public void testInterceptedConnection() throws Exception { public void testInterceptedCleanup() throws Exception { final CountDownLatch latch = new CountDownLatch(1); AbstractServerConnectionFactory scf = new TcpNetServerConnectionFactory(0); + scf.setTaskScheduler(new SimpleAsyncTaskScheduler()); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); scf.setSerializer(serializer); scf.setDeserializer(serializer); @@ -1260,5 +1263,4 @@ public void testInterceptedCleanup() throws Exception { await().untilAsserted(() -> assertThat(handler.getConnections()).isEmpty()); scf.stop(); } - } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java index 8cf7b0ff3cb..30d25c5ff84 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java @@ -59,6 +59,7 @@ import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.PoolItemNotAvailableException; import org.springframework.integration.util.SimplePool; @@ -68,6 +69,7 @@ import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -96,7 +98,7 @@ @SpringJUnitConfig @DirtiesContext @LogLevels(level = "trace", categories = "org.springframework.integration") -public class CachingClientConnectionFactoryTests { +public class CachingClientConnectionFactoryTests implements TestApplicationContextAware { @Autowired SubscribableChannel outbound; @@ -698,6 +700,7 @@ public void testRealConnection() throws Exception { @Test //INT-3722 public void testGatewayRelease() { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); + in.setTaskScheduler(new SimpleAsyncTaskScheduler()); in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); final TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(in); @@ -730,6 +733,7 @@ public void testGatewayRelease() { gate.setOutputChannel(outputChannel); gate.setBeanFactory(mock(BeanFactory.class)); gate.setRemoteTimeout(20_000); + gate.setBeanFactory(TEST_INTEGRATION_CONTEXT); gate.afterPropertiesSet(); LogAccessor logger = spy(TestUtils.getPropertyValue(gate, "logger", LogAccessor.class)); new DirectFieldAccessor(gate).setPropertyValue("logger", logger); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionEventTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionEventTests.java index f7df34ab24c..62aef34ac63 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionEventTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionEventTests.java @@ -45,6 +45,7 @@ import org.springframework.integration.ip.tcp.TcpInboundGateway; import org.springframework.integration.ip.tcp.TcpOutboundGateway; import org.springframework.integration.ip.tcp.TcpSendingMessageHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -71,7 +72,7 @@ * @since 3.0 * */ -public class ConnectionEventTests { +public class ConnectionEventTests implements TestApplicationContextAware { @Test public void testConnectionEvents() throws Exception { @@ -202,6 +203,7 @@ public void publishEvent(ApplicationEvent event) { DirectChannel requestChannel = new DirectChannel(); requestChannel.subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message)); gw.setRequestChannel(requestChannel); + gw.setBeanFactory(TEST_INTEGRATION_CONTEXT); gw.start(); Message message = MessageBuilder.withPayload("foo") .setHeader(IpHeaders.CONNECTION_ID, "bar") diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionFactoryTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionFactoryTests.java index 1b7d00905f1..6bbb9178675 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionFactoryTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/ConnectionFactoryTests.java @@ -40,24 +40,23 @@ import org.mockito.ArgumentCaptor; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.log.LogAccessor; import org.springframework.core.log.LogMessage; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.NullChannel; import org.springframework.integration.channel.QueueChannel; -import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.ip.config.TcpConnectionFactoryFactoryBean; import org.springframework.integration.ip.event.IpIntegrationEvent; import org.springframework.integration.ip.tcp.TcpOutboundGateway; import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; -import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; @@ -80,11 +79,11 @@ * @since 3.0 * */ -public class ConnectionFactoryTests { +public class ConnectionFactoryTests implements TestApplicationContextAware { @Test void netOpenEventOnReadThread() throws InterruptedException, IOException { - TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); + TcpNetServerConnectionFactory server = getTcpNetServerConnectionFactory(0); AtomicReference readThread = new AtomicReference<>(); AtomicReference openEventThread = new AtomicReference<>(); CountDownLatch latch1 = new CountDownLatch(1); @@ -102,6 +101,7 @@ void netOpenEventOnReadThread() throws InterruptedException, IOException { openEventThread.set(Thread.currentThread()); } }); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.start(); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); @@ -162,10 +162,8 @@ public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactor ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(10); scheduler.afterPropertiesSet(); - BeanFactory bf = mock(BeanFactory.class); - when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true); - when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler); - serverFactory.setBeanFactory(bf); + + serverFactory.setTaskScheduler(new SimpleAsyncTaskScheduler()); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setOutputChannel(new NullChannel()); adapter.setConnectionFactory(serverFactory); @@ -225,6 +223,7 @@ public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactor @Test public void testEarlyCloseNio() throws Exception { AbstractServerConnectionFactory factory = new TcpNioServerConnectionFactory(0); + factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); testEarlyClose(factory, "serverChannel", " stopped before registering the server channel"); } @@ -273,22 +272,22 @@ private void testEarlyClose(final AbstractServerConnectionFactory factory, Strin @Test void healthCheckSuccessNet() throws InterruptedException { - healthCheckSuccess(new TcpNetServerConnectionFactory(0), false); + healthCheckSuccess(getTcpNetServerConnectionFactory(0), false); } @Test void healthCheckSuccessNio() throws InterruptedException { - healthCheckSuccess(new TcpNioServerConnectionFactory(0), false); + healthCheckSuccess(getTcpNetServerConnectionFactory(0), false); } @Test void healthCheckFailureNet() throws InterruptedException { - healthCheckSuccess(new TcpNetServerConnectionFactory(0), true); + healthCheckSuccess(getTcpNetServerConnectionFactory(0), true); } @Test void healthCheckFailureNio() throws InterruptedException { - healthCheckSuccess(new TcpNioServerConnectionFactory(0), true); + healthCheckSuccess(getTcpNetServerConnectionFactory(0), true); } private void healthCheckSuccess(AbstractServerConnectionFactory server, boolean fail) throws InterruptedException { @@ -298,7 +297,7 @@ private void healthCheckSuccess(AbstractServerConnectionFactory server, boolean serverUp.countDown(); } }); - server.setBeanFactory(mock(BeanFactory.class)); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); AtomicReference connection = new AtomicReference<>(); server.registerSender(conn -> { connection.set(conn); @@ -367,6 +366,12 @@ private void healthCheckSuccess(AbstractServerConnectionFactory server, boolean server.stop(); } + private TcpNetServerConnectionFactory getTcpNetServerConnectionFactory(int port) { + TcpNetServerConnectionFactory result = new TcpNetServerConnectionFactory(port); + result.setTaskScheduler(new SimpleAsyncTaskScheduler()); + return result; + } + @SuppressWarnings("serial") private class FooEvent extends TcpConnectionOpenEvent { diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/FailoverClientConnectionFactoryTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/FailoverClientConnectionFactoryTests.java index 85cbefb401d..85108a7c630 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/FailoverClientConnectionFactoryTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/FailoverClientConnectionFactoryTests.java @@ -48,12 +48,14 @@ import org.springframework.integration.ip.tcp.TcpInboundGateway; import org.springframework.integration.ip.tcp.TcpOutboundGateway; import org.springframework.integration.ip.util.TestingUtilities; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.SimplePool; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import static org.assertj.core.api.Assertions.assertThat; @@ -76,7 +78,7 @@ * @since 2.2 * */ -public class FailoverClientConnectionFactoryTests { +public class FailoverClientConnectionFactoryTests implements TestApplicationContextAware { @Test public void testFailoverGood() throws Exception { @@ -328,39 +330,39 @@ public TcpConnectionSupport makeMockConnection() { @Test public void testRealNet() throws Exception { - AbstractServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); - AbstractServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server1 = getTcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server2 = getTcpNetServerConnectionFactory(0); Holder holder = setupAndStartServers(server1, server2); - AbstractClientConnectionFactory client1 = new TcpNetClientConnectionFactory("localhost", server1.getPort()); - AbstractClientConnectionFactory client2 = new TcpNetClientConnectionFactory("localhost", server2.getPort()); + AbstractClientConnectionFactory client1 = getTcpNetServerConnectionFactory("localhost", server1.getPort()); + AbstractClientConnectionFactory client2 = getTcpNetServerConnectionFactory("localhost", server2.getPort()); testRealGuts(client1, client2, holder); } @Test public void testRealNio() throws Exception { - AbstractServerConnectionFactory server1 = new TcpNioServerConnectionFactory(0); - AbstractServerConnectionFactory server2 = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory server1 = getTcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server2 = getTcpNetServerConnectionFactory(0); Holder holder = setupAndStartServers(server1, server2); - AbstractClientConnectionFactory client1 = new TcpNioClientConnectionFactory("localhost", server1.getPort()); - AbstractClientConnectionFactory client2 = new TcpNioClientConnectionFactory("localhost", server2.getPort()); + AbstractClientConnectionFactory client1 = getTcpNetServerConnectionFactory("localhost", server1.getPort()); + AbstractClientConnectionFactory client2 = getTcpNetServerConnectionFactory("localhost", server2.getPort()); testRealGuts(client1, client2, holder); } @Test public void testRealNetSingleUse() throws Exception { - AbstractServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); - AbstractServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server1 = getTcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server2 = getTcpNetServerConnectionFactory(0); Holder holder = setupAndStartServers(server1, server2); - AbstractClientConnectionFactory client1 = new TcpNetClientConnectionFactory("localhost", server1.getPort()); - AbstractClientConnectionFactory client2 = new TcpNetClientConnectionFactory("localhost", server2.getPort()); + AbstractClientConnectionFactory client1 = getTcpNetServerConnectionFactory("localhost", server1.getPort()); + AbstractClientConnectionFactory client2 = getTcpNetServerConnectionFactory("localhost", server2.getPort()); client1.setSingleUse(true); client2.setSingleUse(true); testRealGuts(client1, client2, holder); @@ -369,13 +371,13 @@ public void testRealNetSingleUse() throws Exception { @Test public void testRealNioSingleUse() throws Exception { - AbstractServerConnectionFactory server1 = new TcpNioServerConnectionFactory(0); - AbstractServerConnectionFactory server2 = new TcpNioServerConnectionFactory(0); + AbstractServerConnectionFactory server1 = getTcpNetServerConnectionFactory(0); + AbstractServerConnectionFactory server2 = getTcpNetServerConnectionFactory(0); Holder holder = setupAndStartServers(server1, server2); - AbstractClientConnectionFactory client1 = new TcpNioClientConnectionFactory("localhost", server1.getPort()); - AbstractClientConnectionFactory client2 = new TcpNioClientConnectionFactory("localhost", server2.getPort()); + AbstractClientConnectionFactory client1 = getTcpNetServerConnectionFactory("localhost", server1.getPort()); + AbstractClientConnectionFactory client2 = getTcpNetServerConnectionFactory("localhost", server2.getPort()); client1.setSingleUse(true); client2.setSingleUse(true); testRealGuts(client1, client2, holder); @@ -460,12 +462,14 @@ public void testFailoverCachedRealClose() throws Exception { public void testFailoverCachedWithGateway() { final TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); server.setBeanName("server"); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); DirectChannel inChannel = new DirectChannel(); inChannel.setBeanName("inChannel"); TcpInboundGateway inbound = new TcpInboundGateway(); inbound.setConnectionFactory(server); inbound.setRequestChannel(inChannel); + inbound.setBeanFactory(TEST_INTEGRATION_CONTEXT); inbound.afterPropertiesSet(); inChannel.subscribe(new BridgeHandler()); inbound.start(); @@ -477,6 +481,7 @@ public void testFailoverCachedWithGateway() { // Cache CachingClientConnectionFactory cachingClient = new CachingClientConnectionFactory(client, 2); cachingClient.setBeanName("cache"); + cachingClient.setBeanFactory(TEST_INTEGRATION_CONTEXT); cachingClient.afterPropertiesSet(); // Failover @@ -484,6 +489,7 @@ public void testFailoverCachedWithGateway() { clientFactories.add(cachingClient); FailoverClientConnectionFactory failoverClient = new FailoverClientConnectionFactory(clientFactories); failoverClient.setSingleUse(true); + failoverClient.setBeanFactory(TEST_INTEGRATION_CONTEXT); failoverClient.afterPropertiesSet(); TcpOutboundGateway outbound = new TcpOutboundGateway(); @@ -491,7 +497,7 @@ public void testFailoverCachedWithGateway() { QueueChannel replyChannel = new QueueChannel(); replyChannel.setBeanName("replyChannel"); outbound.setReplyChannel(replyChannel); - outbound.setBeanFactory(mock(BeanFactory.class)); + outbound.setBeanFactory(TEST_INTEGRATION_CONTEXT); outbound.afterPropertiesSet(); outbound.start(); @@ -698,5 +704,19 @@ private static AbstractClientConnectionFactory createFactoryWithMockConnection(T return factory; } + private static TcpNetServerConnectionFactory getTcpNetServerConnectionFactory(int port) { + TcpNetServerConnectionFactory result = new TcpNetServerConnectionFactory(port); + result.setTaskScheduler(new SimpleAsyncTaskScheduler()); + + return result; + } + + private static TcpNetClientConnectionFactory getTcpNetServerConnectionFactory(String host, int port) { + TcpNetClientConnectionFactory result = new TcpNetClientConnectionFactory(host, port); + result.setTaskScheduler(new SimpleAsyncTaskScheduler()); + + return result; + } + } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java index 0f2575af86f..a3d14b99709 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java @@ -48,6 +48,7 @@ import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -470,6 +471,7 @@ public void postProcessServerSocket(ServerSocket serverSocket) { public void testNioClientAndServerSSL() throws Exception { System.setProperty("javax.net.debug", "all"); // SSL activity in the console TcpNioServerConnectionFactory server = new TcpNioServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); server.setSslHandshakeTimeout(43); DefaultTcpSSLContextSupport sslContextSupport = new DefaultTcpSSLContextSupport("test.ks", "test.truststore.ks", "secret", "secret"); @@ -576,6 +578,7 @@ protected void postProcessSSLEngine(SSLEngine sslEngine) { public void testNioClientAndServerSSLDifferentContextsLargeDataWithReply() throws Exception { System.setProperty("javax.net.debug", "all"); // SSL activity in the console TcpNioServerConnectionFactory server = new TcpNioServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); TcpSSLContextSupport serverSslContextSupport = new DefaultTcpSSLContextSupport("server.ks", "server.truststore.ks", "secret", "secret"); DefaultTcpNioSSLConnectionSupport serverTcpNioConnectionSupport = diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpConnectionEventListenerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpConnectionEventListenerTests.java index 2d1142bcae6..e93357e2f7a 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpConnectionEventListenerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpConnectionEventListenerTests.java @@ -17,18 +17,16 @@ package org.springframework.integration.ip.tcp.connection; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.ResolvableType; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.event.inbound.ApplicationEventListeningMessageProducer; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** @@ -37,7 +35,7 @@ * @since 3.0 * */ -public class TcpConnectionEventListenerTests { +public class TcpConnectionEventListenerTests implements TestApplicationContextAware { @Test public void testNoFilter() { @@ -45,14 +43,12 @@ public void testNoFilter() { QueueChannel outputChannel = new QueueChannel(); eventProducer.setOutputChannel(outputChannel); eventProducer.setEventTypes(TcpConnectionEvent.class); - BeanFactory mock = mock(BeanFactory.class); - given(mock.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, - ApplicationEventMulticaster.class)) - .willReturn(mock(ApplicationEventMulticaster.class)); - eventProducer.setBeanFactory(mock); + TEST_INTEGRATION_CONTEXT.registerBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, + mock(ApplicationEventMulticaster.class)); + eventProducer.setBeanFactory(TEST_INTEGRATION_CONTEXT); eventProducer.afterPropertiesSet(); eventProducer.start(); - TcpConnectionSupport connection = Mockito.mock(TcpConnectionSupport.class); + TcpConnectionSupport connection = mock(TcpConnectionSupport.class); assertThat(eventProducer.supportsEventType(ResolvableType.forClass(TcpConnectionOpenEvent.class))).isTrue(); TcpConnectionEvent event1 = new TcpConnectionOpenEvent(connection, "foo"); @@ -85,14 +81,12 @@ public void testFilter() { QueueChannel outputChannel = new QueueChannel(); eventProducer.setOutputChannel(outputChannel); eventProducer.setEventTypes(FooEvent.class, BarEvent.class); - BeanFactory mock = mock(BeanFactory.class); - given(mock.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, - ApplicationEventMulticaster.class)) - .willReturn(mock(ApplicationEventMulticaster.class)); - eventProducer.setBeanFactory(mock); + TEST_INTEGRATION_CONTEXT.registerBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, + mock(ApplicationEventMulticaster.class)); + eventProducer.setBeanFactory(TEST_INTEGRATION_CONTEXT); eventProducer.afterPropertiesSet(); eventProducer.start(); - TcpConnectionSupport connection = Mockito.mock(TcpConnectionSupport.class); + TcpConnectionSupport connection = mock(TcpConnectionSupport.class); assertThat(eventProducer.supportsEventType(ResolvableType.forClass(TcpConnectionOpenEvent.class))).isFalse(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionSupportTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionSupportTests.java index bbe520c1785..875c38f75dd 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionSupportTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionSupportTests.java @@ -27,7 +27,9 @@ import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; @@ -36,11 +38,12 @@ * @since 5.0.3 * */ -public class TcpNetConnectionSupportTests { +public class TcpNetConnectionSupportTests implements TestApplicationContextAware { @Test public void testBadCode() throws Exception { TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); AtomicReference> message = new AtomicReference<>(); CountDownLatch latch1 = new CountDownLatch(1); server.registerListener(m -> { @@ -68,6 +71,7 @@ public TcpNetConnection createNewConnection(Socket socket, boolean isServer, boo latch2.countDown(); } }); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.start(); assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); @@ -80,5 +84,4 @@ public TcpNetConnection createNewConnection(Socket socket, boolean isServer, boo assertThat(message.get()).isNotNull(); server.stop(); } - } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionTests.java index ad900907ca3..a5743d4c6e2 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNetConnectionTests.java @@ -43,9 +43,11 @@ import org.springframework.integration.ip.tcp.serializer.SoftEndOfStreamException; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.converter.MapMessageConverter; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.support.ErrorMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -61,7 +63,7 @@ * @since 2.2.2 * */ -public class TcpNetConnectionTests { +public class TcpNetConnectionTests implements TestApplicationContextAware { @Test public void testErrorLog() throws Exception { @@ -153,6 +155,7 @@ public void transferHeaders() throws Exception { @Test public void socketClosedNextRead() throws InterruptedException, IOException { TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); AtomicInteger port = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1); ApplicationEventPublisher publisher = ev -> { @@ -163,6 +166,7 @@ public void socketClosedNextRead() throws InterruptedException, IOException { }; server.setApplicationEventPublisher(publisher); server.registerListener(message -> false); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.start(); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java index a23b3bf89bc..f8f366e045e 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java @@ -38,6 +38,7 @@ import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.messaging.Message; import org.springframework.messaging.support.ErrorMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.with; @@ -62,6 +63,7 @@ private AbstractServerConnectionFactory getConnectionFactory( AbstractByteArraySerializer serializer, TcpListener listener, TcpSender sender) { TcpNioServerConnectionFactory scf = new TcpNioServerConnectionFactory(0); + scf.setTaskScheduler(new SimpleAsyncTaskScheduler()); scf.setUsingDirectBuffers(true); scf.setApplicationEventPublisher(e -> { }); @@ -119,7 +121,6 @@ public void testFragmented() throws Exception { semaphore.release(); return false; }); - int howMany = 2; scf.setBacklog(howMany + 5); // Fire up the sender. @@ -144,7 +145,6 @@ public void testReadStxEtx() throws Exception { semaphore.release(); return false; }); - // Fire up the sender. CountDownLatch done = SocketTestUtils.testSendStxEtx(scf.getPort(), latch); @@ -533,5 +533,4 @@ private void whileOpen(Semaphore semaphore, List added) .atMost(Duration.ofSeconds(20)) .until(() -> !added.get(0).isOpen()); } - } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java index 51574e287af..a64e5cb5106 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java @@ -71,11 +71,13 @@ import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.converter.MapMessageConverter; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.CompositeExecutor; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.ReflectionUtils; import org.springframework.util.StopWatch; @@ -103,7 +105,7 @@ * @since 2.0 * */ -public class TcpNioConnectionTests { +public class TcpNioConnectionTests implements TestApplicationContextAware { private static final Log logger = LogFactory.getLog(TcpNioConnectionTests.class); @@ -543,9 +545,8 @@ public Integer answer(InvocationOnMock invocation) { @Test public void testAssemblerUsesSecondaryExecutor() throws Exception { - TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0); + TcpNioServerConnectionFactory factory = newTcpNioServerConnectionFactory(); factory.setApplicationEventPublisher(nullPublisher); - CompositeExecutor compositeExec = compositeExecutor(); factory.setSoTimeout(1000); @@ -586,6 +587,12 @@ public void testAssemblerUsesSecondaryExecutor() throws Exception { cleanupCompositeExecutor(compositeExec); } + private static TcpNioServerConnectionFactory newTcpNioServerConnectionFactory() { + TcpNioServerConnectionFactory tcpNioServerConnectionFactory = new TcpNioServerConnectionFactory(0); + tcpNioServerConnectionFactory.setTaskScheduler(new SimpleAsyncTaskScheduler()); + return tcpNioServerConnectionFactory; + } + private void cleanupCompositeExecutor(CompositeExecutor compositeExec) throws Exception { TestUtils.getPropertyValue(compositeExec, "primaryTaskExecutor", DisposableBean.class).destroy(); TestUtils.getPropertyValue(compositeExec, "secondaryTaskExecutor", DisposableBean.class).destroy(); @@ -595,6 +602,7 @@ private void cleanupCompositeExecutor(CompositeExecutor compositeExec) throws Ex public void testAllMessagesDelivered() throws Exception { final int numberOfSockets = 10; TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0); + factory.setTaskScheduler(mock()); factory.setApplicationEventPublisher(nullPublisher); CompositeExecutor compositeExec = compositeExecutor(); @@ -682,6 +690,7 @@ private CompositeExecutor compositeExecutor() { @Test public void int3453RaceTest() throws Exception { TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0); + factory.setTaskScheduler(mock()); final CountDownLatch connectionLatch = new CountDownLatch(1); factory.setApplicationEventPublisher(new ApplicationEventPublisher() { @@ -768,7 +777,8 @@ public void publishEvent(Object event) { @Test public void testNoDelayOnClose() throws Exception { - TcpNioServerConnectionFactory cf = new TcpNioServerConnectionFactory(0); + TcpNioServerConnectionFactory cf = newTcpNioServerConnectionFactory(); + cf.setBeanFactory(TEST_INTEGRATION_CONTEXT); final CountDownLatch reading = new CountDownLatch(1); final StopWatch watch = new StopWatch(); cf.setDeserializer(is -> { @@ -807,7 +817,8 @@ private void testMulti(boolean multiAccept) throws InterruptedException, IOExcep CountDownLatch serverReadyLatch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(21); List sockets = new ArrayList<>(); - TcpNioServerConnectionFactory server = new TcpNioServerConnectionFactory(0); + TcpNioServerConnectionFactory server = newTcpNioServerConnectionFactory(); + try { List events = Collections.synchronizedList(new ArrayList<>()); List> messages = Collections.synchronizedList(new ArrayList<>()); @@ -824,6 +835,7 @@ private void testMulti(boolean multiAccept) throws InterruptedException, IOExcep latch.countDown(); return false; }); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.start(); assertThat(serverReadyLatch.await(10, TimeUnit.SECONDS)).isTrue(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpSenderTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpSenderTests.java index d288293db12..46988688b35 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpSenderTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpSenderTests.java @@ -27,6 +27,9 @@ import org.junit.jupiter.api.Test; +import org.springframework.integration.test.context.TestApplicationContextAware; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; + import static org.assertj.core.api.Assertions.assertThat; /** @@ -37,13 +40,15 @@ * @since 5.3.10 * */ -public class TcpSenderTests { +public class TcpSenderTests implements TestApplicationContextAware { @Test void senderCalledForDeadConnectionClientNet() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); server.registerListener(msg -> false); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.afterPropertiesSet(); server.setApplicationEventPublisher(event -> { if (event instanceof TcpConnectionServerListeningEvent) { @@ -61,6 +66,8 @@ void senderCalledForDeadConnectionClientNet() throws InterruptedException { void senderCalledForDeadConnectionClientNio() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); TcpNetServerConnectionFactory server = new TcpNetServerConnectionFactory(0); + server.setTaskScheduler(new SimpleAsyncTaskScheduler()); + server.setBeanFactory(TEST_INTEGRATION_CONTEXT); server.registerListener(msg -> false); server.afterPropertiesSet(); server.setApplicationEventPublisher(event -> { @@ -140,6 +147,7 @@ public synchronized void removeDeadConnection(TcpConnection connection) { }); client.setSingleUse(true); + client.setBeanFactory(TEST_INTEGRATION_CONTEXT); client.afterPropertiesSet(); client.start(); TcpConnectionSupport conn = client.getConnection(); @@ -160,5 +168,4 @@ public synchronized void removeDeadConnection(TcpConnection connection) { assertThat(passedConnectionsToSenderViaAddNewConnection.get(0)).isSameAs(interceptorsPerInstance.get(3)); assertThat(passedConnectionsToSenderViaAddNewConnection.get(1)).isSameAs(interceptorsPerInstance.get(6)); } - } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java index 8a0bdae3fce..a1e9623c5e8 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java @@ -30,7 +30,6 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.serializer.DefaultDeserializer; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.QueueChannel; @@ -41,15 +40,16 @@ import org.springframework.integration.ip.util.SocketTestUtils; import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatException; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.mockito.Mockito.mock; /** * @author Gary Russell @@ -58,7 +58,7 @@ * * @since 2.0 */ -public class DeserializationTests { +public class DeserializationTests implements TestApplicationContextAware { @Test public void testReadLength() throws Exception { @@ -308,20 +308,27 @@ public void testTimeoutWithRawDeserializer() { testTimeoutWhileDecoding(new ByteArrayRawSerializer(), "reply"); } + private TcpNioServerConnectionFactory getTcpNioServerConnectionFactory(int port) { + TcpNioServerConnectionFactory result = new TcpNioServerConnectionFactory(port); + result.setTaskScheduler(new SimpleAsyncTaskScheduler()); + return result; + } + private void testTimeoutWhileDecoding(AbstractByteArraySerializer deserializer, String reply) { ByteArrayRawSerializer serializer = new ByteArrayRawSerializer(); - TcpNioServerConnectionFactory serverNio = new TcpNioServerConnectionFactory(0); + TcpNioServerConnectionFactory serverNio = getTcpNioServerConnectionFactory(0); serverNio.setApplicationEventPublisher(event -> { }); ByteArrayLengthHeaderSerializer lengthHeaderSerializer = new ByteArrayLengthHeaderSerializer(1); serverNio.setDeserializer(lengthHeaderSerializer); + serverNio.setBeanFactory(TEST_INTEGRATION_CONTEXT); serverNio.setSerializer(serializer); serverNio.afterPropertiesSet(); TcpInboundGateway in = new TcpInboundGateway(); in.setConnectionFactory(serverNio); QueueChannel serverSideChannel = new QueueChannel(); in.setRequestChannel(serverSideChannel); - in.setBeanFactory(mock(BeanFactory.class)); + in.setBeanFactory(TEST_INTEGRATION_CONTEXT); in.afterPropertiesSet(); in.start(); TestingUtilities.waitListening(serverNio, null); @@ -331,13 +338,14 @@ private void testTimeoutWhileDecoding(AbstractByteArraySerializer deserializer, clientNio.setSerializer(serializer); clientNio.setDeserializer(deserializer); clientNio.setSoTimeout(500); + clientNio.setBeanFactory(TEST_INTEGRATION_CONTEXT); clientNio.afterPropertiesSet(); final TcpOutboundGateway out = new TcpOutboundGateway(); out.setConnectionFactory(clientNio); QueueChannel outputChannel = new QueueChannel(); out.setOutputChannel(outputChannel); out.setRemoteTimeout(60000); - out.setBeanFactory(mock(BeanFactory.class)); + out.setBeanFactory(TEST_INTEGRATION_CONTEXT); out.afterPropertiesSet(); out.start(); Runnable command = () -> { @@ -364,18 +372,19 @@ private void testTimeoutWhileDecoding(AbstractByteArraySerializer deserializer, @Test public void testTimeoutWithRawDeserializerEofIsTerminator() { ByteArrayRawSerializer serializer = new ByteArrayRawSerializer(); - TcpNioServerConnectionFactory serverNio = new TcpNioServerConnectionFactory(0); + TcpNioServerConnectionFactory serverNio = getTcpNioServerConnectionFactory(0); ByteArrayLengthHeaderSerializer lengthHeaderSerializer = new ByteArrayLengthHeaderSerializer(1); serverNio.setDeserializer(lengthHeaderSerializer); serverNio.setSerializer(serializer); serverNio.setApplicationEventPublisher(event -> { }); + serverNio.setBeanFactory(TEST_INTEGRATION_CONTEXT); serverNio.afterPropertiesSet(); TcpInboundGateway in = new TcpInboundGateway(); in.setConnectionFactory(serverNio); QueueChannel serverSideChannel = new QueueChannel(); in.setRequestChannel(serverSideChannel); - in.setBeanFactory(mock(BeanFactory.class)); + in.setBeanFactory(TEST_INTEGRATION_CONTEXT); in.afterPropertiesSet(); in.start(); TestingUtilities.waitListening(serverNio, null); @@ -383,6 +392,7 @@ public void testTimeoutWithRawDeserializerEofIsTerminator() { clientNio.setSerializer(serializer); clientNio.setDeserializer(new ByteArrayRawSerializer(true)); clientNio.setSoTimeout(1000); + clientNio.setBeanFactory(TEST_INTEGRATION_CONTEXT); clientNio.setApplicationEventPublisher(event -> { }); clientNio.afterPropertiesSet(); @@ -391,7 +401,7 @@ public void testTimeoutWithRawDeserializerEofIsTerminator() { QueueChannel outputChannel = new QueueChannel(); out.setOutputChannel(outputChannel); out.setRemoteTimeout(60000); - out.setBeanFactory(mock(BeanFactory.class)); + out.setBeanFactory(TEST_INTEGRATION_CONTEXT); out.afterPropertiesSet(); out.start(); Runnable command = () -> { diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java index fc59719165a..6dfa61ee6b5 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java @@ -32,14 +32,13 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.ip.IpHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -50,7 +49,7 @@ */ @Multicast @DisabledOnOs(value = OS.MAC, disabledReason = "Multicast tests don't work on MacOS") -public class DatagramPacketMulticastSendingHandlerTests { +public class DatagramPacketMulticastSendingHandlerTests implements TestApplicationContextAware { @Test public void verifySendMulticast(MulticastCondition multicastCondition) throws Exception { @@ -95,7 +94,7 @@ public void verifySendMulticast(MulticastCondition multicastCondition) throws Ex executor.execute(catcher); assertThat(listening.await(10000, TimeUnit.MILLISECONDS)).isTrue(); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); NetworkInterface nic = multicastCondition.getNic(); if (nic != null) { String hostName = null; @@ -216,7 +215,7 @@ public void verifySendMulticastWithAcks(MulticastCondition multicastCondition) t handler.setLocalAddress(hostName); } handler.setMinAcksForSuccess(2); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); waitAckListening(handler); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java index a362092b73f..1b92a30dd03 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java @@ -26,15 +26,14 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.ip.IpHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -44,7 +43,7 @@ * * @since 2.0 */ -public class DatagramPacketSendingHandlerTests { +public class DatagramPacketSendingHandlerTests implements TestApplicationContextAware { @Test public void verifySend() throws Exception { @@ -122,7 +121,7 @@ public void verifySendWithAck() throws Exception { listening.await(10000, TimeUnit.MILLISECONDS); UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort.get(), true, true, "localhost", 0, 5000); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); waitAckListening(handler); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java index bf3d80c1eb9..e0020118479 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java @@ -35,7 +35,6 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.task.SimpleAsyncTaskExecutor; @@ -46,12 +45,12 @@ import org.springframework.integration.ip.util.SocketTestUtils; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.SubscribableChannel; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @@ -64,7 +63,7 @@ */ @Multicast @LogLevels(categories = "org.springframework.integration.ip.udp", level = "TRACE") -public class UdpChannelAdapterTests { +public class UdpChannelAdapterTests implements TestApplicationContextAware { @Test public void testUnicastReceiver() throws Exception { @@ -235,7 +234,7 @@ public void testUnicastSender() { "localhost", port, false, true, "localhost", 0, 5000); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); Message message = MessageBuilder.withPayload("ABCD".getBytes()).build(); @@ -328,7 +327,7 @@ public void testUnicastReceiverException() throws Exception { UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(0); adapter.setOutputChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService()); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); channel.subscribe(handler); QueueChannel errorChannel = new QueueChannel(); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/ExpressionEvaluatingSqlParameterSourceFactoryTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/ExpressionEvaluatingSqlParameterSourceFactoryTests.java index ec9ddbbd166..759a49aadf4 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/ExpressionEvaluatingSqlParameterSourceFactoryTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/ExpressionEvaluatingSqlParameterSourceFactoryTests.java @@ -22,19 +22,18 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.support.JdbcUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Dave Syer * @author Meherzad Lahewala * @author Artem Bilan */ -class ExpressionEvaluatingSqlParameterSourceFactoryTests { +class ExpressionEvaluatingSqlParameterSourceFactoryTests implements TestApplicationContextAware { private final ExpressionEvaluatingSqlParameterSourceFactory factory = new ExpressionEvaluatingSqlParameterSourceFactory(); @@ -42,7 +41,7 @@ class ExpressionEvaluatingSqlParameterSourceFactoryTests { @Test void testSetStaticParameters() { this.factory.setStaticParameters(Collections.singletonMap("foo", "bar")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(null); assertThat(source.hasValue("foo")).isTrue(); @@ -52,7 +51,7 @@ void testSetStaticParameters() { @Test void testMapInput() { - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Collections.singletonMap("foo", "bar")); assertThat(source.hasValue("foo")).isTrue(); @@ -62,7 +61,7 @@ void testMapInput() { @Test void testListOfMapsInput() { - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Arrays.asList(Collections.singletonMap("foo", "bar"), @@ -75,7 +74,7 @@ void testListOfMapsInput() { @Test void testMapInputWithExpression() { - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Collections.singletonMap("foo", "bar")); // This is an illegal parameter name in Spring JDBC so we'd never get this as input @@ -87,7 +86,7 @@ void testMapInputWithExpression() { @Test void testMapInputWithMappedExpression() { this.factory.setParameterExpressions(Collections.singletonMap("spam", "foo.toUpperCase()")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Collections.singletonMap("foo", "bar")); assertThat(source.hasValue("spam")).isTrue(); @@ -100,7 +99,7 @@ void testMapInputWithMappedExpressionResolveStatic() { this.factory.setParameterExpressions( Collections.singletonMap("spam", "#staticParameters['foo'].toUpperCase()")); this.factory.setStaticParameters(Collections.singletonMap("foo", "bar")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Collections.singletonMap("crap", "bucket")); assertThat(source.hasValue("spam")).isTrue(); @@ -111,7 +110,7 @@ void testMapInputWithMappedExpressionResolveStatic() { @Test void testListOfMapsInputWithExpression() { this.factory.setParameterExpressions(Collections.singletonMap("spam", "foo.toUpperCase()")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Arrays.asList(Collections.singletonMap("foo", "bar"), @@ -125,8 +124,9 @@ void testListOfMapsInputWithExpression() { @Test void testListOfMapsInputWithExpressionAndTypes() { this.factory.setParameterExpressions(Collections.singletonMap("spam", "foo.toUpperCase()")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.setSqlParameterTypes(Collections.singletonMap("spam", Types.SQLXML)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(Arrays.asList(Collections.singletonMap("foo", "bar"), @@ -140,7 +140,7 @@ void testListOfMapsInputWithExpressionAndTypes() { @Test void testListOfMapsInputWithExpressionAndEmptyTypes() { this.factory.setParameterExpressions(Collections.singletonMap("spam", "foo.toUpperCase()")); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.setSqlParameterTypes(Collections.emptyMap()); this.factory.afterPropertiesSet(); SqlParameterSource source = @@ -155,7 +155,7 @@ void testListOfMapsInputWithExpressionAndEmptyTypes() { @Test void testNullValue() { this.factory.setStaticParameters(Collections.singletonMap("foo", null)); - this.factory.setBeanFactory(mock(BeanFactory.class)); + this.factory.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.factory.afterPropertiesSet(); SqlParameterSource source = this.factory.createParameterSource(null); assertThat(source.hasValue("foo")).isTrue(); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcMessageHandlerIntegrationTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcMessageHandlerIntegrationTests.java index 3d950958a8a..5826c7b37e3 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcMessageHandlerIntegrationTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcMessageHandlerIntegrationTests.java @@ -27,8 +27,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; @@ -37,13 +37,12 @@ import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Dave Syer * @author Artem Bilan */ -public class JdbcMessageHandlerIntegrationTests { +public class JdbcMessageHandlerIntegrationTests implements TestApplicationContextAware { private static EmbeddedDatabase embeddedDatabase; @@ -72,6 +71,7 @@ public void cleanup() { public void testSimpleStaticInsert() { JdbcMessageHandler handler = new JdbcMessageHandler(jdbcTemplate, "insert into foos (id, status, name) values (1, 0, 'foo')"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("foo"); handler.handleMessage(message); @@ -85,6 +85,7 @@ public void testSimpleStaticInsert() { public void testSimpleDynamicInsert() { JdbcMessageHandler handler = new JdbcMessageHandler(jdbcTemplate, "insert into foos (id, status, name) values (1, 0, :payload)"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("foo"); handler.handleMessage(message); @@ -96,6 +97,7 @@ public void testSimpleDynamicInsert() { public void testInsertBatch() { JdbcMessageHandler handler = new JdbcMessageHandler(jdbcTemplate, "insert into foos (id, status, name) values (:payload, 0, :payload)"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message> message = new GenericMessage<>(Arrays.asList("foo1", "foo2", "foo3")); @@ -117,8 +119,9 @@ public void testInsertBatchOfMessages() { ExpressionEvaluatingSqlParameterSourceFactory sqlParameterSourceFactory = new ExpressionEvaluatingSqlParameterSourceFactory(); sqlParameterSourceFactory.setParameterExpressions(Map.of("id", "headers.id", "payload", "payload")); - sqlParameterSourceFactory.setBeanFactory(mock(BeanFactory.class)); + sqlParameterSourceFactory.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setSqlParameterSourceFactory(sqlParameterSourceFactory); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List> payload = @@ -151,6 +154,7 @@ public void testInsertWithMessagePreparedStatementSetter() { ps.setObject(1, requestMessage.getPayload()); setterInvoked.set(true); }); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("foo"); handler.handleMessage(message); @@ -167,6 +171,7 @@ public void testInsertBatchWithMessagePreparedStatementSetter() { ps.setObject(1, requestMessage.getPayload()); ps.setObject(2, requestMessage.getPayload()); }); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message> message = new GenericMessage<>(Arrays.asList("foo1", "foo2", "foo3")); @@ -185,6 +190,7 @@ public void testInsertBatchWithMessagePreparedStatementSetter() { public void testIdHeaderDynamicInsert() { JdbcMessageHandler handler = new JdbcMessageHandler(jdbcTemplate, "insert into foos (id, status, name) values (:headers[idAsString], 0, :payload)"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = new GenericMessage<>("foo"); String id = message.getHeaders().getId().toString(); @@ -201,6 +207,7 @@ public void testIdHeaderDynamicInsert() { public void testDottedHeaderDynamicInsert() { JdbcMessageHandler handler = new JdbcMessageHandler(jdbcTemplate, "insert into foos (id, status, name) values (:headers[business.id], 0, :payload)"); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").setHeader("business.id", "FOO").build(); handler.handleMessage(message); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcPollingChannelAdapterIntegrationTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcPollingChannelAdapterIntegrationTests.java index 31978e30492..d6c661e34ae 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcPollingChannelAdapterIntegrationTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/JdbcPollingChannelAdapterIntegrationTests.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.SqlParameterSource; @@ -37,14 +37,13 @@ import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Jonas Partner * @author Gary Russell * @author Artem Bilan */ -public class JdbcPollingChannelAdapterIntegrationTests { +public class JdbcPollingChannelAdapterIntegrationTests implements TestApplicationContextAware { private static EmbeddedDatabase embeddedDatabase; @@ -145,7 +144,7 @@ public void testSimplePollForListWithRowMapperAndOneUpdate() throws Exception { "select * from item where status=2"); adapter.setUpdateSql("update item set status = 10 where id in (:id)"); adapter.setRowMapper(new ItemRowMapper()); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); jdbcTemplate.update("insert into item values(1,2)"); @@ -174,7 +173,7 @@ public void testSimplePollForListWithRowMapperAndUpdatePerRow() throws Exception adapter.setUpdateSql("update item set status = 10 where id = :id"); adapter.setUpdatePerRow(true); adapter.setRowMapper(new ItemRowMapper()); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); jdbcTemplate.update("insert into item values(1,2)"); @@ -204,7 +203,7 @@ public void testSimplePollForListWithRowMapperAndInsertPerRowAndMaxRows() throws adapter.setUpdatePerRow(true); adapter.setMaxRows(1); adapter.setRowMapper(new ItemRowMapper()); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); jdbcTemplate.update("insert into item values(1,2)"); @@ -234,7 +233,7 @@ public void testSimplePollForListWithRowMapperAndUpdatePerRowWithMaxRows() throw adapter.setUpdatePerRow(true); adapter.setMaxRows(1); adapter.setRowMapper(new ItemRowMapper()); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); jdbcTemplate.update("insert into item values(1,2)"); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java index 3e7c3e81d89..547de78e689 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java @@ -26,11 +26,11 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.integration.config.ExpressionFactoryBean; import org.springframework.integration.jdbc.storedproc.ProcedureParameter; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.simple.SimpleJdbcCallOperations; @@ -45,7 +45,7 @@ * @author Artem Bilan * @author Gary Russell */ -public class StoredProcExecutorTests { +public class StoredProcExecutorTests implements TestApplicationContextAware { @Test public void testStoredProcExecutorWithNullDataSource() { @@ -59,7 +59,7 @@ public void testStoredProcExecutorWithNullProcedureName() { DataSource datasource = mock(DataSource.class); StoredProcExecutor storedProcExecutor = new StoredProcExecutor(datasource); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalArgumentException() .isThrownBy(storedProcExecutor::afterPropertiesSet) .withMessage("You must either provide a " @@ -87,7 +87,7 @@ public void testGetStoredProcedureNameExpressionAsString() throws Exception { final Expression expression = efb.getObject(); storedProcExecutor.setStoredProcedureNameExpression(expression); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); assertThat(storedProcExecutor.getStoredProcedureNameExpressionAsString()) @@ -101,7 +101,7 @@ public void testGetStoredProcedureNameExpressionAsString2() { StoredProcExecutor storedProcExecutor = new StoredProcExecutor(datasource); storedProcExecutor.setStoredProcedureName("123"); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); assertThat(storedProcExecutor.getStoredProcedureName()).isEqualTo("123"); @@ -244,7 +244,7 @@ public void testStoredProcExecutorWithNonResolvingExpression() throws Exception final Expression expression = efb.getObject(); storedProcExecutor.setStoredProcedureNameExpression(expression); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcJavaConfigTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcJavaConfigTests.java index 5ff106e55e1..e72d286cf77 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcJavaConfigTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcJavaConfigTests.java @@ -39,6 +39,7 @@ import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.jdbc.storedproc.PrimeMapper; import org.springframework.integration.jdbc.storedproc.ProcedureParameter; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @@ -61,7 +62,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class StoredProcJavaConfigTests { +public class StoredProcJavaConfigTests implements TestApplicationContextAware { @Autowired private PollableChannel fooChannel; @@ -81,6 +82,7 @@ public void test() { assertThat(received).isNull(); MessagingTemplate template = new MessagingTemplate(this.control); template.convertAndSend("'storedProc.inboundChannelAdapter'.stop"); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThat(template.convertSendAndReceive( "'storedProc.inboundChannelAdapter'.isRunning", Boolean.class)) .isFalse(); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcMessageHandlerDerbyIntegrationTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcMessageHandlerDerbyIntegrationTests.java index 8418a7dc9aa..ea77f549d75 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcMessageHandlerDerbyIntegrationTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcMessageHandlerDerbyIntegrationTests.java @@ -25,12 +25,12 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.integration.config.ExpressionFactoryBean; import org.springframework.integration.jdbc.storedproc.ProcedureParameter; import org.springframework.integration.jdbc.storedproc.User; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; @@ -39,14 +39,13 @@ import org.springframework.messaging.support.GenericMessage; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Gunnar Hillert * @author Gary Russell * @author Artem Bilan */ -public class StoredProcMessageHandlerDerbyIntegrationTests { +public class StoredProcMessageHandlerDerbyIntegrationTests implements TestApplicationContextAware { private static EmbeddedDatabase embeddedDatabase; @@ -78,10 +77,10 @@ public void testDerbyStoredProcedureInsertWithDefaultSqlSource() { StoredProcMessageHandler messageHandler = new StoredProcMessageHandler(storedProcExecutor); storedProcExecutor.setStoredProcedureName("CREATE_USER"); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.afterPropertiesSet(); MessageBuilder message = MessageBuilder.withPayload(new User("username", "password", "email")); @@ -104,10 +103,10 @@ public void testDerbyStoredProcInsertWithDefaultSqlSourceAndDynamicProcName() th final Expression expression = efb.getObject(); storedProcExecutor.setStoredProcedureNameExpression(expression); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.afterPropertiesSet(); MessageBuilder message = MessageBuilder.withPayload(new User("username", "password", "email")); @@ -131,10 +130,10 @@ public void testDerbyStoredProcInsertWithDefaultSqlSourceAndSpelProcName() throw Expression expression = efb.getObject(); storedProcExecutor.setStoredProcedureNameExpression(expression); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.afterPropertiesSet(); MessageBuilder message = MessageBuilder.withPayload(new User("username", "password", "email")); @@ -161,10 +160,10 @@ public void testDerbyStoredProcedureInsertWithExpression() { procedureParameters.add(new ProcedureParameter("email", null, "payload.email.toUpperCase()")); storedProcExecutor.setProcedureParameters(procedureParameters); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.afterPropertiesSet(); Message message = new GenericMessage<>(new User("Eric.Cartman", "c4rtm4n", "eric@cartman.com")); @@ -191,10 +190,10 @@ public void testDerbyStoredProcedureInsertWithHeaderExpression() { procedureParameters.add(new ProcedureParameter("email", "static_email", null)); storedProcExecutor.setProcedureParameters(procedureParameters); - storedProcExecutor.setBeanFactory(mock(BeanFactory.class)); + storedProcExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); storedProcExecutor.afterPropertiesSet(); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.afterPropertiesSet(); Message message = diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/dsl/JdbcTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/dsl/JdbcTests.java index c135a6081a1..b23c6d3fad6 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/dsl/JdbcTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/dsl/JdbcTests.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; @@ -65,7 +66,6 @@ import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Jiandong Ma @@ -219,9 +219,9 @@ void testStoredProcOutboundGateway() throws SQLException { public static class Config { @Bean - public IntegrationFlow inboundFlow(DataSource h2DataSource) { + public IntegrationFlow inboundFlow(DataSource h2DataSource, BeanFactory beanFactory) { var sqlParameterSourceFactory = new ExpressionEvaluatingSqlParameterSourceFactory(); - sqlParameterSourceFactory.setBeanFactory(mock()); + sqlParameterSourceFactory.setBeanFactory(beanFactory); return IntegrationFlow.from(Jdbc.inboundAdapter(h2DataSource, "select * from inbound") .maxRows(2) .rowMapper((rs, rowNum) -> new Inbound(rs.getInt(1), rs.getInt(2))) diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/postgres/PostgresChannelMessageTableSubscriberTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/postgres/PostgresChannelMessageTableSubscriberTests.java index 4919a961ee7..dbc5024865b 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/postgres/PostgresChannelMessageTableSubscriberTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/postgres/PostgresChannelMessageTableSubscriberTests.java @@ -49,6 +49,7 @@ import org.springframework.integration.jdbc.channel.PostgresSubscribableChannel; import org.springframework.integration.jdbc.store.JdbcChannelMessageStore; import org.springframework.integration.jdbc.store.channel.PostgresChannelMessageStoreQueryProvider; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; @@ -75,7 +76,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class PostgresChannelMessageTableSubscriberTests implements PostgresContainerTest { +public class PostgresChannelMessageTableSubscriberTests implements PostgresContainerTest, TestApplicationContextAware { private static final String INTEGRATION_DB_SCRIPTS = """ CREATE FUNCTION INT_CHANNEL_MESSAGE_NOTIFY_FCT() @@ -130,6 +131,7 @@ void setUp(TestInfo testInfo) { new PostgresSubscribableChannel(messageStore, groupId, postgresChannelMessageTableSubscriber); this.postgresSubscribableChannel.setBeanName("testPostgresChannel"); this.postgresSubscribableChannel.setDispatcherExecutor(this.taskExecutor); + this.postgresSubscribableChannel.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.postgresSubscribableChannel.afterPropertiesSet(); } diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/JdbcMessageStoreTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/JdbcMessageStoreTests.java index 20f96c27c64..29553159dd4 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/JdbcMessageStoreTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/store/JdbcMessageStoreTests.java @@ -44,7 +44,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContextException; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.SynthesizingMethodParameter; @@ -54,6 +53,7 @@ import org.springframework.integration.history.MessageHistory; import org.springframework.integration.store.MessageGroup; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.UUIDConverter; @@ -81,7 +81,7 @@ @SpringJUnitConfig @DirtiesContext // close at the end after class @Transactional -public class JdbcMessageStoreTests { +public class JdbcMessageStoreTests implements TestApplicationContextAware { @Autowired private DataSource dataSource; @@ -561,7 +561,7 @@ public void testMessageGroupStreamNoConnectionPoolLeak() throws NoSuchMethodExce JdbcMessageStore pooledMessageStore = new JdbcMessageStore(poolingDataSource); CollectionArgumentResolver collectionArgumentResolver = new CollectionArgumentResolver(true); - collectionArgumentResolver.setBeanFactory(new DefaultListableBeanFactory()); + collectionArgumentResolver.setBeanFactory(TEST_INTEGRATION_CONTEXT); Method methodForCollectionOfPayloads = getClass().getMethod("methodForCollectionOfPayloads", Collection.class); MethodParameter methodParameter = SynthesizingMethodParameter.forExecutable(methodForCollectionOfPayloads, 0); diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsInboundGateway.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsInboundGateway.java index 83a48fbdd35..21e96928676 100644 --- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsInboundGateway.java +++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsInboundGateway.java @@ -19,6 +19,7 @@ import io.micrometer.observation.ObservationRegistry; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.integration.context.OrderlyShutdownCapable; import org.springframework.integration.gateway.MessagingGatewaySupport; @@ -147,6 +148,12 @@ public void setApplicationContext(ApplicationContext applicationContext) throws this.endpoint.setApplicationContext(applicationContext); } + @Override + public void setBeanFactory(BeanFactory beanFactory) { + super.setBeanFactory(beanFactory); + this.endpoint.setBeanFactory(beanFactory); + } + @Override protected void onInit() { this.endpoint.setComponentName(getComponentName()); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListenerTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListenerTests.java index 6cd78a3067b..63a878c7e89 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListenerTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/ChannelPublishingJmsMessageListenerTests.java @@ -22,10 +22,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.log.LogAccessor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.MessageConverter; @@ -48,7 +48,7 @@ * @author Gary Russell * @author Artem Bilan */ -public class ChannelPublishingJmsMessageListenerTests { +public class ChannelPublishingJmsMessageListenerTests implements TestApplicationContextAware { private final Session session = new StubSession("test"); @@ -61,7 +61,7 @@ public void noReplyToAndNoDefault() throws JMSException { listener.setRequestChannel(requestChannel); listener.setMessageConverter(new TestMessageConverter()); jakarta.jms.Message jmsMessage = session.createTextMessage("test"); - listener.setBeanFactory(mock(BeanFactory.class)); + listener.setBeanFactory(TEST_INTEGRATION_CONTEXT); listener.afterPropertiesSet(); assertThatExceptionOfType(InvalidDestinationException.class) .isThrownBy(() -> listener.onMessage(jmsMessage, session)); @@ -77,7 +77,6 @@ public void testBadConversion() throws Exception { listener.setRequestChannel(requestChannel); QueueChannel errorChannel = new QueueChannel(); listener.setErrorChannel(errorChannel); - listener.setBeanFactory(mock(BeanFactory.class)); listener.setMessageConverter(new TestMessageConverter() { @Override @@ -86,6 +85,7 @@ public Object fromMessage(jakarta.jms.Message message) throws MessageConversionE } }); + listener.setBeanFactory(TEST_INTEGRATION_CONTEXT); listener.afterPropertiesSet(); jakarta.jms.Message jmsMessage = session.createTextMessage("test"); listener.onMessage(jmsMessage, mock(Session.class)); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/JmsOutboundGatewayTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/JmsOutboundGatewayTests.java index 9591a76b24f..bed6e5c7486 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/JmsOutboundGatewayTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/JmsOutboundGatewayTests.java @@ -34,11 +34,11 @@ import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.expression.ValueExpression; import org.springframework.integration.jms.JmsOutboundGateway.ReplyContainerProperties; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.ErrorHandlingTaskExecutor; import org.springframework.jms.JmsException; @@ -63,7 +63,7 @@ * * @since 2.2.4 */ -public class JmsOutboundGatewayTests extends ActiveMQMultiContextTests { +public class JmsOutboundGatewayTests extends ActiveMQMultiContextTests implements TestApplicationContextAware { private final Log logger = LogFactory.getLog(this.getClass()); @@ -74,7 +74,7 @@ public void testContainerBeanNameWhenNoGatewayBeanName() { gateway.setRequestDestinationName("foo"); gateway.setUseReplyContainer(true); gateway.setReplyContainerProperties(new ReplyContainerProperties()); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); assertThat(TestUtils.getPropertyValue(gateway, "replyContainer.beanName")) .isEqualTo("JMS_OutboundGateway@" + ObjectUtils.getIdentityHexString(gateway) + @@ -165,7 +165,7 @@ public void testConnectionBreakOnReplyMessageIdCorrelation() { gateway.setReplyDestinationExpression(new ValueExpression<>(replyQ)); QueueChannel queueChannel = new QueueChannel(); gateway.setOutputChannel(queueChannel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setReceiveTimeout(60000); gateway.afterPropertiesSet(); gateway.start(); @@ -211,7 +211,7 @@ public void testConnectionBreakOnReplyCustomCorrelation() { gateway.setReplyDestinationName(replyQ); QueueChannel queueChannel = new QueueChannel(); gateway.setOutputChannel(queueChannel); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.setReceiveTimeout(60000); gateway.setCorrelationKey("JMSCorrelationID"); gateway.afterPropertiesSet(); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsDynamicDestinationTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsDynamicDestinationTests.java index fd82c9872d7..0bb799d7d6b 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsDynamicDestinationTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsDynamicDestinationTests.java @@ -23,6 +23,7 @@ import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.jms.ActiveMQMultiContextTests; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; @@ -39,7 +40,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class JmsDynamicDestinationTests extends ActiveMQMultiContextTests { +public class JmsDynamicDestinationTests extends ActiveMQMultiContextTests implements TestApplicationContextAware { @Autowired private MessageChannel channelAdapterChannel; @@ -76,6 +77,7 @@ public void gateway() throws Exception { Message message1 = MessageBuilder.withPayload("test-1").setHeader("destinationNumber", 1).build(); Message message2 = MessageBuilder.withPayload("test-2").setHeader("destinationNumber", 2).build(); MessagingTemplate template = new MessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result1 = template.sendAndReceive(gatewayChannel, message1); Message result2 = template.sendAndReceive(gatewayChannel, message2); assertThat(result1).isNotNull(); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/request_reply/StopStartTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/request_reply/StopStartTests.java index efb66996991..c0b243338b6 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/request_reply/StopStartTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/request_reply/StopStartTests.java @@ -23,6 +23,7 @@ import org.springframework.context.Lifecycle; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.jms.ActiveMQMultiContextTests; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -37,7 +38,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class StopStartTests extends ActiveMQMultiContextTests { +public class StopStartTests extends ActiveMQMultiContextTests implements TestApplicationContextAware { @Autowired @Qualifier("out") @@ -49,6 +50,7 @@ public class StopStartTests extends ActiveMQMultiContextTests { @Test public void test() { MessagingTemplate template = new MessagingTemplate(this.test); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.outGateway.start(); assertThat(template.convertSendAndReceive("foo", String.class)).isEqualTo("FOO"); this.outGateway.stop(); diff --git a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/UpdateMappingsTests.java b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/UpdateMappingsTests.java index 483876bc838..d7b28280747 100644 --- a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/UpdateMappingsTests.java +++ b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/UpdateMappingsTests.java @@ -31,6 +31,7 @@ import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; @@ -49,7 +50,7 @@ */ @SpringJUnitConfig @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class UpdateMappingsTests { +public class UpdateMappingsTests implements TestApplicationContextAware { @Autowired private MessageChannel control; @@ -78,6 +79,7 @@ public void test() { @Test public void testChangeRouterMappings() { MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); messagingTemplate.setReceiveTimeout(1000); Properties newMapping = new Properties(); newMapping.setProperty("foo", "bar"); @@ -110,6 +112,7 @@ public void testChangeRouterMappings() { @Test public void testJmx() throws Exception { MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); messagingTemplate.setReceiveTimeout(1000); Set names = this.server.queryNames(ObjectName .getInstance("update.mapping.domain:type=MessageHandler,name=router,bean=endpoint"), diff --git a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/config/ControlBusParserTests.java b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/config/ControlBusParserTests.java index 524553adcc5..6f433e5d61d 100644 --- a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/config/ControlBusParserTests.java +++ b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/config/ControlBusParserTests.java @@ -21,6 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.integration.core.MessagingTemplate; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -36,7 +37,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class ControlBusParserTests { +public class ControlBusParserTests implements TestApplicationContextAware { @Autowired private ApplicationContext context; @@ -45,6 +46,7 @@ public class ControlBusParserTests { public void testControlMessageToChannelMetrics() { MessageChannel control = this.context.getBean("controlChannel", MessageChannel.class); MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); Object value = messagingTemplate.convertSendAndReceive(control, "@cb.isRunning()", Object.class); assertThat(value).isEqualTo(Boolean.TRUE); } diff --git a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/HibernateJpaOperationsTests.java b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/HibernateJpaOperationsTests.java index 54925c39028..bc110536f92 100644 --- a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/HibernateJpaOperationsTests.java +++ b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/HibernateJpaOperationsTests.java @@ -25,7 +25,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.jpa.support.parametersource.ExpressionEvaluatingParameterSourceFactory; import org.springframework.integration.jpa.support.parametersource.ParameterSource; @@ -33,6 +32,7 @@ import org.springframework.integration.jpa.test.JpaTestUtils; import org.springframework.integration.jpa.test.entity.Gender; import org.springframework.integration.jpa.test.entity.StudentDomain; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.TransactionDefinition; @@ -41,7 +41,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; /** * @author Gunnar Hillert @@ -53,7 +52,7 @@ @SpringJUnitConfig @DirtiesContext @Transactional -public class HibernateJpaOperationsTests { +public class HibernateJpaOperationsTests implements TestApplicationContextAware { @Autowired protected EntityManager entityManager; @@ -87,7 +86,7 @@ public void testExecuteUpdate() { assertThat(students.size() == 3).isTrue(); ParameterSourceFactory requestParameterSourceFactory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); int updatedRecords = jpaOperations.executeUpdate("update Student s " + @@ -106,7 +105,7 @@ public void testExecuteUpdateWithNamedQuery() { final StudentDomain student = JpaTestUtils.getTestStudent(); ParameterSourceFactory requestParameterSourceFactory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); int updatedRecords = jpaOperations.executeUpdateWithNamedQuery("updateStudent", source); @@ -122,7 +121,7 @@ public void testExecuteUpdateWithNativeQuery() { final StudentDomain student = JpaTestUtils.getTestStudent(); ExpressionEvaluatingParameterSourceFactory requestParameterSourceFactory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); int updatedRecords = jpaOperations.executeUpdateWithNativeQuery("update Student " + @@ -179,7 +178,7 @@ public void testExecuteUpdateWithNativeNamedQuery() { final StudentDomain student = JpaTestUtils.getTestStudent(); ParameterSourceFactory requestParameterSourceFactory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); int updatedRecords = jpaOperations.executeUpdateWithNamedQuery("updateStudentNativeQuery", source); diff --git a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/JpaExecutorTests.java b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/JpaExecutorTests.java index 8c54c5fa433..116e07b13c2 100644 --- a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/JpaExecutorTests.java +++ b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/JpaExecutorTests.java @@ -31,6 +31,7 @@ import org.springframework.integration.jpa.support.parametersource.ParameterSourceFactory; import org.springframework.integration.jpa.test.entity.StudentDomain; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.test.annotation.DirtiesContext; @@ -52,13 +53,12 @@ */ @SpringJUnitConfig @DirtiesContext -public class JpaExecutorTests { +public class JpaExecutorTests implements TestApplicationContextAware { @Autowired protected EntityManager entityManager; - @Autowired - private BeanFactory beanFactory; + private BeanFactory beanFactory = TEST_INTEGRATION_CONTEXT; /** * In this test, the {@link JpaExecutor}'s poll method will be called without @@ -68,7 +68,7 @@ public class JpaExecutorTests { @Test public void testExecutePollWithNoEntityClassSpecified() { JpaExecutor jpaExecutor = new JpaExecutor(mock(EntityManager.class)); - jpaExecutor.setBeanFactory(mock(BeanFactory.class)); + jpaExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); jpaExecutor.afterPropertiesSet(); assertThatIllegalStateException() @@ -161,14 +161,14 @@ public void updateWithPayloadAsParameterSource() { private JpaExecutor getJpaExecutorForMessageAsParamSource(String query) { JpaExecutor executor = new JpaExecutor(entityManager); ExpressionEvaluatingParameterSourceFactory factory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); factory.setParameters( Collections.singletonList(new JpaParameter("firstName", null, "payload['firstName']"))); executor.setParameterSourceFactory(factory); executor.setJpaQuery(query); executor.setExpectSingleResult(true); executor.setUsePayloadAsParameterSource(false); - executor.setBeanFactory(mock(BeanFactory.class)); + executor.setBeanFactory(TEST_INTEGRATION_CONTEXT); executor.afterPropertiesSet(); return executor; } @@ -176,14 +176,14 @@ private JpaExecutor getJpaExecutorForMessageAsParamSource(String query) { private JpaExecutor getJpaExecutorForPayloadAsParamSource(String query) { JpaExecutor executor = new JpaExecutor(entityManager); ExpressionEvaluatingParameterSourceFactory factory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); factory.setParameters( Collections.singletonList(new JpaParameter("firstName", null, "#this"))); executor.setParameterSourceFactory(factory); executor.setJpaQuery(query); executor.setExpectSingleResult(true); executor.setUsePayloadAsParameterSource(true); - executor.setBeanFactory(mock(BeanFactory.class)); + executor.setBeanFactory(TEST_INTEGRATION_CONTEXT); executor.afterPropertiesSet(); return executor; } diff --git a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/outbound/JpaOutboundChannelAdapterTests.java b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/outbound/JpaOutboundChannelAdapterTests.java index ff3a5c24603..d29b7fc97ea 100644 --- a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/outbound/JpaOutboundChannelAdapterTests.java +++ b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/outbound/JpaOutboundChannelAdapterTests.java @@ -22,13 +22,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.jpa.core.JpaExecutor; import org.springframework.integration.jpa.support.PersistMode; import org.springframework.integration.jpa.test.JpaTestUtils; import org.springframework.integration.jpa.test.entity.StudentDomain; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -40,7 +40,6 @@ import org.springframework.transaction.support.TransactionTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @@ -53,7 +52,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class JpaOutboundChannelAdapterTests { +public class JpaOutboundChannelAdapterTests implements TestApplicationContextAware { @Autowired private EntityManager entityManager; @@ -80,7 +79,7 @@ public void saveEntityWithMerge() { JpaExecutor jpaExecutor = new JpaExecutor(entityManager); jpaExecutor.setEntityClass(StudentDomain.class); - jpaExecutor.setBeanFactory(mock(BeanFactory.class)); + jpaExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); jpaExecutor.afterPropertiesSet(); final JpaOutboundGateway jpaOutboundChannelAdapter = new JpaOutboundGateway(jpaExecutor); @@ -112,7 +111,7 @@ public void saveEntityWithMergeWithoutSpecifyingEntityClass() { assertThat(results1.size() == 3).isTrue(); JpaExecutor jpaExecutor = new JpaExecutor(entityManager); - jpaExecutor.setBeanFactory(mock(BeanFactory.class)); + jpaExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); jpaExecutor.afterPropertiesSet(); final JpaOutboundGateway jpaOutboundChannelAdapter = new JpaOutboundGateway(jpaExecutor); @@ -146,7 +145,7 @@ public void saveEntityWithPersist() { JpaExecutor jpaExecutor = new JpaExecutor(entityManager); jpaExecutor.setEntityClass(StudentDomain.class); jpaExecutor.setPersistMode(PersistMode.PERSIST); - jpaExecutor.setBeanFactory(mock(BeanFactory.class)); + jpaExecutor.setBeanFactory(TEST_INTEGRATION_CONTEXT); jpaExecutor.afterPropertiesSet(); final JpaOutboundGateway jpaOutboundChannelAdapter = new JpaOutboundGateway(jpaExecutor); @@ -158,7 +157,7 @@ public void saveEntityWithPersist() { final Message message = MessageBuilder.withPayload(testStudent).build(); - jpaOutboundChannelAdapter.setBeanFactory(mock(BeanFactory.class)); + jpaOutboundChannelAdapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); jpaOutboundChannelAdapter.afterPropertiesSet(); TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager); diff --git a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/support/parametersource/ExpressionEvaluatingParameterSourceFactoryTests.java b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/support/parametersource/ExpressionEvaluatingParameterSourceFactoryTests.java index de782af43a0..a92031efd48 100644 --- a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/support/parametersource/ExpressionEvaluatingParameterSourceFactoryTests.java +++ b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/support/parametersource/ExpressionEvaluatingParameterSourceFactoryTests.java @@ -23,11 +23,10 @@ import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.jpa.support.JpaParameter; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @@ -37,10 +36,10 @@ * @since 2.2 * */ -public class ExpressionEvaluatingParameterSourceFactoryTests { +public class ExpressionEvaluatingParameterSourceFactoryTests implements TestApplicationContextAware { private final ExpressionEvaluatingParameterSourceFactory factory = - new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); + new ExpressionEvaluatingParameterSourceFactory(TEST_INTEGRATION_CONTEXT); @Test public void testSetStaticParameters() { diff --git a/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/PollableKafkaChannel.java b/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/PollableKafkaChannel.java index 4a139061589..009f36c18cb 100644 --- a/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/PollableKafkaChannel.java +++ b/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/PollableKafkaChannel.java @@ -19,6 +19,7 @@ import java.util.ArrayDeque; import java.util.Deque; import java.util.List; +import java.util.Objects; import org.jspecify.annotations.Nullable; @@ -67,7 +68,7 @@ protected void onInit() { super.onInit(); if (this.source.getConsumerProperties().getGroupId() == null) { String groupId = getGroupId(); - this.source.getConsumerProperties().setGroupId(groupId != null ? groupId : getBeanName()); + this.source.getConsumerProperties().setGroupId(groupId != null ? groupId : Objects.requireNonNull(getBeanName())); } } diff --git a/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/SubscribableKafkaChannel.java b/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/SubscribableKafkaChannel.java index 39401d5db07..3ae2c616cdf 100644 --- a/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/SubscribableKafkaChannel.java +++ b/spring-integration-kafka/src/main/java/org/springframework/integration/kafka/channel/SubscribableKafkaChannel.java @@ -16,6 +16,8 @@ package org.springframework.integration.kafka.channel; +import java.util.Objects; + import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.jspecify.annotations.Nullable; @@ -139,7 +141,7 @@ protected void onInit() { this.container = this.factory.createContainer(this.topic); String groupId = getGroupId(); ContainerProperties containerProperties = this.container.getContainerProperties(); - containerProperties.setGroupId(groupId != null ? groupId : getBeanName()); + containerProperties.setGroupId(groupId != null ? groupId : Objects.requireNonNull(getBeanName())); containerProperties.setMessageListener(this.recordListener); } diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/channnel/ChannelTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/channnel/ChannelTests.java index 3f1f7643675..2114ffa5462 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/channnel/ChannelTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/channnel/ChannelTests.java @@ -28,6 +28,8 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.MapAccessor; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.NullChannel; import org.springframework.integration.history.MessageHistory; import org.springframework.integration.kafka.channel.PollableKafkaChannel; @@ -122,12 +124,12 @@ public static class Config { String embeddedKafkaBrokers; @Bean - public ProducerFactory pf() { + ProducerFactory pf() { return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(this.embeddedKafkaBrokers)); } @Bean - public ConsumerFactory cf() { + ConsumerFactory cf() { Map consumerProps = KafkaTestUtils.consumerProps(this.embeddedKafkaBrokers, "channelTests", false); consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); @@ -135,12 +137,12 @@ public ConsumerFactory cf() { } @Bean - public KafkaTemplate template(ProducerFactory pf) { + KafkaTemplate template(ProducerFactory pf) { return new KafkaTemplate<>(pf); } @Bean - public ConcurrentKafkaListenerContainerFactory factory(ConsumerFactory cf) { + ConcurrentKafkaListenerContainerFactory factory(ConsumerFactory cf) { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(cf); @@ -148,7 +150,7 @@ public ConcurrentKafkaListenerContainerFactory factory(Consumer } @Bean - public SubscribableKafkaChannel ptp(KafkaTemplate template, + SubscribableKafkaChannel ptp(KafkaTemplate template, KafkaListenerContainerFactory factory) { SubscribableKafkaChannel channel = new SubscribableKafkaChannel(template, factory, "channel.1"); @@ -157,7 +159,7 @@ public SubscribableKafkaChannel ptp(KafkaTemplate template, } @Bean - public SubscribableKafkaChannel pubSub(KafkaTemplate template, + SubscribableKafkaChannel pubSub(KafkaTemplate template, KafkaListenerContainerFactory factory) { SubscribableKafkaChannel channel = new PublishSubscribeKafkaChannel(template, factory, "channel.2"); @@ -166,15 +168,21 @@ public SubscribableKafkaChannel pubSub(KafkaTemplate template, } @Bean - public KafkaMessageSource source(ConsumerFactory cf) { + KafkaMessageSource source(ConsumerFactory cf) { return new KafkaMessageSource<>(cf, new ConsumerProperties("channel.3")); } @Bean - public PollableKafkaChannel pollable(KafkaTemplate template, KafkaMessageSource source) { + PollableKafkaChannel pollable(KafkaTemplate template, KafkaMessageSource source) { return new PollableKafkaChannel(template, source); } + @Bean + StandardEvaluationContext integrationEvaluationContext() { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + return integrationEvaluationContext; + } } } diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaMessageDrivenChannelAdapterParserTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaMessageDrivenChannelAdapterParserTests.java index 81ed7e88927..0accee33e8b 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaMessageDrivenChannelAdapterParserTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaMessageDrivenChannelAdapterParserTests.java @@ -28,6 +28,7 @@ import org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter; import org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.ListenerMode; import org.springframework.integration.support.ErrorMessageStrategy; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ContainerProperties; @@ -50,7 +51,7 @@ */ @SpringJUnitConfig @DirtiesContext -class KafkaMessageDrivenChannelAdapterParserTests { +class KafkaMessageDrivenChannelAdapterParserTests implements TestApplicationContextAware { @Autowired private ApplicationContext context; @@ -131,6 +132,7 @@ void testKafkaMessageDrivenChannelAdapterOptions() { adapter.setOutputChannel(new QueueChannel()); adapter.setRecordFilterStrategy(mock(RecordFilterStrategy.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); containerProps = TestUtils.getPropertyValue(container, "containerProperties", ContainerProperties.class); diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaOutboundAdapterParserTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaOutboundAdapterParserTests.java index 51b6d7ca6bc..5c72520ff86 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaOutboundAdapterParserTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/config/xml/KafkaOutboundAdapterParserTests.java @@ -30,12 +30,12 @@ import org.apache.kafka.test.MockPartitioner; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.MessageTimeoutException; import org.springframework.integration.kafka.outbound.KafkaProducerMessageHandler; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.kafka.KafkaException; import org.springframework.kafka.core.KafkaTemplate; @@ -61,7 +61,7 @@ */ @SpringJUnitConfig @DirtiesContext -class KafkaOutboundAdapterParserTests { +class KafkaOutboundAdapterParserTests implements TestApplicationContextAware { @Autowired private ApplicationContext appContext; @@ -119,7 +119,7 @@ public void close(Duration timeout) { given(pf.getConfigurationProperties()).willReturn(props); KafkaTemplate template = new KafkaTemplate<>(pf); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.setSync(true); diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageDrivenAdapterTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageDrivenAdapterTests.java index 35809ea4af4..d45fe88d2c2 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageDrivenAdapterTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageDrivenAdapterTests.java @@ -52,6 +52,7 @@ import org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.ListenerMode; import org.springframework.integration.kafka.support.RawRecordHeaderErrorMessageStrategy; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.core.DefaultKafkaProducerFactory; @@ -110,7 +111,7 @@ * @since 5.4 * */ -class MessageDrivenAdapterTests { +class MessageDrivenAdapterTests implements TestApplicationContextAware { static final String topic1 = "testTopic1"; @@ -142,6 +143,7 @@ void testInboundRecord() { KafkaMessageDrivenChannelAdapter adapter = new KafkaMessageDrivenChannelAdapter<>(container); QueueChannel out = new QueueChannel(); adapter.setOutputChannel(out); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.setRecordMessageConverter(new MessagingMessageConverter() { @@ -248,6 +250,7 @@ protected boolean doSend(Message message, long timeout) { adapter.setRecoveryCallback( new ErrorMessageSendingRecoverer(errorChannel, new RawRecordHeaderErrorMessageStrategy())); adapter.setRetryTemplate(retryTemplate); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); ContainerTestUtils.waitForAssignment(container, 1); @@ -321,7 +324,7 @@ public void onError(RetryContext context, RetryCallback } }); adapter.setRetryTemplate(retryTemplate); - + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); ContainerTestUtils.waitForAssignment(container, 1); @@ -363,6 +366,7 @@ protected boolean doSend(Message message, long timeout) { adapter.setRecoveryCallback( new ErrorMessageSendingRecoverer(errorChannel, new RawRecordHeaderErrorMessageStrategy())); adapter.setBindSourceRecord(true); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); ContainerTestUtils.waitForAssignment(container, 1); @@ -411,8 +415,9 @@ void testInboundBatch() throws Exception { final CountDownLatch onPartitionsAssignedCalledLatch = new CountDownLatch(1); adapter.setOnPartitionsAssignedSeekCallback((map, consumer) -> onPartitionsAssignedCalledLatch.countDown()); - + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.setBatchMessageConverter(new BatchMessagingMessageConverter() { @Override @@ -496,6 +501,7 @@ void testInboundJson() { adapter.setRecordMessageConverter(new StringJsonMessageConverter()); QueueChannel out = new QueueChannel(); adapter.setOutputChannel(out); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); ContainerTestUtils.waitForAssignment(container, 1); @@ -543,6 +549,7 @@ void testInboundJsonWithPayload() { .getObject(); QueueChannel out = new QueueChannel(); adapter.setOutputChannel(out); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); ContainerTestUtils.waitForAssignment(container, 1); @@ -616,6 +623,7 @@ void testPauseResume() throws Exception { KafkaMessageDrivenChannelAdapter adapter = new KafkaMessageDrivenChannelAdapter(container); QueueChannel outputChannel = new QueueChannel(); adapter.setOutputChannel(outputChannel); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); assertThat(commitLatch.await(10, TimeUnit.SECONDS)).isTrue(); diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageSourceIntegrationTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageSourceIntegrationTests.java index 4f86a4a3102..c0fe67e2c6f 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageSourceIntegrationTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/inbound/MessageSourceIntegrationTests.java @@ -30,6 +30,7 @@ import org.springframework.integration.channel.NullChannel; import org.springframework.integration.history.MessageHistory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; @@ -44,7 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.mock; /** * @author Gary Russell @@ -54,7 +54,7 @@ * @since 5.4 * */ -class MessageSourceIntegrationTests { +class MessageSourceIntegrationTests implements TestApplicationContextAware { static final String TOPIC1 = "MessageSourceIntegrationTests1"; @@ -151,7 +151,7 @@ void deserializationErrorIsThrownFromSource() { KafkaMessageSource source = new KafkaMessageSource<>(consumerFactory, consumerProperties); source.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); - source.setBeanFactory(mock()); + source.setBeanFactory(TEST_INTEGRATION_CONTEXT); source.afterPropertiesSet(); source.start(); diff --git a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/outbound/KafkaProducerMessageHandlerTests.java b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/outbound/KafkaProducerMessageHandlerTests.java index 89a4bd4e2aa..3aa7e3f41ad 100644 --- a/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/outbound/KafkaProducerMessageHandlerTests.java +++ b/spring-integration-kafka/src/test/java/org/springframework/integration/kafka/outbound/KafkaProducerMessageHandlerTests.java @@ -49,7 +49,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.channel.DirectChannel; @@ -61,6 +60,7 @@ import org.springframework.integration.kafka.support.KafkaIntegrationHeaders; import org.springframework.integration.kafka.support.KafkaSendFailureException; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.kafka.KafkaException; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; @@ -119,7 +119,7 @@ * * @since 5.4 */ -class KafkaProducerMessageHandlerTests { +class KafkaProducerMessageHandlerTests implements TestApplicationContextAware { private static final String topic1 = "testTopic1out"; @@ -161,7 +161,7 @@ void testOutbound() { DefaultKafkaProducerFactory producerFactory = new DefaultKafkaProducerFactory<>(producerProps); KafkaTemplate template = new KafkaTemplate<>(producerFactory); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setSendTimeout(50_000); handler.setSync(true); handler.afterPropertiesSet(); @@ -219,7 +219,7 @@ void testOutboundWithTimestamp() { KafkaTestUtils.producerProps(embeddedKafka)); KafkaTemplate template = new KafkaTemplate<>(producerFactory); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo") @@ -250,7 +250,7 @@ void testOutboundWithTimestampExpression() { KafkaTestUtils.producerProps(embeddedKafka)); KafkaTemplate template = new KafkaTemplate<>(producerFactory); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo") @@ -289,7 +289,7 @@ void testOutboundWithAsyncResults() { KafkaTestUtils.producerProps(embeddedKafka)); KafkaTemplate template = new KafkaTemplate<>(producerFactory); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); PollableChannel successes = new QueueChannel(); handler.setSendSuccessChannel(successes); handler.afterPropertiesSet(); @@ -327,7 +327,7 @@ protected CompletableFuture> doSend( }); PollableChannel failures = new QueueChannel(); handler.setSendFailureChannel(failures); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); message = MessageBuilder.withPayload("bar") .setHeader(KafkaHeaders.TOPIC, "foo") @@ -380,7 +380,7 @@ void testOutboundWithCustomHeaderMapper() { KafkaTestUtils.producerProps(embeddedKafka)); KafkaTemplate template = new KafkaTemplate<>(producerFactory); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setHeaderMapper(new DefaultKafkaHeaderMapper("!*")); handler.afterPropertiesSet(); @@ -434,7 +434,7 @@ public void onPartitionsAssigned(Collection partitions) { template.start(); assertThat(assigned.await(30, TimeUnit.SECONDS)).isTrue(); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler<>(template); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); QueueChannel replies = new QueueChannel(); handler.setOutputChannel(replies); handler.afterPropertiesSet(); @@ -485,7 +485,7 @@ void testTransaction() { KafkaTemplate template = new KafkaTemplate(pf); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); handler.handleMessage(new GenericMessage<>("foo")); @@ -547,6 +547,7 @@ void testConsumeAndProduceTransaction() throws Exception { handler.setMessageKeyExpression(new LiteralExpression("bar")); handler.setTopicExpression(new LiteralExpression("topic")); channel.subscribe(handler); + inbound.setBeanFactory(TEST_INTEGRATION_CONTEXT); inbound.afterPropertiesSet(); inbound.start(); assertThat(closeLatch.await(10, TimeUnit.SECONDS)).isTrue(); @@ -589,7 +590,7 @@ protected Producer createTransactionalProducer(String txIdPrefix) { template.setTransactionIdPrefix("overridden.tx.id."); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); handler.handleMessage(new GenericMessage<>("foo")); @@ -612,7 +613,7 @@ void testTransactionSynch() { KafkaTemplate template = new KafkaTemplate(pf); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); try { @@ -692,6 +693,7 @@ protected Producer createTransactionalProducer(String txIdPrefix) { handler.setMessageKeyExpression(new LiteralExpression("bar")); handler.setTopicExpression(new LiteralExpression("topic")); channel.subscribe(handler); + inbound.setBeanFactory(TEST_INTEGRATION_CONTEXT); inbound.afterPropertiesSet(); inbound.start(); assertThat(closeLatch.await(10, TimeUnit.SECONDS)).isTrue(); @@ -739,7 +741,7 @@ void testFlush() { KafkaTemplate template = new KafkaTemplate(pf); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); handler.handleMessage( @@ -762,7 +764,7 @@ void testNoFlush() { KafkaTemplate template = new KafkaTemplate(pf); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); handler.handleMessage(new GenericMessage<>("foo")); @@ -786,7 +788,7 @@ void conversion() { template.setMessageConverter(converter); KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(template); handler.setTopicExpression(new LiteralExpression("bar")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); ProducerRecordCreator creator = mock(ProducerRecordCreator.class); ProducerRecord recordFromCreator = mock(ProducerRecord.class); given(creator.create(any(), any(), any(), any(), any(), any(), any())).willReturn(recordFromCreator); diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java index 223a967efd6..a60af9f0a36 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java @@ -79,10 +79,12 @@ import org.springframework.integration.history.MessageHistory; import org.springframework.integration.mail.support.DefaultMailHeaderMapper; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.PollableChannel; import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -93,6 +95,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willDoNothing; @@ -122,7 +125,7 @@ "com.icegreen.greenmail", "jakarta.mail" }) -public class ImapMailReceiverTests { +public class ImapMailReceiverTests implements TestApplicationContextAware { private static final ImapSearchLoggingHandler imapSearches = new ImapSearchLoggingHandler(); @@ -170,6 +173,7 @@ void stopImapServer() { public void testIdleWithServerCustomSearch() throws Exception { ImapMailReceiver receiver = new ImapMailReceiver("imap://user:pw@localhost:" + imapIdleServer.getImap().getPort() + "/INBOX"); + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); receiver.setSearchTermStrategy((supportedFlags, folder) -> { try { FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz")); @@ -186,6 +190,7 @@ public void testIdleWithServerCustomSearch() throws Exception { public void testIdleWithServerDefaultSearch() throws Exception { ImapMailReceiver receiver = new ImapMailReceiver("imap://user:pw@localhost:" + imapIdleServer.getImap().getPort() + "/INBOX"); + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); testIdleWithServerGuts(receiver, false); assertThat(imapSearches.searches.get(0)).contains("testSIUserFlag"); } @@ -213,6 +218,7 @@ public void testIdleWithMessageMappingSimple() throws Exception { ImapMailReceiver receiver = new ImapMailReceiver("imap://user:pw@localhost:" + imapIdleServer.getImap().getPort() + "/INBOX"); receiver.setSimpleContent(true); + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); receiver.setHeaderMapper(new DefaultMailHeaderMapper()); testIdleWithServerGuts(receiver, true, true); } @@ -228,11 +234,13 @@ public void testIdleWithServerGuts(ImapMailReceiver receiver, boolean mapped, bo ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); setUpScheduler(receiver, taskScheduler); receiver.setUserFlag("testSIUserFlag"); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); adapter.setReconnectDelay(10); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); MimeMessage message = @@ -311,7 +319,7 @@ private AbstractMailReceiver receiveAndMarkAsReadDontDeleteGuts(AbstractMailRece ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(true); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); folderField.setAccessible(true); @@ -419,7 +427,7 @@ public void receiveMarkAsReadAndDelete() throws Exception { ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(true); receiver.setShouldDeleteMessages(true); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -457,7 +465,7 @@ public void receiveAndDontMarkAsRead() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(false); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -487,7 +495,7 @@ public void receiveAndDontMarkAsReadButDelete() throws Exception { receiver.setShouldDeleteMessages(true); ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(false); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -525,7 +533,7 @@ public void receiveAndDontMarkAsReadButDelete() throws Exception { public void receiveAndIgnoreMarkAsReadDontDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -563,7 +571,7 @@ public void testMessageHistory() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); @@ -619,7 +627,7 @@ protected Object handleRequestMessage(org.springframework.messaging.Message r adapter.setReconnectDelay(10); AbstractMailReceiver receiver = new ImapMailReceiver(); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -675,7 +683,7 @@ public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception { given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); - + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); @@ -744,7 +752,7 @@ public void testInitialIdleDelayWhenRecentIsSupported() throws Exception { given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); - + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); @@ -786,6 +794,7 @@ public void testConnectionException() throws Exception { latch.countDown(); }); adapter.setReconnectDelay(10); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); @@ -810,7 +819,7 @@ public void testImapLifecycleForRaceCondition() throws Exception { DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); new Thread(() -> { @@ -890,7 +899,7 @@ private Folder testAttachmentsGuts(final ImapMailReceiver receiver) throws Messa given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); df.setPropertyValue("store", store); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); return folder; @@ -946,7 +955,7 @@ public Message[] receive() throws MessagingException { @Test public void testIdleReconnects() throws Exception { ImapMailReceiver receiver = spy(new ImapMailReceiver("imap:foo")); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); @@ -971,6 +980,7 @@ public void testIdleReconnects() throws Exception { adapter.setReconnectDelay(10); CountDownLatch latch = new CountDownLatch(3); adapter.setApplicationEventPublisher(e -> latch.countDown()); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); adapter.start(); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); @@ -982,7 +992,7 @@ public void testIdleReconnects() throws Exception { private void setUpScheduler(ImapMailReceiver mailReceiver, ThreadPoolTaskScheduler taskScheduler) { taskScheduler.setPoolSize(5); taskScheduler.initialize(); - BeanFactory bf = mock(BeanFactory.class); + BeanFactory bf = getBeanFactory(taskScheduler); given(bf.containsBean("taskScheduler")).willReturn(true); given(bf.getBean("taskScheduler", TaskScheduler.class)).willReturn(taskScheduler); mailReceiver.setBeanFactory(bf); @@ -1013,6 +1023,14 @@ public void receiveAndMarkAsReadDontDeleteWithThrowingWhenCopying() throws Excep verify(receiver, times(0)).deleteMessages(Mockito.any()); } + private BeanFactory getBeanFactory(TaskScheduler taskScheduler) { + BeanFactory beanFactory = mock(BeanFactory.class); + when(beanFactory.getBean(eq("taskScheduler"), any(Class.class))) + .thenReturn(taskScheduler); + when(beanFactory.containsBean("taskScheduler")).thenReturn(true); + return beanFactory; + } + private static class ImapSearchLoggingHandler extends Handler { private final List searches = new ArrayList<>(); diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailSearchTermsTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailSearchTermsTests.java index 679c0e95617..6ffe3d7ce61 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailSearchTermsTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailSearchTermsTests.java @@ -29,7 +29,8 @@ import jakarta.mail.search.SearchTerm; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; +import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -42,7 +43,7 @@ * @author Artem Bilan * */ -public class ImapMailSearchTermsTests { +public class ImapMailSearchTermsTests implements TestApplicationContextAware { @Test public void validateSearchTermsWhenShouldMarkAsReadNoExistingFlags() throws Exception { @@ -62,7 +63,7 @@ public void validateSearchTermsWhenShouldMarkAsReadNoExistingFlagsCustom() throw public void validateSearchTermsWhenShouldMarkAsReadNoExistingFlagsGuts(String userFlag, ImapMailReceiver receiver) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException { receiver.setShouldMarkMessagesAsRead(true); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); folderField.setAccessible(true); @@ -85,8 +86,8 @@ public void validateSearchTermsWhenShouldMarkAsReadNoExistingFlagsGuts(String us public void validateSearchTermsWhenShouldMarkAsReadWithExistingFlags() throws Exception { ImapMailReceiver receiver = new ImapMailReceiver(); receiver.setShouldMarkMessagesAsRead(true); - receiver.setBeanFactory(mock(BeanFactory.class)); - + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); folderField.setAccessible(true); @@ -115,7 +116,8 @@ public void validateSearchTermsWhenShouldMarkAsReadWithExistingFlags() throws Ex public void validateSearchTermsWhenShouldNotMarkAsReadNoExistingFlags() throws Exception { ImapMailReceiver receiver = new ImapMailReceiver(); receiver.setShouldMarkMessagesAsRead(false); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setTaskScheduler(new SimpleAsyncTaskScheduler()); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java index baa63b5a6a4..a95dd4f0a55 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; @@ -40,14 +40,14 @@ * @author Artem Bilan * */ -public class Pop3MailReceiverTests { +public class Pop3MailReceiverTests implements TestApplicationContextAware { @Test public void receiveAndDelete() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); receiver.setShouldDeleteMessages(true); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -83,7 +83,7 @@ public void receiveAndDontDelete() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); receiver.setShouldDeleteMessages(false); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -111,7 +111,7 @@ public void receiveAndDontDelete() throws Exception { public void receiveAndDontSetDeleteWithUrl() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver("pop3://some.host"); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); @@ -139,7 +139,7 @@ public void receiveAndDontSetDeleteWithUrl() throws Exception { public void receiveAndDontSetDeleteWithoutUrl() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); receiver = spy(receiver); - receiver.setBeanFactory(mock(BeanFactory.class)); + receiver.setBeanFactory(TEST_INTEGRATION_CONTEXT); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MailHeaderEnricherTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MailHeaderEnricherTests.java index 77d4b2d0dac..baa0ebf656e 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MailHeaderEnricherTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/config/MailHeaderEnricherTests.java @@ -24,6 +24,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.mail.MailHeaders; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; @@ -38,7 +39,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class MailHeaderEnricherTests { +public class MailHeaderEnricherTests implements TestApplicationContextAware { @Autowired @Qualifier("literalValuesInput") @@ -52,6 +53,7 @@ public class MailHeaderEnricherTests { public void literalValues() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.literalValuesInput); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = template.sendAndReceive(new GenericMessage<>("test")); Map headers = result.getHeaders(); assertThat(headers.get(MailHeaders.TO)).isEqualTo("test.to"); @@ -68,6 +70,7 @@ public void literalValues() { public void expressions() { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.expressionsInput); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); Message result = template.sendAndReceive(new GenericMessage<>("foo")); Map headers = result.getHeaders(); assertThat(headers.get(MailHeaders.TO)).isEqualTo("foo.to"); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/MongoDbMessageSourceTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/MongoDbMessageSourceTests.java index 7dd9d57e6c8..0e4fcb0093b 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/MongoDbMessageSourceTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/MongoDbMessageSourceTests.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; @@ -35,6 +34,7 @@ import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.mongodb.MongoDbContainerTest; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -54,7 +54,7 @@ * @since 2.2 * */ -class MongoDbMessageSourceTests implements MongoDbContainerTest { +class MongoDbMessageSourceTests implements MongoDbContainerTest, TestApplicationContextAware { static MongoDatabaseFactory MONGO_DATABASE_FACTORY; @@ -90,7 +90,7 @@ void validateSuccessfulQueryWithSingleElementIfOneInListAsDbObject() { Expression queryExpression = new LiteralExpression("{'name' : 'Oleg'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); @SuppressWarnings("unchecked") List results = ((List) messageSource.receive().getPayload()); @@ -110,7 +110,7 @@ void validateSuccessfulQueryWithSingleElementIfOneInList() { Expression queryExpression = new LiteralExpression("{'name' : 'Oleg'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); messageSource.setEntityClass(Object.class); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); @SuppressWarnings("unchecked") List results = ((List) messageSource.receive().getPayload()); @@ -131,7 +131,7 @@ void validateSuccessfulQueryWithSingleElementIfOneInListAndSingleResult() { MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); messageSource.setEntityClass(Object.class); messageSource.setExpectSingleResult(true); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); Person person = (Person) messageSource.receive().getPayload(); @@ -149,7 +149,7 @@ void validateSuccessfulSubObjectQueryWithSingleElementIfOneInList() { Expression queryExpression = new LiteralExpression("{'address.state' : 'PA'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); messageSource.setEntityClass(Object.class); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); @SuppressWarnings("unchecked") List results = ((List) messageSource.receive().getPayload()); @@ -188,7 +188,7 @@ private List queryMultipleElements(Expression queryExpression) { template.save(MongoDbContainerTest.createPerson("Jack"), "data"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); return (List) messageSource.receive().getPayload(); @@ -206,7 +206,7 @@ void validateSuccessfulQueryWithNullReturn() { Expression queryExpression = new LiteralExpression("{'address.state' : 'NJ'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); assertThat(messageSource.receive()).isNull(); } @@ -225,7 +225,7 @@ void validateSuccessfulQueryWithCustomConverter() { Expression queryExpression = new LiteralExpression("{'address.state' : 'PA'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); MappingMongoConverter converter = new TestMongoConverter(MONGO_DATABASE_FACTORY, new MongoMappingContext()); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); converter.afterPropertiesSet(); converter = spy(converter); messageSource.setMongoConverter(converter); @@ -247,7 +247,7 @@ void validateSuccessfulQueryWithMongoTemplateAndUpdate() { MongoTemplate template = new MongoTemplate(MONGO_DATABASE_FACTORY, converter); Expression queryExpression = new LiteralExpression("{'address.state' : 'PA'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(template, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.setUpdateExpression(new LiteralExpression("{ $set: {'address.state' : 'NJ'} }")); messageSource.afterPropertiesSet(); @@ -278,7 +278,7 @@ void validatePipelineInModifyOut() { Expression queryExpression = new LiteralExpression("{'name' : 'Manny'}"); MongoDbMessageSource messageSource = new MongoDbMessageSource(MONGO_DATABASE_FACTORY, queryExpression); messageSource.setExpectSingleResult(true); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); BasicDBObject result = (BasicDBObject) messageSource.receive().getPayload(); Object id = result.get("_id"); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/ReactiveMongoDbMessageSourceTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/ReactiveMongoDbMessageSourceTests.java index 254061db0af..7bb9d551f1f 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/ReactiveMongoDbMessageSourceTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/inbound/ReactiveMongoDbMessageSourceTests.java @@ -32,7 +32,6 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -51,6 +50,7 @@ import org.springframework.integration.dsl.Pollers; import org.springframework.integration.mongodb.MongoDbContainerTest; import org.springframework.integration.mongodb.dsl.MongoDb; +import org.springframework.integration.test.context.TestApplicationContextAware; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -66,7 +66,7 @@ * * @since 5.3 */ -class ReactiveMongoDbMessageSourceTests implements MongoDbContainerTest { +class ReactiveMongoDbMessageSourceTests implements MongoDbContainerTest, TestApplicationContextAware { static ReactiveMongoDatabaseFactory REACTIVE_MONGO_DATABASE_FACTORY; @@ -107,7 +107,7 @@ void validateSuccessfulQueryWithSingleElementFluxOfDbObject() { Expression queryExpression = new LiteralExpression("{'name' : 'Oleg'}"); ReactiveMongoDbMessageSource messageSource = new ReactiveMongoDbMessageSource(REACTIVE_MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); StepVerifier.create((Flux) messageSource.receive().getPayload()) @@ -127,7 +127,7 @@ void validateSuccessfulQueryWithSingleElementFluxOfPerson() { Expression queryExpression = new LiteralExpression("{'name' : 'Oleg'}"); ReactiveMongoDbMessageSource messageSource = new ReactiveMongoDbMessageSource(REACTIVE_MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); messageSource.setEntityClass(Person.class); @@ -208,7 +208,7 @@ void validatePipelineInModifyOut() { ReactiveMongoDbMessageSource messageSource = new ReactiveMongoDbMessageSource(REACTIVE_MONGO_DATABASE_FACTORY, queryExpression); messageSource.setExpectSingleResult(true); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); BasicDBObject result = waitFor((Mono) messageSource.receive().getPayload()); Object id = result.get("_id"); @@ -233,9 +233,10 @@ private Flux queryMultipleElements(Expression queryExpression, Optional< ReactiveMongoDbMessageSource messageSource = new ReactiveMongoDbMessageSource(REACTIVE_MONGO_DATABASE_FACTORY, queryExpression); - messageSource.setBeanFactory(mock(BeanFactory.class)); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.setEntityClass(Person.class); converter.ifPresent(messageSource::setMongoConverter); + messageSource.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageSource.afterPropertiesSet(); return (Flux) messageSource.receive().getPayload(); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbOutboundGatewayTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbOutboundGatewayTests.java index f606c17e836..d188fd813d8 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbOutboundGatewayTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbOutboundGatewayTests.java @@ -39,6 +39,7 @@ import org.springframework.integration.expression.FunctionExpression; import org.springframework.integration.mongodb.MongoDbContainerTest; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.test.annotation.DirtiesContext; @@ -58,7 +59,7 @@ */ @SpringJUnitConfig @DirtiesContext -class MongoDbOutboundGatewayTests implements MongoDbContainerTest { +class MongoDbOutboundGatewayTests implements MongoDbContainerTest, TestApplicationContextAware { private static final String COLLECTION_NAME = "data"; @@ -131,6 +132,7 @@ void testListOfResultsWithQueryExpressionAndLimit() { MongoDbOutboundGateway gateway = createGateway(); gateway.setQueryExpression( PARSER.parseExpression("new BasicQuery('{''address.state'' : ''PA''}').limit(2)")); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -149,6 +151,7 @@ void testListOfResultsWithQueryFunction() { gateway.setQueryExpression(functionExpression); gateway.setExpectSingleResult(true); gateway.setEntityClass(Person.class); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -178,6 +181,7 @@ void testListOfResultsWithQueryExpression() { MongoDbOutboundGateway gateway = createGateway(); gateway.setEntityClass(Person.class); gateway.setQueryExpression(PARSER.parseExpression("payload")); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -192,6 +196,7 @@ void testListOfResultsWithQueryExpressionReturningOneResult() { MongoDbOutboundGateway gateway = createGateway(); gateway.setEntityClass(Person.class); gateway.setQueryExpression(PARSER.parseExpression("payload")); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -208,6 +213,7 @@ void testSingleResultWithQueryExpressionAsString() { gateway.setQueryExpression(PARSER.parseExpression("payload")); gateway.setExpectSingleResult(true); gateway.setEntityClass(Person.class); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -223,6 +229,7 @@ void testSingleResultWithQueryExpressionAsQuery() { gateway.setQueryExpression(PARSER.parseExpression("new BasicQuery('{''name'' : ''Gary''}')")); gateway.setExpectSingleResult(true); gateway.setEntityClass(Person.class); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -237,6 +244,7 @@ void testSingleResultWithQueryExpressionAndNoEntityClass() { MongoDbOutboundGateway gateway = createGateway(); gateway.setQueryExpression(new LiteralExpression("{name : 'Xavi'}")); gateway.setExpectSingleResult(true); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -268,6 +276,7 @@ void testWithCollectionNameExpressionSpecified() { gateway.setQueryExpression(new LiteralExpression("{name : 'Xavi'}")); gateway.setExpectSingleResult(true); gateway.setCollectionNameExpression(new LiteralExpression("anotherCollection")); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); Object result = gateway.handleRequestMessage(message); @@ -287,6 +296,7 @@ void testWithCollectionCallbackCount() { gateway.setCollectionNameExpression(new LiteralExpression("data")); gateway.setMessageCollectionCallback((collection, requestMessage) -> collection.countDocuments()); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); long result = (long) gateway.handleRequestMessage(message); @@ -306,6 +316,7 @@ void testWithCollectionCallbackFindOne() { collection.insertOne(new Document("name", requestMessage.getPayload())); return null; }); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); gateway.handleRequestMessage(message); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbStoringMessageHandlerTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbStoringMessageHandlerTests.java index 639e23c00fd..a8deb485296 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbStoringMessageHandlerTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/MongoDbStoringMessageHandlerTests.java @@ -22,7 +22,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; @@ -33,11 +32,11 @@ import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.mongodb.MongoDbContainerTest; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -50,7 +49,7 @@ * * @since 2.2 */ -class MongoDbStoringMessageHandlerTests implements MongoDbContainerTest { +class MongoDbStoringMessageHandlerTests implements MongoDbContainerTest, TestApplicationContextAware { static MongoDatabaseFactory MONGO_DATABASE_FACTORY; @@ -82,7 +81,7 @@ void withNullMongoTemplate() { void validateMessageHandlingWithDefaultCollection() { MongoDbStoringMessageHandler handler = new MongoDbStoringMessageHandler(MONGO_DATABASE_FACTORY); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); handler.handleMessage(message); @@ -99,7 +98,7 @@ void validateMessageHandlingWithNamedCollection() { MongoDbStoringMessageHandler handler = new MongoDbStoringMessageHandler(MONGO_DATABASE_FACTORY); handler.setCollectionNameExpression(new LiteralExpression("foo")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); handler.handleMessage(message); @@ -120,7 +119,7 @@ void validateMessageHandlingWithMongoConverter() { converter.afterPropertiesSet(); converter = spy(converter); handler.setMongoConverter(converter); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); handler.handleMessage(message); @@ -142,7 +141,7 @@ void validateMessageHandlingWithMongoTemplate() { MongoDbStoringMessageHandler handler = new MongoDbStoringMessageHandler(writingTemplate); handler.setCollectionNameExpression(new LiteralExpression("foo")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); handler.handleMessage(message); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/ReactiveMongoDbStoringMessageHandlerTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/ReactiveMongoDbStoringMessageHandlerTests.java index 85c41357fda..8d3600d30d8 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/ReactiveMongoDbStoringMessageHandlerTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/outbound/ReactiveMongoDbStoringMessageHandlerTests.java @@ -25,7 +25,6 @@ import org.mockito.Answers; import reactor.core.publisher.Mono; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory; @@ -38,6 +37,7 @@ import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.mongodb.MongoDbContainerTest; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; @@ -61,7 +61,7 @@ */ @SpringJUnitConfig @DirtiesContext -class ReactiveMongoDbStoringMessageHandlerTests implements MongoDbContainerTest { +class ReactiveMongoDbStoringMessageHandlerTests implements MongoDbContainerTest, TestApplicationContextAware { public static ReactiveMongoDatabaseFactory REACTIVE_MONGO_DATABASE_FACTORY; @@ -96,7 +96,7 @@ void withNullMongoTemplate() { @Test void validateMessageHandlingWithDefaultCollection() { ReactiveMongoDbStoringMessageHandler handler = new ReactiveMongoDbStoringMessageHandler(REACTIVE_MONGO_DATABASE_FACTORY); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); @@ -113,7 +113,7 @@ void validateMessageHandlingWithDefaultCollection() { void validateMessageHandlingWithNamedCollection() { ReactiveMongoDbStoringMessageHandler handler = new ReactiveMongoDbStoringMessageHandler(REACTIVE_MONGO_DATABASE_FACTORY); handler.setCollectionNameExpression(new LiteralExpression("foo")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); @@ -133,7 +133,7 @@ void errorOnMessageHandlingWithNullValuedExpression() { ReactiveMongoDbStoringMessageHandler handler = new ReactiveMongoDbStoringMessageHandler(REACTIVE_MONGO_DATABASE_FACTORY); handler.setCollectionNameExpression(new LiteralExpression(null)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); @@ -153,7 +153,7 @@ void validateMessageHandlingWithMongoConverter() { converter.afterPropertiesSet(); converter = spy(converter); handler.setMongoConverter(converter); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); @@ -175,7 +175,7 @@ void validateMessageHandlingWithMongoTemplate() { ReactiveMongoTemplate writingTemplate = new ReactiveMongoTemplate(REACTIVE_MONGO_DATABASE_FACTORY, converter); ReactiveMongoDbStoringMessageHandler handler = new ReactiveMongoDbStoringMessageHandler(writingTemplate); handler.setCollectionNameExpression(new LiteralExpression("foo")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); Message message = MessageBuilder.withPayload(MongoDbContainerTest.createPerson("Bob")).build(); diff --git a/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttAdapterTests.java b/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttAdapterTests.java index 791355ec4c0..0f3caf231b4 100644 --- a/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttAdapterTests.java +++ b/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttAdapterTests.java @@ -43,12 +43,15 @@ import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; +import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; import org.springframework.core.log.LogAccessor; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.StaticMessageHeaderAccessor; import org.springframework.integration.channel.NullChannel; import org.springframework.integration.channel.QueueChannel; @@ -65,6 +68,7 @@ import org.springframework.integration.mqtt.support.MqttHeaderAccessor; import org.springframework.integration.mqtt.support.MqttMessageConverter; import org.springframework.integration.support.AbstractIntegrationMessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; @@ -100,7 +104,7 @@ * @since 4.0 * */ -public class MqttAdapterTests { +public class MqttAdapterTests implements TestApplicationContextAware { private final IMqttToken alwaysComplete; @@ -152,7 +156,7 @@ public void testOutboundOptionsApplied() throws Exception { MqttPahoMessageHandler handler = new MqttPahoMessageHandler("foo", "bar", factory); handler.setDefaultTopic("mqtt-foo"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); @@ -208,7 +212,7 @@ void testClientManagerIsNotConnectedAndClosedInHandler() throws Exception { var handler = new MqttPahoMessageHandler(clientManager); handler.setDefaultTopic("mqtt-foo"); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.start(); @@ -238,7 +242,7 @@ void testClientManagerIsNotConnectedAndClosedInAdapter() throws Exception { .willReturn(subscribeToken); var adapter = new MqttPahoMessageDrivenChannelAdapter(clientManager, "mqtt-foo"); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); // when @@ -311,7 +315,7 @@ public void testInboundOptionsApplied() throws Exception { adapter.setOutputChannel(outputChannel); QueueChannel errorChannel = new QueueChannel(); adapter.setErrorChannel(errorChannel); - adapter.setBeanFactory(mock(BeanFactory.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class); final BlockingQueue events = new LinkedBlockingQueue<>(); willAnswer(invocation -> { @@ -399,6 +403,7 @@ public void testCustomExpressions() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); MqttPahoMessageHandler handler = ctx.getBean("handler", MqttPahoMessageHandler.class); GenericMessage message = new GenericMessage<>("foo"); + handler.setApplicationContext(ctx); assertThat(TestUtils.getPropertyValue(handler, "topicProcessor", MessageProcessor.class) .processMessage(message)).isEqualTo("fooTopic"); assertThat(TestUtils.getPropertyValue(handler, "converter.qosProcessor", MessageProcessor.class) @@ -555,6 +560,7 @@ public IMqttAsyncClient getAsyncClientInstance(String uri, String clientId) { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("client", factory, "foo"); adapter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); adapter.setOutputChannel(new NullChannel()); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); return adapter; } @@ -574,6 +580,7 @@ public IMqttAsyncClient getAsyncClientInstance(String uri, String clientId) { MqttPahoMessageHandler adapter = new MqttPahoMessageHandler("client", factory); adapter.setDefaultTopic("foo"); adapter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); + adapter.setBeanFactory(TEST_INTEGRATION_CONTEXT); adapter.afterPropertiesSet(); return adapter; } @@ -629,6 +636,14 @@ public MqttPahoMessageHandler handlerWithNullExpressions() { return handler; } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } + } } diff --git a/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttDslTests.java b/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttDslTests.java index 6a578f6c7ec..f5add0389a6 100644 --- a/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttDslTests.java +++ b/spring-integration-mqtt/src/test/java/org/springframework/integration/mqtt/MqttDslTests.java @@ -37,6 +37,7 @@ import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.jmx.support.MBeanServerFactoryBean; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -53,7 +54,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class MqttDslTests implements MosquittoContainerTest { +public class MqttDslTests implements MosquittoContainerTest, TestApplicationContextAware { @Autowired @Qualifier("mqttOutFlow.input") diff --git a/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/inbound/R2dbcMessageSourceTests.java b/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/inbound/R2dbcMessageSourceTests.java index 3db126d16c7..46dc12bd1d2 100644 --- a/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/inbound/R2dbcMessageSourceTests.java +++ b/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/inbound/R2dbcMessageSourceTests.java @@ -27,11 +27,15 @@ import reactor.test.StepVerifier; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; import org.springframework.data.r2dbc.dialect.H2Dialect; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.expression.ValueExpression; import org.springframework.integration.r2dbc.config.R2dbcDatabaseConfiguration; import org.springframework.integration.r2dbc.entity.Person; @@ -314,6 +318,14 @@ public R2dbcMessageSource r2dbcMessageSourceError() { return r2dbcMessageSource; } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } + } } diff --git a/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/outbound/R2dbcMessageHandlerTests.java b/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/outbound/R2dbcMessageHandlerTests.java index 4d531e082f0..463bafd682f 100644 --- a/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/outbound/R2dbcMessageHandlerTests.java +++ b/spring-integration-r2dbc/src/test/java/org/springframework/integration/r2dbc/outbound/R2dbcMessageHandlerTests.java @@ -30,11 +30,15 @@ import reactor.test.StepVerifier; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; import org.springframework.data.r2dbc.core.R2dbcEntityTemplate; import org.springframework.data.relational.core.query.Criteria; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.expression.FunctionExpression; import org.springframework.integration.r2dbc.config.R2dbcDatabaseConfiguration; import org.springframework.integration.r2dbc.entity.Person; @@ -297,6 +301,14 @@ public R2dbcMessageHandler r2dbcMessageHandler(R2dbcEntityTemplate r2dbcEntityTe return new R2dbcMessageHandler(r2dbcEntityTemplate); } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } + } } diff --git a/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/ReactiveRedisStreamMessageProducerTests.java b/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/ReactiveRedisStreamMessageProducerTests.java index 581cc1b5119..af207f24e61 100644 --- a/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/ReactiveRedisStreamMessageProducerTests.java +++ b/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/ReactiveRedisStreamMessageProducerTests.java @@ -29,14 +29,18 @@ import reactor.test.StepVerifier; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.connection.stream.PendingMessagesSummary; import org.springframework.data.redis.connection.stream.ReadOffset; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.stream.StreamReceiver; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.StaticMessageHeaderAccessor; import org.springframework.integration.acks.SimpleAcknowledgment; @@ -359,6 +363,14 @@ ReactiveRedisStreamMessageProducer reactiveRedisStreamProducer( return messageProducer; } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } + } } diff --git a/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/ReactiveRedisStreamMessageHandlerTests.java b/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/ReactiveRedisStreamMessageHandlerTests.java index 1432e938e91..93be83f3678 100644 --- a/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/ReactiveRedisStreamMessageHandlerTests.java +++ b/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/ReactiveRedisStreamMessageHandlerTests.java @@ -24,13 +24,17 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.connection.stream.ObjectRecord; import org.springframework.data.redis.connection.stream.StreamOffset; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.handler.ReactiveMessageHandlerAdapter; import org.springframework.integration.redis.RedisContainerTest; @@ -158,6 +162,14 @@ public ReactiveMessageHandlerAdapter reactiveMessageHandlerAdapter( return new ReactiveMessageHandlerAdapter(streamMessageHandler); } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } + } } diff --git a/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/RedisStoreWritingMessageHandlerTests.java b/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/RedisStoreWritingMessageHandlerTests.java index 193684bd65e..165f1369e9d 100644 --- a/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/RedisStoreWritingMessageHandlerTests.java +++ b/spring-integration-redis/src/test/java/org/springframework/integration/redis/outbound/RedisStoreWritingMessageHandlerTests.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; @@ -41,6 +40,7 @@ import org.springframework.integration.redis.RedisContainerTest; import org.springframework.integration.redis.support.RedisHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.support.GenericMessage; @@ -48,7 +48,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Oleg Zhurakousky @@ -58,7 +57,7 @@ * @author Artem Bilan * @author Artem Vozhdayenko */ -class RedisStoreWritingMessageHandlerTests implements RedisContainerTest { +class RedisStoreWritingMessageHandlerTests implements RedisContainerTest, TestApplicationContextAware { private static RedisConnectionFactory redisConnectionFactory; @@ -79,7 +78,7 @@ void testListWithListPayloadParsedAndProvidedKey() { RedisStoreWritingMessageHandler handler = new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -108,7 +107,7 @@ void testListWithListPayloadParsedAndProvidedKeyAsHeader() { RedisStoreWritingMessageHandler handler = new RedisStoreWritingMessageHandler(redisConnectionFactory); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -136,7 +135,7 @@ void testListWithListPayloadParsedAndNoKey() { RedisStoreWritingMessageHandler handler = new RedisStoreWritingMessageHandler(redisConnectionFactory); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -162,7 +161,7 @@ void testListWithListPayloadAsSingleEntry() { new RedisStoreWritingMessageHandler(template); handler.setKey(key); handler.setExtractPayloadElements(false); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -193,7 +192,7 @@ void testZsetWithListPayloadParsedAndProvidedKeyDefault() { new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -234,7 +233,7 @@ void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrement() { new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -276,7 +275,7 @@ void testZsetWithListPayloadParsedAndProvidedKeyScoreIncrementAsStringHeader() { new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -320,7 +319,7 @@ void testZsetWithListPayloadAsSingleEntryAndHeaderKeyHeaderScore() { handler.setCollectionType(CollectionType.ZSET); handler.setExtractPayloadElements(false); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); List list = new ArrayList<>(); @@ -352,7 +351,7 @@ void testZsetWithMapPayloadParsedHeaderKey() { new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Map presidents = new HashMap<>(); @@ -396,7 +395,7 @@ void testZsetWithMapPayloadPojoParsedHeaderKey() { new RedisStoreWritingMessageHandler(template); handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Map presidents = new HashMap<>(); @@ -441,7 +440,7 @@ void testZsetWithMapPayloadPojoAsSingleEntryHeaderKey() { handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); handler.setExtractPayloadElements(false); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); Map presidents = new HashMap<>(); @@ -464,7 +463,7 @@ void testListWithMapKeyExpression() { new RedisStoreWritingMessageHandler(redisConnectionFactory); handler.setKey(key); handler.setMapKeyExpression(new LiteralExpression(key)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class); } @@ -476,7 +475,7 @@ void testSetWithMapKeyExpression() { handler.setKey(key); handler.setCollectionType(CollectionType.SET); handler.setMapKeyExpression(new LiteralExpression(key)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class); } @@ -488,7 +487,7 @@ void testZsetWithMapKeyExpression() { handler.setKey(key); handler.setCollectionType(CollectionType.ZSET); handler.setMapKeyExpression(new LiteralExpression(key)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatThrownBy(handler::afterPropertiesSet).isInstanceOf(IllegalStateException.class); } @@ -501,7 +500,7 @@ void testMapWithMapKeyExpression() { handler.setKey(key); handler.setCollectionType(CollectionType.MAP); handler.setMapKeyExpression(new LiteralExpression(key)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { handler.afterPropertiesSet(); } @@ -520,7 +519,7 @@ void testPropertiesWithMapKeyExpression() { handler.setKey(key); handler.setCollectionType(CollectionType.PROPERTIES); handler.setMapKeyExpression(new LiteralExpression(key)); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); try { handler.afterPropertiesSet(); } diff --git a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpInboundRemoteFileSystemSynchronizerTests.java b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpInboundRemoteFileSystemSynchronizerTests.java index fc69d411ac6..552901d1d57 100644 --- a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpInboundRemoteFileSystemSynchronizerTests.java +++ b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpInboundRemoteFileSystemSynchronizerTests.java @@ -32,7 +32,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.file.FileHeaders; import org.springframework.integration.file.filters.AcceptOnceFileListFilter; import org.springframework.integration.file.filters.CompositeFileListFilter; @@ -44,6 +43,7 @@ import org.springframework.integration.sftp.session.DefaultSftpSessionFactory; import org.springframework.integration.sftp.session.SftpSession; import org.springframework.integration.sftp.session.SftpTestSessionFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; @@ -65,7 +65,7 @@ * * @since 2.0 */ -public class SftpInboundRemoteFileSystemSynchronizerTests { +public class SftpInboundRemoteFileSystemSynchronizerTests implements TestApplicationContextAware { @BeforeEach @AfterEach @@ -104,13 +104,13 @@ public void testCopyFileToLocalDir() throws Exception { filters.add(patternFilter); CompositeFileListFilter filter = new CompositeFileListFilter<>(filters); synchronizer.setFilter(filter); - synchronizer.setBeanFactory(mock(BeanFactory.class)); + synchronizer.setBeanFactory(TEST_INTEGRATION_CONTEXT); synchronizer.afterPropertiesSet(); SftpInboundFileSynchronizingMessageSource ms = new SftpInboundFileSynchronizingMessageSource(synchronizer); ms.setAutoCreateLocalDirectory(true); ms.setLocalDirectory(localDirectory); - ms.setBeanFactory(mock(BeanFactory.class)); + ms.setBeanFactory(TEST_INTEGRATION_CONTEXT); CompositeFileListFilter localFileListFilter = new CompositeFileListFilter<>(); localFileListFilter.addFilter(new RegexPatternFileListFilter(".*\\.test$")); AcceptOnceFileListFilter localAcceptOnceFilter = new AcceptOnceFileListFilter<>(); diff --git a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpMessageSourceTests.java b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpMessageSourceTests.java index 634beefdd66..dc2d8eeadd7 100644 --- a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpMessageSourceTests.java +++ b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/inbound/SftpMessageSourceTests.java @@ -23,6 +23,9 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.context.expression.MapAccessor; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.integration.file.FileHeaders; import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.sftp.SftpTestSupport; @@ -80,6 +83,13 @@ public SessionFactory ftpSessionFactory() { return SftpMessageSourceTests.sessionFactory(); } + @Bean + public StandardEvaluationContext integrationEvaluationContext(ApplicationContext applicationContext) { + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + integrationEvaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext)); + return integrationEvaluationContext; + } } } diff --git a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/outbound/SftpOutboundTests.java b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/outbound/SftpOutboundTests.java index 391f407ced5..6a23b3a4bb0 100644 --- a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/outbound/SftpOutboundTests.java +++ b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/outbound/SftpOutboundTests.java @@ -40,7 +40,6 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.file.DefaultFileNameGenerator; @@ -52,6 +51,7 @@ import org.springframework.integration.sftp.session.SftpSession; import org.springframework.integration.sftp.session.SftpTestSessionFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -78,7 +78,7 @@ * @author Artem Bilan * @author Darryl Smith */ -public class SftpOutboundTests { +public class SftpOutboundTests implements TestApplicationContextAware { @Test public void testHandleFileMessage() throws Exception { @@ -90,10 +90,10 @@ public void testHandleFileMessage() throws Exception { new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression(targetDir.getName())); DefaultFileNameGenerator fGenerator = new DefaultFileNameGenerator(); - fGenerator.setBeanFactory(mock(BeanFactory.class)); + fGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); fGenerator.setExpression("payload.name + '.test'"); handler.setFileNameGenerator(fGenerator); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); File srcFile = File.createTempFile("testHandleFileMessage", ".tmp", new File(".")); @@ -118,11 +118,11 @@ public void testHandleStringMessage() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); DefaultFileNameGenerator fGenerator = new DefaultFileNameGenerator(); - fGenerator.setBeanFactory(mock(BeanFactory.class)); + fGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); fGenerator.setExpression("'foo.txt'"); handler.setFileNameGenerator(fGenerator); handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("String data")); @@ -144,11 +144,11 @@ public void testHandleBytesMessage() throws Exception { FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); DefaultFileNameGenerator fGenerator = new DefaultFileNameGenerator(); - fGenerator.setBeanFactory(mock(BeanFactory.class)); + fGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); fGenerator.setExpression("'foo.txt'"); handler.setFileNameGenerator(fGenerator); handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("byte[] data".getBytes())); @@ -216,7 +216,7 @@ public void testMkDir() throws Exception { new FileTransferringMessageHandler<>(sessionFactory); handler.setAutoCreateDirectory(true); handler.setRemoteDirectoryExpression(new LiteralExpression("/foo/bar/baz")); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); final List madeDirs = new ArrayList<>(); doAnswer(invocation -> { diff --git a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/session/SftpRemoteFileTemplateTests.java b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/session/SftpRemoteFileTemplateTests.java index ff61ad370c9..4c2bcabc213 100644 --- a/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/session/SftpRemoteFileTemplateTests.java +++ b/spring-integration-sftp/src/test/java/org/springframework/integration/sftp/session/SftpRemoteFileTemplateTests.java @@ -25,7 +25,6 @@ import org.apache.sshd.sftp.common.SftpException; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -39,6 +38,7 @@ import org.springframework.integration.file.support.FileExistsMode; import org.springframework.integration.sftp.SftpTestSupport; import org.springframework.integration.test.condition.LogLevels; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessagingException; @@ -49,7 +49,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.mockito.Mockito.mock; /** * @author Gary Russell @@ -59,7 +58,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class SftpRemoteFileTemplateTests extends SftpTestSupport { +public class SftpRemoteFileTemplateTests extends SftpTestSupport implements TestApplicationContextAware { @Autowired private CachingSessionFactory sessionFactory; @@ -70,11 +69,11 @@ public void testINT3412AppendStatRmdir() { SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory); DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); fileNameGenerator.setExpression("'foobar.txt'"); - fileNameGenerator.setBeanFactory(mock(BeanFactory.class)); + fileNameGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setFileNameGenerator(fileNameGenerator); template.setRemoteDirectoryExpression(new LiteralExpression("/foo/")); template.setUseTemporaryFileName(false); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.afterPropertiesSet(); template.execute(session -> { @@ -112,11 +111,11 @@ public void testNoDeadLockOnSend() { CachingSessionFactory sessionFactory = new CachingSessionFactory<>(sessionFactory(), 1); SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("")); - template.setBeanFactory(mock(BeanFactory.class)); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setUseTemporaryFileName(false); DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); fileNameGenerator.setExpression("'test.file'"); - fileNameGenerator.setBeanFactory(mock(BeanFactory.class)); + fileNameGenerator.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setFileNameGenerator(fileNameGenerator); template.afterPropertiesSet(); diff --git a/spring-integration-smb/src/test/java/org/springframework/integration/smb/outbound/SmbSendingMessageHandlerTests.java b/spring-integration-smb/src/test/java/org/springframework/integration/smb/outbound/SmbSendingMessageHandlerTests.java index 2fc07a2ea5c..b69f43ebc44 100644 --- a/spring-integration-smb/src/test/java/org/springframework/integration/smb/outbound/SmbSendingMessageHandlerTests.java +++ b/spring-integration-smb/src/test/java/org/springframework/integration/smb/outbound/SmbSendingMessageHandlerTests.java @@ -26,11 +26,11 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.smb.AbstractBaseTests; import org.springframework.integration.smb.session.SmbSession; import org.springframework.integration.smb.session.SmbSessionFactory; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.support.GenericMessage; import org.springframework.util.FileSystemUtils; @@ -45,7 +45,7 @@ * @author Prafull Kumar Soni * @author Gregory Bragg */ -public class SmbSendingMessageHandlerTests extends AbstractBaseTests { +public class SmbSendingMessageHandlerTests extends AbstractBaseTests implements TestApplicationContextAware { private SmbSession smbSession; @@ -75,7 +75,7 @@ public void testHandleFileContentMessage() { handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); handler.setFileNameGenerator(message -> "handlerContent.test"); handler.setAutoCreateDirectory(true); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("hello")); assertFileExists(file); @@ -88,7 +88,7 @@ public void testHandleFileAsByte() { handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); handler.setFileNameGenerator(message -> "handlerContent.test"); handler.setAutoCreateDirectory(true); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("hello".getBytes())); assertFileExists(file); diff --git a/spring-integration-smb/src/test/java/org/springframework/integration/smb/session/SmbSessionFactoryWithCIFSContextTests.java b/spring-integration-smb/src/test/java/org/springframework/integration/smb/session/SmbSessionFactoryWithCIFSContextTests.java index 47e52bf95aa..01c8112685c 100644 --- a/spring-integration-smb/src/test/java/org/springframework/integration/smb/session/SmbSessionFactoryWithCIFSContextTests.java +++ b/spring-integration-smb/src/test/java/org/springframework/integration/smb/session/SmbSessionFactoryWithCIFSContextTests.java @@ -29,10 +29,10 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.file.remote.handler.FileTransferringMessageHandler; import org.springframework.integration.smb.AbstractBaseTests; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.support.GenericMessage; import org.springframework.util.FileSystemUtils; @@ -46,7 +46,7 @@ * @author Gregory Bragg * @author Artem Bilan */ -public class SmbSessionFactoryWithCIFSContextTests extends AbstractBaseTests { +public class SmbSessionFactoryWithCIFSContextTests extends AbstractBaseTests implements TestApplicationContextAware { private SmbSession smbSession; @@ -79,7 +79,7 @@ public void testHandleFileContentMessage() { handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir")); handler.setFileNameGenerator(message -> "handlerContent.test"); handler.setAutoCreateDirectory(true); - handler.setBeanFactory(mock(BeanFactory.class)); + handler.setBeanFactory(TEST_INTEGRATION_CONTEXT); handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage<>("hello")); assertFileExists(file); diff --git a/spring-integration-syslog/src/test/java/org/springframework/integration/syslog/inbound/SyslogReceivingChannelAdapterTests.java b/spring-integration-syslog/src/test/java/org/springframework/integration/syslog/inbound/SyslogReceivingChannelAdapterTests.java index e275547ceb2..2ba1638a11a 100644 --- a/spring-integration-syslog/src/test/java/org/springframework/integration/syslog/inbound/SyslogReceivingChannelAdapterTests.java +++ b/spring-integration-syslog/src/test/java/org/springframework/integration/syslog/inbound/SyslogReceivingChannelAdapterTests.java @@ -46,14 +46,17 @@ import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.PollableChannel; +import org.springframework.scheduling.TaskScheduler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; /** * @author Gary Russell @@ -72,13 +75,14 @@ public void testUdp() throws Exception { PollableChannel outputChannel = new QueueChannel(); factory.setPort(0); factory.setOutputChannel(outputChannel); - factory.setBeanFactory(mock(BeanFactory.class)); + factory.setBeanFactory(mock()); factory.afterPropertiesSet(); factory.start(); UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "syslogAdapter.udpAdapter", UnicastReceivingChannelAdapter.class); TestingUtilities.waitListening(server, null); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); + adapter.setBeanFactory(mock()); byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", server.getPort())); @@ -106,7 +110,7 @@ public void testTcp() throws Exception { return null; }).when(publisher).publishEvent(any(ApplicationEvent.class)); factory.setApplicationEventPublisher(publisher); - factory.setBeanFactory(mock(BeanFactory.class)); + factory.setBeanFactory(getBeanFactory()); factory.afterPropertiesSet(); factory.start(); AbstractServerConnectionFactory server = TestUtils.getPropertyValue(factory, "syslogAdapter.connectionFactory", @@ -144,15 +148,18 @@ public void testAsMapFalse() throws Exception { factory.setPort(0); PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); - factory.setBeanFactory(mock(BeanFactory.class)); + factory.setBeanFactory(mock()); factory.afterPropertiesSet(); factory.start(); UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "syslogAdapter.udpAdapter", UnicastReceivingChannelAdapter.class); + server.setBeanFactory(mock()); TestingUtilities.waitListening(server, null); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); + adapter.setBeanFactory(mock()); DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter(); defaultMessageConverter.setAsMap(false); + defaultMessageConverter.setBeanFactory(mock()); adapter.setConverter(defaultMessageConverter); byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", @@ -173,6 +180,7 @@ public void testAsMapFalse() throws Exception { public void testTcpRFC5424() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp); + factory.setBeanFactory(getBeanFactory()); PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @@ -181,8 +189,9 @@ public void testTcpRFC5424() throws Exception { latch.countDown(); return null; }).when(publisher).publishEvent(any(ApplicationEvent.class)); - factory.setBeanFactory(mock(BeanFactory.class)); + factory.setBeanFactory(getBeanFactory()); AbstractServerConnectionFactory connectionFactory = new TcpNioServerConnectionFactory(0); + connectionFactory.setBeanFactory(getBeanFactory()); connectionFactory.setDeserializer(new RFC6587SyslogDeserializer()); connectionFactory.setApplicationEventPublisher(publisher); factory.setConnectionFactory(connectionFactory); @@ -191,6 +200,7 @@ public void testTcpRFC5424() throws Exception { factory.start(); TestingUtilities.waitListening(connectionFactory, null); TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject(); + adapter.setBeanFactory(getBeanFactory()); LogAccessor logger = spy(TestUtils.getPropertyValue(adapter, "logger", LogAccessor.class)); doReturn(true).when(logger).isDebugEnabled(); final CountDownLatch sawLog = new CountDownLatch(1); @@ -223,21 +233,23 @@ public void testTcpRFC5424() throws Exception { public void testUdpRFC5424() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.udp); + factory.setBeanFactory(mock()); factory.setPort(0); PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); - factory.setBeanFactory(mock(BeanFactory.class)); factory.setConverter(new RFC5424MessageConverter()); factory.afterPropertiesSet(); factory.start(); UnicastReceivingChannelAdapter server = TestUtils.getPropertyValue(factory, "syslogAdapter.udpAdapter", UnicastReceivingChannelAdapter.class); + server.setBeanFactory(mock()); TestingUtilities.waitListening(server, null); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - " + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance") .getBytes(StandardCharsets.UTF_8); + adapter.setBeanFactory(mock()); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", adapter.getPort())); DatagramSocket socket = new DatagramSocket(); @@ -251,4 +263,12 @@ public void testUdpRFC5424() throws Exception { adapter.stop(); } + private BeanFactory getBeanFactory() { + BeanFactory beanFactory = mock(BeanFactory.class); + TaskScheduler taskScheduler = mock(TaskScheduler.class); + when(beanFactory.getBean(eq("taskScheduler"), any(Class.class))) + .thenReturn(taskScheduler); + when(beanFactory.containsBean("taskScheduler")).thenReturn(true); + return beanFactory; + } } diff --git a/spring-integration-test-support/src/main/java/org/springframework/integration/test/context/TestApplicationContextAware.java b/spring-integration-test-support/src/main/java/org/springframework/integration/test/context/TestApplicationContextAware.java new file mode 100644 index 00000000000..1ef5c22a2a4 --- /dev/null +++ b/spring-integration-test-support/src/main/java/org/springframework/integration/test/context/TestApplicationContextAware.java @@ -0,0 +1,71 @@ +/* + * Copyright 2002-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.integration.test.context; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; + +import org.springframework.integration.test.util.TestUtils; + +/** + * Utility interface for test classes that require access to a shared + * {@link org.springframework.context.ApplicationContext} initialized via + * {@link TestUtils#createTestApplicationContext()}. + *

+ * This interface provides default {@code @BeforeAll} and {@code @AfterAll} + * lifecycle hooks to initialize and close the test application context + * once per test class. + *

+ * It ensures that: + *

    + *
  • The context is refreshed exactly once before any test runs.
  • + *
  • Any redundant refresh attempts are caught and suppressed (unless caused by an unrelated issue).
  • + *
  • The context is properly closed after all tests complete.
  • + *
+ *

+ * To use this interface, a test class simply needs to implement it. + * + * @author Glenn Renfro + * + * @since 7.0 + */ +public interface TestApplicationContextAware { + + TestUtils.TestApplicationContext TEST_INTEGRATION_CONTEXT = TestUtils.createTestApplicationContext(); + + @BeforeAll + static void beforeAll() { + try { + TEST_INTEGRATION_CONTEXT.refresh(); + } + catch (IllegalStateException ex) { + if (!ex.getMessage().contains("just call 'refresh' once")) { + throw new RuntimeException(ex); + } + + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + @AfterAll + static void tearDown() { + TEST_INTEGRATION_CONTEXT.close(); + } + +} diff --git a/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java b/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java index ec0f707e2be..a6a7ed0698c 100644 --- a/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java +++ b/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java @@ -37,7 +37,9 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.SmartLifecycle; +import org.springframework.context.expression.MapAccessor; import org.springframework.context.support.GenericApplicationContext; +import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; @@ -120,7 +122,7 @@ else if (i == tokens.length - 1) { public static TestApplicationContext createTestApplicationContext() { TestApplicationContext context = new TestApplicationContext(); ErrorHandler errorHandler = new MessagePublishingErrorHandler(context); - ThreadPoolTaskScheduler scheduler = createTaskScheduler(10); // NOSONAR + ThreadPoolTaskScheduler scheduler = createTaskScheduler(10); scheduler.setErrorHandler(errorHandler); registerBean("taskScheduler", scheduler, context); registerBean("integrationConversionService", new DefaultFormattingConversionService(), context); @@ -129,6 +131,9 @@ public static TestApplicationContext createTestApplicationContext() { LOGGER.error(message); return true; }, context); + StandardEvaluationContext integrationEvaluationContext = new StandardEvaluationContext(); + integrationEvaluationContext.addPropertyAccessor(new MapAccessor()); + registerBean("integrationEvaluationContext", integrationEvaluationContext, context); return context; } diff --git a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/observation/WebFluxObservationPropagationTests.java b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/observation/WebFluxObservationPropagationTests.java index 707b3b3188b..701fb302702 100644 --- a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/observation/WebFluxObservationPropagationTests.java +++ b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/observation/WebFluxObservationPropagationTests.java @@ -53,6 +53,7 @@ import org.springframework.integration.config.EnableIntegrationManagement; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.dsl.IntegrationFlow; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.webflux.dsl.WebFlux; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -75,7 +76,7 @@ */ @SpringJUnitWebConfig @DirtiesContext -public class WebFluxObservationPropagationTests { +public class WebFluxObservationPropagationTests implements TestApplicationContextAware { private static final TestSpanHandler SPANS = new TestSpanHandler(); @@ -135,8 +136,10 @@ void observationIsPropagatedWebFluxRequestReply() { @Test void observationIsPropagatedWebFluxClientRequestReply() { + MessagingTemplate messagingTemplate = new MessagingTemplate(); + messagingTemplate.setBeanFactory(TEST_INTEGRATION_CONTEXT); String result = - new MessagingTemplate() + messagingTemplate .convertSendAndReceive(this.webFluxRequestReplyClientFlowInput, "test", String.class); assertThat(result).isEqualTo("SOME REPLY"); diff --git a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/outbound/WebFluxRequestExecutingMessageHandlerTests.java b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/outbound/WebFluxRequestExecutingMessageHandlerTests.java index e622e4dee2c..e2d9792ace9 100644 --- a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/outbound/WebFluxRequestExecutingMessageHandlerTests.java +++ b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/outbound/WebFluxRequestExecutingMessageHandlerTests.java @@ -26,12 +26,12 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferLimitException; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.SimpleEvaluationContext; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -41,6 +41,7 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.http.HttpHeaders; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.webflux.support.ClientHttpResponseBodyExtractor; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; @@ -55,7 +56,6 @@ import org.springframework.web.reactive.function.client.WebClientResponseException; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @author Shiliang Li @@ -65,7 +65,7 @@ * * @since 5.0 */ -class WebFluxRequestExecutingMessageHandlerTests { +class WebFluxRequestExecutingMessageHandlerTests implements TestApplicationContextAware { @Test void testReactiveReturn() { @@ -470,7 +470,10 @@ public Mono filter(ClientRequest request, ExchangeFunction next) reactiveHandler.setReplyPayloadToFlux(true); Expression expr = new SpelExpressionParser().parseExpression("{name:{first:'Nikola'}}"); reactiveHandler.setAttributeVariablesExpression(expr); - reactiveHandler.setBeanFactory(mock(BeanFactory.class)); + reactiveHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); + TEST_INTEGRATION_CONTEXT.registerBean("integrationSimpleEvaluationContext", SimpleEvaluationContext + .forReadOnlyDataBinding() + .build()); reactiveHandler.afterPropertiesSet(); reactiveHandler.handleMessage(MessageBuilder.withPayload(Mono.just("hello, world")).build()); diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/SimpleWebServiceOutboundGatewayTests.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/SimpleWebServiceOutboundGatewayTests.java index 23c5c4a5c30..8f9cc98b1fc 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/SimpleWebServiceOutboundGatewayTests.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/SimpleWebServiceOutboundGatewayTests.java @@ -31,11 +31,11 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ByteArrayResource; import org.springframework.integration.handler.ReplyRequiredException; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandlingException; @@ -62,7 +62,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; /** * @author Mark Fisher @@ -71,7 +70,7 @@ * * @since 2.0 */ -public class SimpleWebServiceOutboundGatewayTests { +public class SimpleWebServiceOutboundGatewayTests implements TestApplicationContextAware { private static final String response = "Test Name"; @@ -99,7 +98,7 @@ public void soapActionAndCustomCallback() { SoapMessage soapMessage = (SoapMessage) message; soapActionFromCallback.set(soapMessage.getSoapAction()); }); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); gateway.afterPropertiesSet(); String soapActionHeaderValue = "testAction"; String request = "foo"; @@ -142,7 +141,7 @@ public void testInt3022EmptyResponseBody() throws Exception { public void testAttachments() throws Exception { String uri = "https://www.example.org"; SimpleWebServiceOutboundGateway gateway = new SimpleWebServiceOutboundGateway(uri); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); final CompletableFuture requestFuture = new CompletableFuture<>(); @@ -202,7 +201,7 @@ public boolean handleRequest(MessageContext messageContext) throws WebServiceCli public void testDomPoxMessageFactory() throws Exception { String uri = "https://www.example.org"; SimpleWebServiceOutboundGateway gateway = new SimpleWebServiceOutboundGateway(uri); - gateway.setBeanFactory(mock(BeanFactory.class)); + gateway.setBeanFactory(TEST_INTEGRATION_CONTEXT); final CompletableFuture requestFuture = new CompletableFuture<>(); diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceHeaderEnricherTests.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceHeaderEnricherTests.java index 3a191710e8f..d5bee75b5d5 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceHeaderEnricherTests.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceHeaderEnricherTests.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.core.MessagingTemplate; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.ws.WebServiceHeaders; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -40,7 +41,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class WebServiceHeaderEnricherTests { +public class WebServiceHeaderEnricherTests implements TestApplicationContextAware { @Autowired @Qualifier("literalValueInput") @@ -53,6 +54,7 @@ public class WebServiceHeaderEnricherTests { @Test public void literalValue() { MessagingTemplate template = new MessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(literalValueInput); Message result = template.sendAndReceive(new GenericMessage<>("foo")); Map headers = result.getHeaders(); @@ -62,6 +64,7 @@ public void literalValue() { @Test public void expression() { MessagingTemplate template = new MessagingTemplate(); + template.setBeanFactory(TEST_INTEGRATION_CONTEXT); template.setDefaultDestination(expressionInput); Message result = template.sendAndReceive(new GenericMessage<>("foo")); Map headers = result.getHeaders(); diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XsltPayloadTransformerTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XsltPayloadTransformerTests.java index b34e2cdcd25..851f383dba9 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XsltPayloadTransformerTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XsltPayloadTransformerTests.java @@ -28,13 +28,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.mockito.Mockito; import org.w3c.dom.Document; -import org.springframework.beans.factory.BeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.xml.result.DomResultFactory; import org.springframework.integration.xml.result.StringResultFactory; import org.springframework.integration.xml.util.XmlTestUtil; @@ -56,7 +55,7 @@ * @author Mike Bazos * @author Artem Bilan */ -public class XsltPayloadTransformerTests { +public class XsltPayloadTransformerTests implements TestApplicationContextAware { private XsltPayloadTransformer testTransformer; @@ -78,7 +77,7 @@ public class XsltPayloadTransformerTests { @BeforeEach public void setUp() throws Exception { this.testTransformer = new XsltPayloadTransformer(getXslTemplates()); - this.testTransformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + this.testTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); this.testTransformer.setAlwaysUseResultFactory(false); this.testTransformer.afterPropertiesSet(); } @@ -144,7 +143,7 @@ public void testSourceWithResultTransformer() throws Exception { Integer returnValue = 13; XsltPayloadTransformer transformer = new XsltPayloadTransformer(getXslTemplates(), new StubResultTransformer(returnValue)); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); Object transformed = transformer .doTransform(new GenericMessage<>(new StringSource(docAsString))); @@ -157,7 +156,7 @@ public void testXsltPayloadWithTransformerFactoryClassName() throws Exception { XsltPayloadTransformer transformer = new XsltPayloadTransformer(getXslResourceThatOutputsText(), new StubResultTransformer(returnValue), "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); Object transformed = transformer.doTransform(new GenericMessage<>(new StringSource(this.docAsString))); assertThat(transformed) @@ -169,7 +168,7 @@ public void testXsltPayloadWithTransformerFactoryClassName() throws Exception { public void testXsltPayloadWithBadTransformerFactoryClassName() throws IOException { XsltPayloadTransformer transformer = new XsltPayloadTransformer(getXslResourceThatOutputsText(), "foo.bar.Baz"); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); assertThatIllegalStateException() .isThrownBy(transformer::afterPropertiesSet) .withCauseExactlyInstanceOf(ClassNotFoundException.class); @@ -192,7 +191,7 @@ public void testUnsupportedPayloadType() { public void testXsltWithImports() { Resource resource = new ClassPathResource("transform-with-import.xsl", getClass()); XsltPayloadTransformer transformer = new XsltPayloadTransformer(resource); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); Object transformed = transformer.doTransform(new GenericMessage<>(this.docAsString)); assertThat(transformed).and(this.outputAsString).areIdentical(); @@ -204,7 +203,7 @@ public void documentInStringResultOut() throws Exception { XsltPayloadTransformer transformer = new XsltPayloadTransformer(resource); transformer.setResultFactory(new StringResultFactory()); transformer.setAlwaysUseResultFactory(true); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); GenericMessage message = new GenericMessage<>(XmlTestUtil.getDocumentForString(this.docAsString)); Object transformed = transformer.doTransform(message); @@ -219,7 +218,7 @@ public void stringInDomResultOut() throws Exception { XsltPayloadTransformer transformer = new XsltPayloadTransformer(resource); transformer.setResultFactory(new DomResultFactory()); transformer.setAlwaysUseResultFactory(true); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); GenericMessage message = new GenericMessage<>(XmlTestUtil.getDocumentForString(this.docAsString)); Object transformed = transformer.doTransform(message); @@ -233,7 +232,7 @@ public void docInStringOut() throws Exception { XsltPayloadTransformer transformer = new XsltPayloadTransformer(getXslResourceThatOutputsText()); transformer.setResultFactory(new StringResultFactory()); transformer.setAlwaysUseResultFactory(true); - transformer.setBeanFactory(Mockito.mock(BeanFactory.class)); + transformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); transformer.afterPropertiesSet(); GenericMessage message = new GenericMessage<>(XmlTestUtil.getDocumentForString(this.docAsString)); Object transformed = transformer.doTransform(message); diff --git a/spring-integration-xmpp/src/test/java/org/springframework/integration/xmpp/inbound/ChatMessageListeningEndpointTests.java b/spring-integration-xmpp/src/test/java/org/springframework/integration/xmpp/inbound/ChatMessageListeningEndpointTests.java index 94f9bc8a47a..fafedbdb027 100644 --- a/spring-integration-xmpp/src/test/java/org/springframework/integration/xmpp/inbound/ChatMessageListeningEndpointTests.java +++ b/spring-integration-xmpp/src/test/java/org/springframework/integration/xmpp/inbound/ChatMessageListeningEndpointTests.java @@ -41,13 +41,12 @@ import org.mockito.Mockito; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.log.LogAccessor; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.xmpp.core.XmppContextUtils; import org.springframework.messaging.MessagingException; @@ -70,7 +69,7 @@ * @author Florian Schmaus * @author Artem Bilan */ -public class ChatMessageListeningEndpointTests { +public class ChatMessageListeningEndpointTests implements TestApplicationContextAware { /* * Should add/remove StanzaListener when endpoint started/stopped @@ -95,7 +94,7 @@ public void testLifecycle() { assertThat(packetListSet.size()).isEqualTo(0); endpoint.setOutputChannel(new QueueChannel()); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); endpoint.start(); assertThat(packetListSet.size()).isEqualTo(1); @@ -112,10 +111,9 @@ public void testNonInitializationFailure() { @Test public void testWithImplicitXmppConnection() { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - bf.registerSingleton(XmppContextUtils.XMPP_CONNECTION_BEAN_NAME, mock(XMPPConnection.class)); + TEST_INTEGRATION_CONTEXT.registerBean(XmppContextUtils.XMPP_CONNECTION_BEAN_NAME, mock(XMPPConnection.class)); ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint(); - endpoint.setBeanFactory(bf); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.setOutputChannel(new QueueChannel()); endpoint.afterPropertiesSet(); assertThat(TestUtils.getPropertyValue(endpoint, "xmppConnection")).isNotNull(); @@ -124,17 +122,14 @@ public void testWithImplicitXmppConnection() { @Test public void testNoXmppConnection() { ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint(); - endpoint.setBeanFactory(mock(BeanFactory.class)); assertThatIllegalArgumentException() .isThrownBy(endpoint::afterPropertiesSet); } @Test public void testWithErrorChannel() throws Exception { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XMPPConnection connection = mock(XMPPConnection.class); - bf.registerSingleton(XmppContextUtils.XMPP_CONNECTION_BEAN_NAME, connection); - + TEST_INTEGRATION_CONTEXT.registerBean(XmppContextUtils.XMPP_CONNECTION_BEAN_NAME, connection); ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint(); DirectChannel outChannel = new DirectChannel(); @@ -142,7 +137,7 @@ public void testWithErrorChannel() throws Exception { throw new RuntimeException("ooops"); }); PollableChannel errorChannel = new QueueChannel(); - endpoint.setBeanFactory(bf); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.setOutputChannel(outChannel); endpoint.setErrorChannel(errorChannel); endpoint.afterPropertiesSet(); @@ -168,7 +163,7 @@ public void testExpression() throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); endpoint.setPayloadExpression(parser.parseExpression("#root")); endpoint.setOutputChannel(inputChannel); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); endpoint.start(); @@ -239,7 +234,7 @@ public void testGcmExtension() throws Exception { Expression payloadExpression = new SpelExpressionParser().parseExpression("#extension.json"); endpoint.setPayloadExpression(payloadExpression); endpoint.setOutputChannel(inputChannel); - endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.setBeanFactory(TEST_INTEGRATION_CONTEXT); endpoint.afterPropertiesSet(); endpoint.start(); diff --git a/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/channel/ZeroMqChannelTests.java b/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/channel/ZeroMqChannelTests.java index c98ffaa6803..0434f9dad0b 100644 --- a/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/channel/ZeroMqChannelTests.java +++ b/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/channel/ZeroMqChannelTests.java @@ -33,6 +33,7 @@ import reactor.core.publisher.Mono; import org.springframework.integration.support.json.EmbeddedJsonHeadersMessageMapper; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.zeromq.ZeroMqProxy; import org.springframework.messaging.Message; @@ -46,18 +47,18 @@ * * @since 5.4 */ -public class ZeroMqChannelTests { +public class ZeroMqChannelTests implements TestApplicationContextAware { - private static final ZContext CONTEXT = new ZContext(); + private static final ZContext Z_CONTEXT = new ZContext(); @AfterAll static void tearDown() { - CONTEXT.close(); + Z_CONTEXT.close(); } @Test void testSimpleSendAndReceive() throws InterruptedException { - ZeroMqChannel channel = new ZeroMqChannel(CONTEXT); + ZeroMqChannel channel = new ZeroMqChannel(Z_CONTEXT); channel.setBeanName("testChannel1"); channel.setConsumeDelay(Duration.ofMillis(10)); channel.setSendSocketConfigurer(socket -> socket.setZapDomain("global")); @@ -72,6 +73,7 @@ public Message toMessage(byte[] bytes, Map headers) { } }); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel.afterPropertiesSet(); @SuppressWarnings("unchecked") @@ -112,9 +114,10 @@ public Message toMessage(byte[] bytes, Map headers) { @Test void testPubSubLocal() throws InterruptedException { - ZeroMqChannel channel = new ZeroMqChannel(CONTEXT, true); + ZeroMqChannel channel = new ZeroMqChannel(Z_CONTEXT, true); channel.setBeanName("testChannel2"); channel.setConsumeDelay(Duration.ofMillis(10)); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel.afterPropertiesSet(); BlockingQueue> received = new LinkedBlockingQueue<>(); @@ -135,7 +138,7 @@ void testPubSubLocal() throws InterruptedException { @Test void testPushPullBind() throws InterruptedException { - ZeroMqProxy proxy = new ZeroMqProxy(CONTEXT); + ZeroMqProxy proxy = new ZeroMqProxy(Z_CONTEXT); proxy.setBeanName("pullPushProxy"); proxy.setExposeCaptureSocket(true); proxy.afterPropertiesSet(); @@ -143,14 +146,15 @@ void testPushPullBind() throws InterruptedException { await().until(() -> proxy.getBackendPort() > 0); - ZMQ.Socket captureSocket = CONTEXT.createSocket(SocketType.SUB); + ZMQ.Socket captureSocket = Z_CONTEXT.createSocket(SocketType.SUB); captureSocket.subscribe(ZMQ.SUBSCRIPTION_ALL); captureSocket.connect(proxy.getCaptureAddress()); - ZeroMqChannel channel = new ZeroMqChannel(CONTEXT); + ZeroMqChannel channel = new ZeroMqChannel(Z_CONTEXT); channel.setConnectUrl("tcp://localhost:" + proxy.getFrontendPort() + ':' + proxy.getBackendPort()); channel.setBeanName("testChannel3"); channel.setConsumeDelay(Duration.ofMillis(10)); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel.afterPropertiesSet(); BlockingQueue> received = new LinkedBlockingQueue<>(); @@ -179,15 +183,17 @@ void testPushPullBind() throws InterruptedException { @Test void testPubSubBind() throws InterruptedException { - ZeroMqProxy proxy = new ZeroMqProxy(CONTEXT, ZeroMqProxy.Type.SUB_PUB); + ZeroMqProxy proxy = new ZeroMqProxy(Z_CONTEXT, ZeroMqProxy.Type.SUB_PUB); proxy.setBeanName("subPubProxy"); proxy.afterPropertiesSet(); proxy.start(); - ZeroMqChannel channel = new ZeroMqChannel(CONTEXT, true); + ZeroMqChannel channel = new ZeroMqChannel(Z_CONTEXT, true); channel.setZeroMqProxy(proxy); channel.setBeanName("testChannel4"); channel.setConsumeDelay(Duration.ofMillis(10)); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel.afterPropertiesSet(); BlockingQueue> received = new LinkedBlockingQueue<>(); @@ -197,10 +203,11 @@ void testPubSubBind() throws InterruptedException { await().until(() -> proxy.getBackendPort() > 0); - ZeroMqChannel channel2 = new ZeroMqChannel(CONTEXT, true); + ZeroMqChannel channel2 = new ZeroMqChannel(Z_CONTEXT, true); channel2.setConnectUrl("tcp://localhost:" + proxy.getFrontendPort() + ':' + proxy.getBackendPort()); channel2.setBeanName("testChannel5"); channel2.setConsumeDelay(Duration.ofMillis(10)); + channel2.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel2.afterPropertiesSet(); channel2.subscribe(received::offer); @@ -227,12 +234,12 @@ void testPubSubBind() throws InterruptedException { @Test void testPubSubWithCurve() throws InterruptedException { - new ZAuth(CONTEXT).configureCurve(ZAuth.CURVE_ALLOW_ANY); + new ZAuth(Z_CONTEXT).configureCurve(ZAuth.CURVE_ALLOW_ANY); ZMQ.Curve.KeyPair frontendKeyPair = ZMQ.Curve.generateKeyPair(); ZMQ.Curve.KeyPair backendKeyPair = ZMQ.Curve.generateKeyPair(); - ZeroMqProxy proxy = new ZeroMqProxy(CONTEXT, ZeroMqProxy.Type.SUB_PUB); + ZeroMqProxy proxy = new ZeroMqProxy(Z_CONTEXT, ZeroMqProxy.Type.SUB_PUB); proxy.setBeanName("subPubCurveProxy"); proxy.setFrontendSocketConfigurer(socket -> { socket.setZAPDomain("global".getBytes()); @@ -249,7 +256,7 @@ void testPubSubWithCurve() throws InterruptedException { proxy.afterPropertiesSet(); proxy.start(); - ZeroMqChannel channel = new ZeroMqChannel(CONTEXT, true); + ZeroMqChannel channel = new ZeroMqChannel(Z_CONTEXT, true); channel.setZeroMqProxy(proxy); channel.setBeanName("testChannelWithCurve"); channel.setSendSocketConfigurer(socket -> { @@ -266,6 +273,7 @@ void testPubSubWithCurve() throws InterruptedException { } ); channel.setConsumeDelay(Duration.ofMillis(10)); + channel.setBeanFactory(TEST_INTEGRATION_CONTEXT); channel.afterPropertiesSet(); BlockingQueue> received = new LinkedBlockingQueue<>(); diff --git a/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/outbound/ZeroMqMessageHandlerTests.java b/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/outbound/ZeroMqMessageHandlerTests.java index 50ec0fe68ee..da3259b8061 100644 --- a/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/outbound/ZeroMqMessageHandlerTests.java +++ b/spring-integration-zeromq/src/test/java/org/springframework/integration/zeromq/outbound/ZeroMqMessageHandlerTests.java @@ -26,10 +26,10 @@ import org.zeromq.ZMsg; import reactor.core.publisher.Mono; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.expression.FunctionExpression; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.json.EmbeddedJsonHeadersMessageMapper; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.zeromq.ZeroMqProxy; import org.springframework.messaging.Message; @@ -39,7 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.mock; /** * @author Artem Bilan @@ -47,23 +46,23 @@ * * @since 5.4 */ -public class ZeroMqMessageHandlerTests { +public class ZeroMqMessageHandlerTests implements TestApplicationContextAware { - private static final ZContext CONTEXT = new ZContext(); + private static final ZContext Z_CONTEXT = new ZContext(); @AfterAll static void tearDown() { - CONTEXT.close(); + Z_CONTEXT.close(); } @Test void testMessageHandlerForPair() { String socketAddress = "inproc://messageHandler.test"; - ZMQ.Socket socket = CONTEXT.createSocket(SocketType.PAIR); + ZMQ.Socket socket = Z_CONTEXT.createSocket(SocketType.PAIR); socket.bind(socketAddress); - ZeroMqMessageHandler messageHandler = new ZeroMqMessageHandler(CONTEXT, socketAddress); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + ZeroMqMessageHandler messageHandler = new ZeroMqMessageHandler(Z_CONTEXT, socketAddress); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.setSocketConfigurer(s -> s.setZapDomain("global")); messageHandler.afterPropertiesSet(); messageHandler.start(); @@ -88,14 +87,14 @@ void testMessageHandlerForPair() { @Test void testMessageHandlerForPubSub() { - ZMQ.Socket subSocket = CONTEXT.createSocket(SocketType.SUB); + ZMQ.Socket subSocket = Z_CONTEXT.createSocket(SocketType.SUB); subSocket.setReceiveTimeOut(0); int port = subSocket.bindToRandomPort("tcp://*"); subSocket.subscribe("test"); ZeroMqMessageHandler messageHandler = - new ZeroMqMessageHandler(CONTEXT, "tcp://localhost:" + port, SocketType.PUB); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + new ZeroMqMessageHandler(Z_CONTEXT, "tcp://localhost:" + port, SocketType.PUB); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.setTopicExpression( new FunctionExpression>((message) -> message.getHeaders().get("topic"))); messageHandler.setMessageMapper(new EmbeddedJsonHeadersMessageMapper()); @@ -123,20 +122,20 @@ void testMessageHandlerForPubSub() { @Test void testMessageHandlerForPushPullOverProxy() { - ZeroMqProxy proxy = new ZeroMqProxy(CONTEXT); + ZeroMqProxy proxy = new ZeroMqProxy(Z_CONTEXT); proxy.setBeanName("pullPushProxy"); proxy.afterPropertiesSet(); proxy.start(); await().until(() -> proxy.getBackendPort() > 0); - ZMQ.Socket pullSocket = CONTEXT.createSocket(SocketType.PULL); + ZMQ.Socket pullSocket = Z_CONTEXT.createSocket(SocketType.PULL); pullSocket.setReceiveTimeOut(20_000); pullSocket.connect("tcp://localhost:" + proxy.getBackendPort()); ZeroMqMessageHandler messageHandler = - new ZeroMqMessageHandler(CONTEXT, "tcp://localhost:" + proxy.getFrontendPort(), SocketType.PUSH); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + new ZeroMqMessageHandler(Z_CONTEXT, "tcp://localhost:" + proxy.getFrontendPort(), SocketType.PUSH); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.setMessageConverter(new ByteArrayMessageConverter()); messageHandler.afterPropertiesSet(); messageHandler.start(); @@ -154,14 +153,14 @@ void testMessageHandlerForPushPullOverProxy() { @Test void testMessageHandlerForPubSubDisabledWrapTopic() { - ZMQ.Socket subSocket = CONTEXT.createSocket(SocketType.SUB); + ZMQ.Socket subSocket = Z_CONTEXT.createSocket(SocketType.SUB); subSocket.setReceiveTimeOut(0); int port = subSocket.bindToRandomPort("tcp://*"); subSocket.subscribe("test"); ZeroMqMessageHandler messageHandler = - new ZeroMqMessageHandler(CONTEXT, "tcp://localhost:" + port, SocketType.PUB); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + new ZeroMqMessageHandler(Z_CONTEXT, "tcp://localhost:" + port, SocketType.PUB); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.setTopicExpression( new FunctionExpression>((message) -> message.getHeaders().get("topic"))); messageHandler.setMessageMapper(new EmbeddedJsonHeadersMessageMapper()); @@ -192,8 +191,8 @@ void testMessageHandlerForPubSubDisabledWrapTopic() { void testMessageHandlerForPubSubWithBind() { int boundPort = TestSocketUtils.findAvailableTcpPort(); ZeroMqMessageHandler messageHandler = - new ZeroMqMessageHandler(CONTEXT, boundPort, SocketType.PUB); - messageHandler.setBeanFactory(mock(BeanFactory.class)); + new ZeroMqMessageHandler(Z_CONTEXT, boundPort, SocketType.PUB); + messageHandler.setBeanFactory(TEST_INTEGRATION_CONTEXT); messageHandler.setTopicExpression( new FunctionExpression>((message) -> message.getHeaders().get("topic"))); messageHandler.setMessageMapper(new EmbeddedJsonHeadersMessageMapper()); @@ -201,7 +200,7 @@ void testMessageHandlerForPubSubWithBind() { messageHandler.afterPropertiesSet(); messageHandler.start(); - ZMQ.Socket subSocket = CONTEXT.createSocket(SocketType.SUB); + ZMQ.Socket subSocket = Z_CONTEXT.createSocket(SocketType.SUB); subSocket.setReceiveTimeOut(0); subSocket.connect("tcp://localhost:" + boundPort); subSocket.subscribe("test"); diff --git a/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/UnZipTransformerTests.java b/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/UnZipTransformerTests.java index 8e531448283..aba7cb86324 100644 --- a/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/UnZipTransformerTests.java +++ b/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/UnZipTransformerTests.java @@ -34,6 +34,7 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; @@ -53,7 +54,7 @@ */ @SpringJUnitConfig @DirtiesContext -public class UnZipTransformerTests { +public class UnZipTransformerTests implements TestApplicationContextAware { @TempDir public File workDir; @@ -70,6 +71,7 @@ public void unzipFlatFileEntryZip() throws IOException { final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.FILE); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); final Message resultMessage = unZipTransformer.transform(message); @@ -91,6 +93,7 @@ public void unzipSingleFileAsInputStreamToByteArray() throws IOException { final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); final Message resultMessage = unZipTransformer.transform(message); @@ -120,6 +123,7 @@ public void unzipSingleFileToByteArray() throws IOException { final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); final Message resultMessage = unZipTransformer.transform(message); @@ -151,6 +155,7 @@ public void unzipSingleFileToByteArrayWithDeleteFilesTrue() throws IOException { final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); unZipTransformer.setDeleteFiles(true); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); final Message resultMessage = unZipTransformer.transform(message); @@ -174,6 +179,7 @@ public void unzipMultipleFilesAsInputStreamToByteArray() throws IOException { final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); final Message resultMessage = unZipTransformer.transform(message); @@ -196,6 +202,7 @@ public void unzipMultipleFilesAsInputStreamWithExpectSingleResultTrue() throws I final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); unZipTransformer.setExpectSingleResult(true); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); assertThatExceptionOfType(MessagingException.class) @@ -212,6 +219,7 @@ public void unzipInvalidZipFile() throws IOException { UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); unZipTransformer.setExpectSingleResult(true); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); Message message = MessageBuilder.withPayload(fileToUnzip).build(); @@ -229,6 +237,7 @@ public void testUnzipMaliciousTraversalZipFile() throws IOException { final Message message = MessageBuilder.withPayload(is).build(); final UnZipTransformer unZipTransformer = new UnZipTransformer(); + unZipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); unZipTransformer.afterPropertiesSet(); assertThatExceptionOfType(MessageTransformationException.class) diff --git a/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/ZipTransformerTests.java b/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/ZipTransformerTests.java index 9693875ea70..9ae6fa9e70e 100644 --- a/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/ZipTransformerTests.java +++ b/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/ZipTransformerTests.java @@ -31,13 +31,12 @@ import org.junit.jupiter.api.io.TempDir; import org.zeroturnaround.zip.ZipUtil; -import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.context.TestApplicationContextAware; import org.springframework.integration.zip.ZipHeaders; import org.springframework.messaging.Message; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; /** * @@ -46,7 +45,7 @@ * * @since 6.1 */ -public class ZipTransformerTests { +public class ZipTransformerTests implements TestApplicationContextAware { @TempDir public File workDir; @@ -54,7 +53,7 @@ public class ZipTransformerTests { @Test public void zipString() { final ZipTransformer zipTransformer = new ZipTransformer(); - zipTransformer.setBeanFactory(mock(BeanFactory.class)); + zipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); zipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); zipTransformer.afterPropertiesSet(); @@ -87,7 +86,7 @@ public void zipString() { @Test public void zipStringCollection() { final ZipTransformer zipTransformer = new ZipTransformer(); - zipTransformer.setBeanFactory(mock(BeanFactory.class)); + zipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); zipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY); zipTransformer.afterPropertiesSet(); @@ -145,7 +144,7 @@ public void zipStringCollection() { @Test public void zipStringToFile() { final ZipTransformer zipTransformer = new ZipTransformer(); - zipTransformer.setBeanFactory(mock(BeanFactory.class)); + zipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); zipTransformer.afterPropertiesSet(); final String stringToCompress = "Hello World"; @@ -174,7 +173,7 @@ public void zipStringToFile() { public void zipFile() { ZipTransformer zipTransformer = new ZipTransformer(); - zipTransformer.setBeanFactory(mock(BeanFactory.class)); + zipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); zipTransformer.setDeleteFiles(true); zipTransformer.afterPropertiesSet(); @@ -215,7 +214,7 @@ public void zipCollection() { files.add(testFile4); final ZipTransformer zipTransformer = new ZipTransformer(); - zipTransformer.setBeanFactory(mock(BeanFactory.class)); + zipTransformer.setBeanFactory(TEST_INTEGRATION_CONTEXT); zipTransformer.afterPropertiesSet(); final Message> message = MessageBuilder.withPayload(files).build();