INT-799: Remove Core Deps from s-i-test

JIRA: https://jira.spring.io/browse/INT-799

Some test classes (e.g. `TestUtils`) were duplicated in core to avoid cyclic
dependency.

Now that core messaging has been moved to spring-messaging, it is possible
to remove the dependencies on `spring-integration-core` from `spring-integration-test`.

A few minor test cases have been moved to `spring-integration-core`.

The simple polishing to the `build.gradle` and `ServiceActivatorOnMockitoMockTests`
This commit is contained in:
Gary Russell
2015-11-25 17:17:41 -05:00
committed by Artem Bilan
parent 5850022bfe
commit d16cd9748c
27 changed files with 345 additions and 524 deletions

View File

@@ -103,7 +103,6 @@ import org.springframework.integration.scheduling.PollerMetadata;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.MutableMessageBuilder;
import org.springframework.integration.support.SmartLifecycleRoleController;
import org.springframework.integration.test.util.LogAdjustingTestSupport;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;

View File

@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:channel id="in" />
<int:chain input-channel="in" output-channel="out">
<int:filter expression="payload == 'singleAnnotatedMethodOnClass'" throw-exception-on-rejection="true"/>
<int:service-activator ref="singleAnnotatedMethodOnClass" />
</int:chain>
<bean id="singleAnnotatedMethodOnClass" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="org.springframework.integration.handler.ServiceActivatorOnMockitoMockTests.SingleAnnotatedMethodOnClass" />
</bean>
<int:chain input-channel="in" output-channel="out">
<int:filter expression="payload == 'SingleMethodOnClass'" throw-exception-on-rejection="true"/>
<int:service-activator ref="singleMethodOnClass" />
</int:chain>
<bean id="singleMethodOnClass" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="org.springframework.integration.handler.ServiceActivatorOnMockitoMockTests.SingleMethodOnClass" />
</bean>
<int:chain input-channel="in" output-channel="out">
<int:filter expression="payload == 'SingleMethodAcceptingHeaderOnClass'" throw-exception-on-rejection="true"/>
<int:service-activator ref="singleMethodAcceptingHeaderOnClass" />
</int:chain>
<bean id="singleMethodAcceptingHeaderOnClass" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg
value="org.springframework.integration.handler.ServiceActivatorOnMockitoMockTests.SingleMethodAcceptingHeaderOnClass" />
</bean>
<int:channel id="out">
<int:queue capacity="10" />
</int:channel>
</beans>

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2002-2014 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
*
* http://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.handler;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Iwein Fuld
* @author Gunnar Hillert
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ServiceActivatorOnMockitoMockTests {
@Autowired
@Qualifier("in")
MessageChannel in;
@Autowired
@Qualifier("out")
PollableChannel out;
public static class SingleAnnotatedMethodOnClass {
@ServiceActivator
public String move(String s) {
return s;
}
}
@Autowired
SingleAnnotatedMethodOnClass singleAnnotatedMethodOnClass;
@Test
public void shouldInvokeMockedSingleAnnotatedMethodOnClass() {
in.send(MessageBuilder.withPayload("singleAnnotatedMethodOnClass").build());
verify(singleAnnotatedMethodOnClass).move("singleAnnotatedMethodOnClass");
}
public static class SingleMethodOnClass {
public String move(String s) {
return s;
}
}
@Autowired
SingleMethodOnClass singleMethodOnClass;
@Test
public void shouldInvokeMockedSingleMethodOnClass() {
in.send(MessageBuilder.withPayload("SingleMethodOnClass").build());
verify(singleMethodOnClass).move("SingleMethodOnClass");
}
public static class SingleMethodAcceptingHeaderOnClass {
public String move(@Header("s") String s) {
return s;
}
}
@Autowired
SingleMethodAcceptingHeaderOnClass singleMethodAcceptingHeaderOnClass;
@Test
public void shouldInvokeMockedSingleMethodAcceptingHeaderOnClass() {
in.send(MessageBuilder.withPayload("SingleMethodAcceptingHeaderOnClass")
.setHeader("s", "SingleMethodAcceptingHeaderOnClass")
.build());
verify(singleMethodAcceptingHeaderOnClass).move("SingleMethodAcceptingHeaderOnClass");
}
}

View File

@@ -0,0 +1,201 @@
/*
* Copyright 2002-2013 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
*
* http://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.message;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasAllHeaders;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasCorrelationId;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasExpirationDate;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeader;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasMessageId;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasSequenceNumber;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasSequenceSize;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasTimestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
/**
* @author Alex Peters
* @author Iwein Fuld
* @author Gunnar Hillert
*
*/
public class HeaderMatcherTests {
static final String UNKNOWN_KEY = "unknownKey";
static final String ANY_HEADER_VALUE = "bar";
static final String ANY_HEADER_KEY = "test.foo";
static final String ANY_PAYLOAD = "bla";
static final String OTHER_HEADER_KEY = "test.number";
static final Integer OTHER_HEADER_VALUE = Integer.valueOf(123);
Message<?> message;
@Before
public void setUp() {
message = MessageBuilder.withPayload(ANY_PAYLOAD).setHeader(ANY_HEADER_KEY, ANY_HEADER_VALUE).setHeader(
OTHER_HEADER_KEY, OTHER_HEADER_VALUE).build();
}
@Test
public void hasEntry_withValidKeyValue_matches() throws Exception {
assertThat(message, hasHeader(ANY_HEADER_KEY, ANY_HEADER_VALUE));
assertThat(message, hasHeader(OTHER_HEADER_KEY, OTHER_HEADER_VALUE));
}
@Test
public void hasEntry_withUnknownKey_notMatching() throws Exception {
assertThat(message, not(hasHeader("test.unknown", ANY_HEADER_VALUE)));
}
@Test
public void hasEntry_withValidKeyAndMatcherValue_matches() throws Exception {
assertThat(message, hasHeader(ANY_HEADER_KEY, is(instanceOf(String.class))));
assertThat(message, hasHeader(ANY_HEADER_KEY, notNullValue()));
assertThat(message, hasHeader(ANY_HEADER_KEY, is(ANY_HEADER_VALUE)));
}
@Test
public void hasEntry_withValidKeyAndMatcherValue_notMatching() throws Exception {
assertThat(message, not(hasHeader(ANY_HEADER_KEY, is(instanceOf(Integer.class)))));
}
@Test
public void hasKey_withValidKey_matches() throws Exception {
assertThat(message, hasHeaderKey(ANY_HEADER_KEY));
assertThat(message, hasHeaderKey(OTHER_HEADER_KEY));
}
@Test
public void hasKey_withInvalidKey_notMatching() throws Exception {
assertThat(message, not(hasHeaderKey(UNKNOWN_KEY)));
}
@Test
public void hasAllEntries_withMessageHeader_matches() throws Exception {
Map<String, Object> expectedInHeaderMap = message.getHeaders();
assertThat(message, hasAllHeaders(expectedInHeaderMap));
}
@Test
public void hasAllEntries_withValidKeyValueOrMatcherValue_matches() throws Exception {
Map<String, Object> expectedInHeaderMap = new HashMap<String, Object>();
expectedInHeaderMap.put(ANY_HEADER_KEY, ANY_HEADER_VALUE);
expectedInHeaderMap.put(OTHER_HEADER_KEY, is(OTHER_HEADER_VALUE));
assertThat(message, hasAllHeaders(expectedInHeaderMap));
}
@Test
public void hasAllEntries_withInvalidValidKeyValueOrMatcherValue_notMatching() throws Exception {
Map<String, Object> expectedInHeaderMap = new HashMap<String, Object>();
expectedInHeaderMap.put(ANY_HEADER_KEY, ANY_HEADER_VALUE); // valid
expectedInHeaderMap.put(UNKNOWN_KEY, not(nullValue())); // fails
assertThat(message, not(hasAllHeaders(expectedInHeaderMap)));
expectedInHeaderMap.remove(UNKNOWN_KEY);
expectedInHeaderMap.put(OTHER_HEADER_KEY, ANY_HEADER_VALUE); // fails
}
@Test
public void readableException_singleHeader() throws Exception {
try {
assertThat(message, hasHeader("corn", "bread"));
}
catch (AssertionError ae) {
assertTrue(ae.getMessage().contains("Expected: a Message with Headers containing "));
}
}
@Test
public void readableException_allHeaders() throws Exception {
try {
Map<String, String> entries = new HashMap<String, String>();
entries.put("corn", "bread");
entries.put("chocolate", "pudding");
assertThat(message, hasAllHeaders(entries));
}
catch (AssertionError ae) {
assertTrue(ae.getMessage().contains("Expected: a Message with Headers containing "));
}
}
@Test
public void hasMessageId_sameId() throws Exception {
assertThat(message, hasMessageId(message.getHeaders().getId()));
}
@Test
public void hasCorrelationId_() throws Exception {
UUID correlationId = message.getHeaders().getId();
message = MessageBuilder.withPayload("blabla").setCorrelationId(correlationId).build();
assertThat(message, hasCorrelationId(correlationId));
}
@Test
public void hasSequenceNumber_() throws Exception {
int sequenceNumber = 123;
message = MessageBuilder.fromMessage(message).setSequenceNumber(sequenceNumber).build();
assertThat(message, hasSequenceNumber(sequenceNumber));
}
@Test
public void hasSequenceSize_() throws Exception {
int sequenceSize = 123;
message = MessageBuilder.fromMessage(message).setSequenceSize(sequenceSize).build();
assertThat(message, hasSequenceSize(sequenceSize));
assertThat(message, hasSequenceSize(is(sequenceSize)));
}
@Test
public void hasTimestamp_() throws Exception {
assertThat(message, hasTimestamp(new Date(message.getHeaders().getTimestamp())));
}
@Test
public void hasExpirationDate_() throws Exception {
Matcher<Long> anyMatcher = any(Long.class);
assertThat(message, not(hasExpirationDate(anyMatcher)));
Date expirationDate = new Date(System.currentTimeMillis() + 10000);
message = MessageBuilder.fromMessage(message).setExpirationDate(expirationDate).build();
assertThat(message, hasExpirationDate(expirationDate));
assertThat(message, hasExpirationDate(not(is((System.currentTimeMillis())))));
}
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<int:transformer input-channel="inputChannel" output-channel="outputChannel" expression="payload.toUpperCase()"/>
<int:channel id="outputChannel"/>
<int:transformer input-channel="inputChannel2" output-channel="outputChannel2" expression="payload.toUpperCase()"/>
<int:channel id="outputChannel2">
<int:queue/>
</int:channel>
</beans>

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2002-2015 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
*
* http://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.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeader;
import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload;
import java.util.ArrayList;
import java.util.List;
import org.springframework.integration.test.support.AbstractRequestResponseScenarioTests;
import org.springframework.integration.test.support.MessageValidator;
import org.springframework.integration.test.support.PayloadValidator;
import org.springframework.integration.test.support.RequestResponseScenario;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration
public class MessageScenariosTests extends AbstractRequestResponseScenarioTests {
@Override
protected List<RequestResponseScenario> defineRequestResponseScenarios() {
List<RequestResponseScenario> scenarios= new ArrayList<RequestResponseScenario>();
RequestResponseScenario scenario1 = new RequestResponseScenario(
"inputChannel","outputChannel")
.setPayload("hello")
.setResponseValidator(new PayloadValidator<String>() {
@Override
protected void validateResponse(String response) {
assertEquals("HELLO",response);
}
});
scenarios.add(scenario1);
RequestResponseScenario scenario2 = new RequestResponseScenario(
"inputChannel","outputChannel")
.setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build())
.setResponseValidator(new MessageValidator() {
@Override
protected void validateMessage(Message<?> message) {
assertThat(message,hasPayload("HELLO"));
assertThat(message,hasHeader("foo","bar"));
}
});
scenarios.add(scenario2);
RequestResponseScenario scenario3 = new RequestResponseScenario(
"inputChannel2","outputChannel2")
.setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build())
.setResponseValidator(new MessageValidator() {
@Override
protected void validateMessage(Message<?> message) {
assertThat(message,hasPayload("HELLO"));
assertThat(message,hasHeader("foo","bar"));
}
});
scenarios.add(scenario3);
return scenarios;
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2015 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
*
* http://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.support;
import static org.junit.Assert.assertEquals;
import org.springframework.integration.test.support.PayloadValidator;
import org.springframework.integration.test.support.RequestResponseScenario;
import org.springframework.integration.test.support.SingleRequestResponseScenarioTests;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration("MessageScenariosTests-context.xml")
public class SingleScenarioTests extends SingleRequestResponseScenarioTests {
@Override
protected RequestResponseScenario defineRequestResponseScenario() {
RequestResponseScenario scenario = new RequestResponseScenario(
"inputChannel","outputChannel")
.setPayload("hello")
.setResponseValidator(new PayloadValidator<String>() {
@Override
protected void validateResponse(String response) {
assertEquals("HELLO",response);
}
});
return scenario;
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright 2015 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
*
* http://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.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
/**
* Base class for module tests where logging is set to TRACE for the duration
* of the test and reverted to the previous value. Also logs a start/end
* message. Duplicated from s-i-test to avoid circular dep.
* @author Artem Bilan
* @author Gary Russell
* @since 4.2.2
*
*/
public class LogAdjustingTestSupport {
@Rule
public TestName testName = new TestName();
protected final Log logger = LogFactory.getLog(this.getClass());
private final Collection<Logger> loggersToAdjust = new ArrayList<Logger>();
private final Collection<Level> oldCategories = new ArrayList<Level>();
public LogAdjustingTestSupport() {
this("org.springframework.integration");
}
public LogAdjustingTestSupport(String... loggersToAdjust) {
for (String loggerToAdjust : loggersToAdjust) {
this.loggersToAdjust.add(LogManager.getLogger(loggerToAdjust));
}
}
@Before
public void beforeTest() {
for (Logger loggerToAdjust : this.loggersToAdjust) {
this.oldCategories.add(loggerToAdjust.getEffectiveLevel());
loggerToAdjust.setLevel(Level.TRACE);
}
this.logger.debug("!!!! Starting test: " + this.testName.getMethodName() + " !!!!");
}
@After
public void afterTest() {
logger.debug("!!!! Finished test: " + this.testName.getMethodName() + " !!!!");
Iterator<Level> oldCategory = this.oldCategories.iterator();
for (Logger loggerToAdjust : this.loggersToAdjust) {
loggerToAdjust.setLevel(oldCategory.next());
}
}
}

View File

@@ -1,199 +0,0 @@
/*
* Copyright 2002-2014 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
*
* http://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.util;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import org.hamcrest.Matcher;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.integration.MessageRejectedException;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.endpoint.AbstractEndpoint;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.support.channel.BeanFactoryChannelResolver;
import org.springframework.integration.support.context.NamedComponent;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.Assert;
import org.springframework.util.ErrorHandler;
import org.springframework.util.StringUtils;
/**
* @author Mark Fisher
* @author Iwein Fuld
* @author Oleg Zhurakousky
* @author Artem Bilan
* @author Gary Russell
*/
public abstract class TestUtils {
public static Object getPropertyValue(Object root, String propertyPath) {
Object value = null;
DirectFieldAccessor accessor = new DirectFieldAccessor(root);
String[] tokens = propertyPath.split("\\.");
for (int i = 0; i < tokens.length; i++) {
value = accessor.getPropertyValue(tokens[i]);
if (value != null) {
accessor = new DirectFieldAccessor(value);
} else if (i == tokens.length - 1) {
return null;
} else {
throw new IllegalArgumentException(
"intermediate property '" + tokens[i] + "' is null");
}
}
return value;
}
@SuppressWarnings("unchecked")
public static <T> T getPropertyValue(Object root, String propertyPath, Class<T> type) {
Object value = getPropertyValue(root, propertyPath);
if (value != null) {
Assert.isAssignable(type, value.getClass());
}
return (T) value;
}
public static TestApplicationContext createTestApplicationContext() {
TestApplicationContext context = new TestApplicationContext();
ErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(context));
ThreadPoolTaskScheduler scheduler = createTaskScheduler(10);
scheduler.setErrorHandler(errorHandler);
registerBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, scheduler, context);
return context;
}
public static ThreadPoolTaskScheduler createTaskScheduler(int poolSize) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(poolSize);
scheduler.setRejectedExecutionHandler(new CallerRunsPolicy());
scheduler.afterPropertiesSet();
return scheduler;
}
private static void registerBean(String beanName, Object bean, BeanFactory beanFactory) {
Assert.notNull(beanName, "bean name must not be null");
ConfigurableListableBeanFactory configurableListableBeanFactory = null;
if (beanFactory instanceof ConfigurableListableBeanFactory) {
configurableListableBeanFactory = (ConfigurableListableBeanFactory) beanFactory;
} else if (beanFactory instanceof GenericApplicationContext) {
configurableListableBeanFactory = ((GenericApplicationContext) beanFactory).getBeanFactory();
}
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(beanFactory);
}
if (bean instanceof InitializingBean) {
try {
((InitializingBean) bean).afterPropertiesSet();
}
catch (Exception e) {
throw new FatalBeanException("failed to register bean with test context", e);
}
}
configurableListableBeanFactory.registerSingleton(beanName, bean);
}
public static class TestApplicationContext extends GenericApplicationContext {
private TestApplicationContext() {
super();
}
public void registerChannel(String channelName, MessageChannel channel) {
if (channel instanceof NamedComponent && ((NamedComponent) channel).getComponentName() != null) {
if (channelName == null) {
channelName = ((NamedComponent) channel).getComponentName();
}
else {
Assert.isTrue(((NamedComponent) channel).getComponentName().equals(channelName),
"channel name has already been set with a conflicting value");
}
}
TestUtils.registerBean(channelName, channel, this);
}
public void registerEndpoint(String endpointName, AbstractEndpoint endpoint) {
TestUtils.registerBean(endpointName, endpoint, this);
}
public void registerBean(String beanName, Object bean) {
TestUtils.registerBean(beanName, bean, this);
}
}
@SuppressWarnings("rawtypes")
public static MessageHandler handlerExpecting(final Matcher<Message> messageMatcher) {
return new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
assertThat(message, is(messageMatcher));
}
};
}
/**
* @param history a message history
* @param componentName the name of a component to scan for
* @param startingIndex the index to start scanning
* @return the properties provided by the named component or null if none available
*/
public static Properties locateComponentInHistory(MessageHistory history, String componentName, int startingIndex){
Assert.notNull(history, "'history' must not be null");
Assert.isTrue(StringUtils.hasText(componentName), "'componentName' must be provided");
Assert.isTrue(startingIndex < history.size(), "'startingIndex' can not be greater then size of history");
Properties component = null;
for (int i = startingIndex; i < history.size(); i++) {
Properties properties = history.get(i);
if (componentName.equals(properties.get("name"))){
component = properties;
break;
}
}
return component;
}
/**
* Update file path by replacing any '/' with the system's file separator.
* @param s The file path containing '/'.
* @return The updated file path (if necessary).
*/
public static String applySystemFileSeparator(String s) {
return s.replaceAll("/", java.util.regex.Matcher.quoteReplacement(File.separator));
}
}