moving unit tests from .testsuite -> .jms

This commit is contained in:
Chris Beams
2008-12-17 00:19:07 +00:00
parent 15860b1607
commit 5e0c5a42ad
49 changed files with 1051 additions and 144 deletions

View File

@@ -1,27 +0,0 @@
/*
* Copyright 2002-2007 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.core.task;
/**
* @author Juergen Hoeller
*/
public class StubTaskExecutor implements TaskExecutor {
public void execute(Runnable task) {
}
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2007 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.jca;
import javax.resource.ResourceException;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.InvalidPropertyException;
import javax.resource.spi.ResourceAdapter;
/**
* @author Juergen Hoeller
*/
public class StubActivationSpec implements ActivationSpec {
public void validate() throws InvalidPropertyException {
}
public ResourceAdapter getResourceAdapter() {
return null;
}
public void setResourceAdapter(ResourceAdapter resourceAdapter) throws ResourceException {
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright 2002-2007 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.jca;
import javax.resource.ResourceException;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterInternalException;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.transaction.xa.XAResource;
/**
* @author Juergen Hoeller
*/
public class StubResourceAdapter implements ResourceAdapter {
public void start(BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
}
public void stop() {
}
public void endpointActivation(MessageEndpointFactory messageEndpointFactory, ActivationSpec activationSpec) throws ResourceException {
}
public void endpointDeactivation(MessageEndpointFactory messageEndpointFactory, ActivationSpec activationSpec) {
}
public XAResource[] getXAResources(ActivationSpec[] activationSpecs) throws ResourceException {
return null;
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2002-2007 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.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
/**
* A stub implementation of the JMS ConnectionFactory for testing.
*
* @author Mark Fisher
*/
public class StubConnectionFactory implements ConnectionFactory {
public Connection createConnection() throws JMSException {
return null;
}
public Connection createConnection(String username, String password) throws JMSException {
return null;
}
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright 2002-2007 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.jms;
import javax.jms.Queue;
/**
* Stub implementation of the {@link javax.jms.Queue} interface.
*
* @author Rick Evans
*/
public class StubQueue implements Queue {
public static final String DEFAULT_QUEUE_NAME = "banjo";
private String queueName = DEFAULT_QUEUE_NAME;
public StubQueue() {
}
public StubQueue(String queueName) {
this.queueName = queueName;
}
public String getQueueName() {
return this.queueName;
}
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright 2002-2008 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.jms;
import javax.jms.Topic;
/**
* Stub implementation of the {@link Topic} interface.
*
* @author Rick Evans
*/
public class StubTopic implements Topic {
public static final String DEFAULT_TOPIC_NAME = "banjo";
private String topicName = DEFAULT_TOPIC_NAME;
public StubTopic() {
}
public StubTopic(String topicName) {
this.topicName = topicName;
}
public String getTopicName() {
return this.topicName;
}
}

View File

@@ -1,247 +0,0 @@
/*
* Copyright 2002-2008 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.jms.config;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.ComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.parsing.EmptyReaderEventListener;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jca.endpoint.GenericMessageEndpointManager;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager;
/**
* @author Mark Fisher
* @author Juergen Hoeller
* @author Christian Dupuis
*/
public class JmsNamespaceHandlerTests extends TestCase {
private static final String DEFAULT_CONNECTION_FACTORY = "connectionFactory";
private static final String EXPLICIT_CONNECTION_FACTORY = "testConnectionFactory";
private ToolingTestApplicationContext context;
protected void setUp() throws Exception {
this.context = new ToolingTestApplicationContext("jmsNamespaceHandlerTests.xml", getClass());
}
protected void tearDown() throws Exception {
this.context.close();
}
public void testBeansCreated() {
Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class);
assertEquals("Context should contain 3 JMS listener containers", 3, containers.size());
containers = context.getBeansOfType(GenericMessageEndpointManager.class);
assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size());
}
public void testContainerConfiguration() throws Exception {
Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class);
ConnectionFactory defaultConnectionFactory = (ConnectionFactory) context.getBean(DEFAULT_CONNECTION_FACTORY);
ConnectionFactory explicitConnectionFactory = (ConnectionFactory) context.getBean(EXPLICIT_CONNECTION_FACTORY);
int defaultConnectionFactoryCount = 0;
int explicitConnectionFactoryCount = 0;
Iterator iter = containers.values().iterator();
while (iter.hasNext()) {
DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) iter.next();
if (container.getConnectionFactory().equals(defaultConnectionFactory)) {
defaultConnectionFactoryCount++;
}
else if (container.getConnectionFactory().equals(explicitConnectionFactory)) {
explicitConnectionFactoryCount++;
}
}
assertEquals("1 container should have the default connectionFactory", 1, defaultConnectionFactoryCount);
assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount);
}
public void testListeners() throws Exception {
TestBean testBean1 = (TestBean) context.getBean("testBean1");
TestBean testBean2 = (TestBean) context.getBean("testBean2");
TestMessageListener testBean3 = (TestMessageListener) context.getBean("testBean3");
assertNull(testBean1.getName());
assertNull(testBean2.getName());
assertNull(testBean3.message);
MockControl control1 = MockControl.createControl(TextMessage.class);
TextMessage message1 = (TextMessage) control1.getMock();
control1.expectAndReturn(message1.getText(), "Test1");
control1.replay();
MessageListener listener1 = getListener("listener1");
listener1.onMessage(message1);
assertEquals("Test1", testBean1.getName());
control1.verify();
MockControl control2 = MockControl.createControl(TextMessage.class);
TextMessage message2 = (TextMessage) control2.getMock();
control2.expectAndReturn(message2.getText(), "Test2");
control2.replay();
MessageListener listener2 = getListener("listener2");
listener2.onMessage(message2);
assertEquals("Test2", testBean2.getName());
control2.verify();
MockControl control3 = MockControl.createControl(TextMessage.class);
TextMessage message3 = (TextMessage) control3.getMock();
control3.replay();
MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0");
listener3.onMessage(message3);
assertSame(message3, testBean3.message);
control3.verify();
}
private MessageListener getListener(String containerBeanName) {
DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) this.context.getBean(containerBeanName);
return (MessageListener) container.getMessageListener();
}
public void testComponentRegistration() {
assertTrue("Parser should have registered a component named 'listener1'", context.containsComponentDefinition("listener1"));
assertTrue("Parser should have registered a component named 'listener2'", context.containsComponentDefinition("listener2"));
assertTrue("Parser should have registered a component named 'listener3'", context.containsComponentDefinition("listener3"));
assertTrue("Parser should have registered a component named '" + DefaultMessageListenerContainer.class.getName() + "#0'",
context.containsComponentDefinition(DefaultMessageListenerContainer.class.getName() + "#0"));
assertTrue("Parser should have registered a component named '" + JmsMessageEndpointManager.class.getName() + "#0'",
context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0"));
}
public void testSourceExtraction() {
Iterator iterator = context.getRegisteredComponents();
while (iterator.hasNext()) {
ComponentDefinition compDef = (ComponentDefinition) iterator.next();
if (compDef instanceof CompositeComponentDefinition) {
assertNotNull("CompositeComponentDefinition '" + compDef.getName()+ "' has no source attachment", ((CompositeComponentDefinition) compDef).getSource());
}
validateComponentDefinition(compDef);
}
}
private void validateComponentDefinition(ComponentDefinition compDef) {
BeanDefinition[] beanDefs = compDef.getBeanDefinitions();
for (int i = 0; i < beanDefs.length; i++) {
if (beanDefs[i] instanceof AbstractBeanDefinition) {
assertNotNull("AbstractBeanDefinition has no source attachment", ((AbstractBeanDefinition) beanDefs[i]).getSource());
}
}
}
public static class TestMessageListener implements MessageListener {
public Message message;
public void onMessage(Message message) {
this.message = message;
}
}
/**
* Internal extension that registers a {@link ReaderEventListener} to store
* registered {@link ComponentDefinition}s.
*/
private static class ToolingTestApplicationContext extends ClassPathXmlApplicationContext {
private static final Set REGISTERED_COMPONENTS = new HashSet();
public ToolingTestApplicationContext(String path, Class clazz)
throws BeansException {
super(path, clazz);
}
protected void initBeanDefinitionReader(
XmlBeanDefinitionReader beanDefinitionReader) {
beanDefinitionReader.setEventListener(new StoringReaderEventListener(REGISTERED_COMPONENTS));
beanDefinitionReader.setSourceExtractor(new PassThroughSourceExtractor());
}
public boolean containsComponentDefinition(String name) {
Iterator iterator = REGISTERED_COMPONENTS.iterator();
while (iterator.hasNext()) {
ComponentDefinition cd = (ComponentDefinition) iterator.next();
if (cd instanceof CompositeComponentDefinition) {
ComponentDefinition[] innerCds = ((CompositeComponentDefinition) cd)
.getNestedComponents();
for (int i = 0; i < innerCds.length; i++) {
if (innerCds[i].getName().equals(name)) {
return true;
}
}
}
else {
if (cd.getName().equals(name)) {
return true;
}
}
}
return false;
}
public Iterator getRegisteredComponents() {
return REGISTERED_COMPONENTS.iterator();
}
}
private static class StoringReaderEventListener extends EmptyReaderEventListener {
protected Set registeredComponents = null;
public StoringReaderEventListener(Set registeredComponents) {
this.registeredComponents = registeredComponents;
this.registeredComponents.clear();
}
public void componentRegistered(ComponentDefinition componentDefinition) {
this.registeredComponents.add(componentDefinition);
}
}
}

View File

@@ -1,55 +0,0 @@
<?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:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd">
<jms:listener-container connection-factory="testConnectionFactory" task-executor="testTaskExecutor"
destination-resolver="testDestinationResolver" message-converter="testMessageConverter"
transaction-manager="testTransactionManager">
<jms:listener id="listener1" destination="testDestination" ref="testBean1" method="setName"/>
<jms:listener id="listener2" destination="testDestination" ref="testBean2" method="setName" response-destination="responseDestination"/>
</jms:listener-container>
<jms:listener-container>
<jms:listener destination="testDestination" ref="testBean3"/>
</jms:listener-container>
<jms:jca-listener-container resource-adapter="testResourceAdapter" activation-spec-factory="testActivationSpecFactory"
message-converter="testMessageConverter">
<jms:listener id="listener3" destination="testDestination" ref="testBean1" method="setName"/>
<jms:listener id="listener4" destination="testDestination" ref="testBean2" method="setName" response-destination="responseDestination"/>
</jms:jca-listener-container>
<jms:jca-listener-container activation-spec-factory="testActivationSpecFactory">
<jms:listener destination="testDestination" ref="testBean3"/>
</jms:jca-listener-container>
<!-- the default ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.StubConnectionFactory"/>
<bean id="testConnectionFactory" class="org.springframework.jms.StubConnectionFactory"/>
<!-- the default ResourceAdapter -->
<bean id="resourceAdapter" class="org.springframework.jca.StubResourceAdapter"/>
<bean id="testResourceAdapter" class="org.springframework.jca.StubResourceAdapter"/>
<bean id="testTaskExecutor" class="org.springframework.core.task.StubTaskExecutor"/>
<bean id="testActivationSpecFactory" class="org.springframework.jms.listener.endpoint.StubJmsActivationSpecFactory"/>
<bean id="testDestinationResolver" class="org.springframework.jms.support.destination.DynamicDestinationResolver"/>
<bean id="testMessageConverter" class="org.springframework.jms.support.converter.SimpleMessageConverter102"/>
<bean id="testTransactionManager" class="org.springframework.transaction.CallCountingTransactionManager"/>
<bean id="testBean1" class="org.springframework.beans.TestBean"/>
<bean id="testBean2" class="org.springframework.beans.TestBean"/>
<bean id="testBean3" class="org.springframework.jms.config.JmsNamespaceHandlerTests$TestMessageListener"/>
</beans>

View File

@@ -1,505 +0,0 @@
/*
* Copyright 2002-2008 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.StubQueue;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.JmsTemplate102;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.SessionCallback;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* @author Juergen Hoeller
* @since 26.07.2004
*/
public class JmsTransactionManagerTests extends TestCase {
public void testTransactionCommit() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionRollback() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.rollback();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.rollback(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testParticipatingTransactionWithCommit() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testParticipatingTransactionWithRollbackOnly() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.rollback();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
status.setRollbackOnly();
}
});
try {
tm.commit(ts);
fail("Should have thrown UnexpectedRollbackException");
}
catch (UnexpectedRollbackException ex) {
// expected
}
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testSuspendedTransaction() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
MockControl session2Control = MockControl.createControl(Session.class);
final Session session2 = (Session) session2Control.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 2);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
con.createSession(false, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session2, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
session2.close();
session2Control.setVoidCallable(1);
con.close();
conControl.setVoidCallable(2);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess != session);
return null;
}
});
}
});
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionSuspension() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
MockControl session2Control = MockControl.createControl(Session.class);
final Session session2 = (Session) session2Control.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 2);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session2, 1);
session.commit();
sessionControl.setVoidCallable(1);
session2.commit();
session2Control.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
session2.close();
session2Control.setVoidCallable(1);
con.close();
conControl.setVoidCallable(2);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
final JmsTemplate jt = new JmsTemplate(cf);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess != session);
return null;
}
});
}
});
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommitWithMessageProducer() throws JMSException {
Destination dest = new StubQueue();
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl producerControl = MockControl.createControl(MessageProducer.class);
MessageProducer producer = (MessageProducer) producerControl.getMock();
MockControl messageControl = MockControl.createControl(Message.class);
final Message message = (Message) messageControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.createProducer(dest);
sessionControl.setReturnValue(producer, 1);
producer.send(message);
producerControl.setVoidCallable(1);
session.getTransacted();
sessionControl.setReturnValue(true, 1);
session.commit();
sessionControl.setVoidCallable(1);
producer.close();
producerControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
producerControl.replay();
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager(cf);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate(cf);
jt.send(dest, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return message;
}
});
tm.commit(ts);
producerControl.verify();
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommit102WithQueue() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) sessionControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager102(cf, false);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate102(cf, false);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
public void testTransactionCommit102WithTopic() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
MockControl sessionControl = MockControl.createControl(TopicSession.class);
final TopicSession session = (TopicSession) sessionControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(session, 1);
session.commit();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
sessionControl.replay();
conControl.replay();
cfControl.replay();
JmsTransactionManager tm = new JmsTransactionManager102(cf, true);
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
JmsTemplate jt = new JmsTemplate102(cf, true);
jt.execute(new SessionCallback() {
public Object doInJms(Session sess) {
assertTrue(sess == session);
return null;
}
});
tm.commit(ts);
sessionControl.verify();
conControl.verify();
cfControl.verify();
}
protected void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
}

View File

@@ -1,651 +0,0 @@
/*
* Copyright 2002-2008 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
/**
* @author Juergen Hoeller
* @since 26.07.2004
*/
public class SingleConnectionFactoryTests extends TestCase {
public void testWithConnection() throws JMSException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
Connection con1 = scf.createConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithQueueConnection() throws JMSException {
MockControl conControl = MockControl.createControl(QueueConnection.class);
Connection con = (QueueConnection) conControl.getMock();
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithTopicConnection() throws JMSException {
MockControl conControl = MockControl.createControl(TopicConnection.class);
Connection con = (TopicConnection) conControl.getMock();
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(con);
TopicConnection con1 = scf.createTopicConnection();
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
conControl.verify();
}
public void testWithConnectionFactory() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createQueueConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createQueueConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
Connection con1 = scf.createTopicConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createTopicConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndClientId() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.setClientID("myId");
conControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setClientId("myId");
Connection con1 = scf.createConnection();
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndExceptionListener() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
ExceptionListener listener = new ChainedExceptionListener();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.setExceptionListener(listener);
conControl.setVoidCallable(1);
con.getExceptionListener();
conControl.setReturnValue(listener, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setExceptionListener(listener);
Connection con1 = scf.createConnection();
assertEquals(listener, con1.getExceptionListener());
con1.start();
con1.stop(); // should be ignored
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
con2.start();
con2.stop(); // should be ignored
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testWithConnectionFactoryAndReconnectOnException() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
TestConnection con = new TestConnection();
cf.createConnection();
cfControl.setReturnValue(con, 2);
cfControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setReconnectOnException(true);
Connection con1 = scf.createConnection();
assertNull(con1.getExceptionListener());
con1.start();
con.getExceptionListener().onException(new JMSException(""));
Connection con2 = scf.createConnection();
con2.start();
scf.destroy(); // should trigger actual close
cfControl.verify();
assertEquals(2, con.getStartCount());
assertEquals(2, con.getCloseCount());
}
public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
TestConnection con = new TestConnection();
TestExceptionListener listener = new TestExceptionListener();
cf.createConnection();
cfControl.setReturnValue(con, 2);
cfControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory(cf);
scf.setExceptionListener(listener);
scf.setReconnectOnException(true);
Connection con1 = scf.createConnection();
assertSame(listener, con1.getExceptionListener());
con1.start();
con.getExceptionListener().onException(new JMSException(""));
Connection con2 = scf.createConnection();
con2.start();
scf.destroy(); // should trigger actual close
cfControl.verify();
assertEquals(2, con.getStartCount());
assertEquals(2, con.getCloseCount());
assertEquals(1, listener.getCount());
}
public void testConnectionFactory102WithQueue() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testConnectionFactory102WithTopic() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
SingleConnectionFactory scf = new SingleConnectionFactory102(cf, true);
TopicConnection con1 = scf.createTopicConnection();
con1.start();
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
}
public void testCachingConnectionFactory() throws JMSException {
MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(Session.class);
Session txSession = (Session) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(Session.class);
Session nonTxSession = (Session) nonTxSessionControl.getMock();
cf.createConnection();
cfControl.setReturnValue(con, 1);
con.createSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 2);
txSession.rollback();
txSessionControl.setVoidCallable(1);
txSession.commit();
txSessionControl.setVoidCallable(1);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1.close(); // should lead to rollback
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
Connection con2 = scf.createConnection();
Session session2 = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.commit();
session2.close(); // should be ignored
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(QueueConnection.class);
QueueConnection con = (QueueConnection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(QueueSession.class);
QueueSession txSession = (QueueSession) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(QueueSession.class);
QueueSession nonTxSession = (QueueSession) nonTxSessionControl.getMock();
cf.createQueueConnection();
cfControl.setReturnValue(con, 1);
con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 2);
txSession.rollback();
txSessionControl.setVoidCallable(2);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createQueueConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.rollback();
session1.close(); // should be ignored
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
QueueConnection con2 = scf.createQueueConnection();
Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should lead to rollback
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
MockControl conControl = MockControl.createControl(TopicConnection.class);
TopicConnection con = (TopicConnection) conControl.getMock();
MockControl txSessionControl = MockControl.createControl(TopicSession.class);
TopicSession txSession = (TopicSession) txSessionControl.getMock();
MockControl nonTxSessionControl = MockControl.createControl(TopicSession.class);
TopicSession nonTxSession = (TopicSession) nonTxSessionControl.getMock();
cf.createTopicConnection();
cfControl.setReturnValue(con, 1);
con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
conControl.setReturnValue(txSession, 1);
txSession.getTransacted();
txSessionControl.setReturnValue(true, 4);
txSession.rollback();
txSessionControl.setVoidCallable(2);
txSession.close();
txSessionControl.setVoidCallable(1);
con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
conControl.setReturnValue(nonTxSession, 1);
nonTxSession.close();
nonTxSessionControl.setVoidCallable(1);
con.start();
conControl.setVoidCallable(2);
con.stop();
conControl.setVoidCallable(1);
con.close();
conControl.setVoidCallable(1);
cfControl.replay();
conControl.replay();
txSessionControl.replay();
nonTxSessionControl.replay();
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createTopicConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1.close(); // should lead to rollback
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close(); // should be ignored
con1.start();
con1.close(); // should be ignored
TopicConnection con2 = scf.createTopicConnection();
Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close(); // should be ignored
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should be ignored
con2.start();
con2.close(); // should be ignored
scf.destroy(); // should trigger actual close
cfControl.verify();
conControl.verify();
txSessionControl.verify();
nonTxSessionControl.verify();
}
}

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2002-2006 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.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionConsumer;
import javax.jms.ConnectionMetaData;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.ServerSessionPool;
import javax.jms.Session;
import javax.jms.Topic;
/**
* @author Juergen Hoeller
*/
public class TestConnection implements Connection {
private ExceptionListener exceptionListener;
private int startCount;
private int closeCount;
public Session createSession(boolean b, int i) throws JMSException {
return null;
}
public String getClientID() throws JMSException {
return null;
}
public void setClientID(String paramName) throws JMSException {
}
public ConnectionMetaData getMetaData() throws JMSException {
return null;
}
public ExceptionListener getExceptionListener() throws JMSException {
return exceptionListener;
}
public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
this.exceptionListener = exceptionListener;
}
public void start() throws JMSException {
this.startCount++;
}
public void stop() throws JMSException {
}
public void close() throws JMSException {
this.closeCount++;
}
public ConnectionConsumer createConnectionConsumer(Destination destination, String paramName, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String paramName, String paramName1, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
public int getStartCount() {
return startCount;
}
public int getCloseCount() {
return closeCount;
}
}

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2002-2006 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.jms.connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
/**
* @author Juergen Hoeller
*/
public class TestExceptionListener implements ExceptionListener {
private int count = 0;
public void onException(JMSException ex) {
this.count++;
}
public int getCount() {
return count;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2002-2005 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplate102JtaTests extends JmsTemplate102Tests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return false;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2002-2005 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplate102TransactedTests extends JmsTemplate102Tests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return true;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2002-2005 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplateJtaTests extends JmsTemplateTests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return false;
}
}

View File

@@ -1,847 +0,0 @@
/*
* Copyright 2002-2007 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.jms.core;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.NamingException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.InvalidClientIDException;
import org.springframework.jms.InvalidDestinationException;
import org.springframework.jms.InvalidSelectorException;
import org.springframework.jms.JmsException;
import org.springframework.jms.JmsSecurityException;
import org.springframework.jms.MessageEOFException;
import org.springframework.jms.MessageFormatException;
import org.springframework.jms.MessageNotReadableException;
import org.springframework.jms.MessageNotWriteableException;
import org.springframework.jms.ResourceAllocationException;
import org.springframework.jms.TransactionInProgressException;
import org.springframework.jms.TransactionRolledBackException;
import org.springframework.jms.UncategorizedJmsException;
import org.springframework.jms.connection.ConnectionFactoryUtils;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy;
import org.springframework.jms.support.JmsUtils;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import org.springframework.jndi.JndiTemplate;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Unit tests for the JmsTemplate implemented using JMS 1.1.
*
* @author Andre Biryukov
* @author Mark Pollack
*/
public class JmsTemplateTests extends TestCase {
private Context mockJndiContext;
private MockControl mockJndiControl;
private MockControl connectionFactoryControl;
private ConnectionFactory mockConnectionFactory;
private MockControl connectionControl;
private Connection mockConnection;
private MockControl sessionControl;
private Session mockSession;
private MockControl queueControl;
private Destination mockQueue;
private int deliveryMode = DeliveryMode.PERSISTENT;
private int priority = 9;
private int timeToLive = 10000;
/**
* Create the mock objects for testing.
*/
protected void setUp() throws Exception {
mockJndiControl = MockControl.createControl(Context.class);
mockJndiContext = (Context) this.mockJndiControl.getMock();
createMockforDestination();
mockJndiContext.close();
mockJndiControl.replay();
}
private void createMockforDestination() throws JMSException, NamingException {
connectionFactoryControl = MockControl.createControl(ConnectionFactory.class);
mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock();
connectionControl = MockControl.createControl(Connection.class);
mockConnection = (Connection) connectionControl.getMock();
sessionControl = MockControl.createControl(Session.class);
mockSession = (Session) sessionControl.getMock();
queueControl = MockControl.createControl(Queue.class);
mockQueue = (Queue) queueControl.getMock();
mockConnectionFactory.createConnection();
connectionFactoryControl.setReturnValue(mockConnection);
connectionFactoryControl.replay();
mockConnection.createSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE);
connectionControl.setReturnValue(mockSession);
mockSession.getTransacted();
sessionControl.setReturnValue(useTransactedSession());
mockJndiContext.lookup("testDestination");
mockJndiControl.setReturnValue(mockQueue);
}
private JmsTemplate createTemplate() {
JmsTemplate template = new JmsTemplate();
JndiDestinationResolver destMan = new JndiDestinationResolver();
destMan.setJndiTemplate(new JndiTemplate() {
protected Context createInitialContext() {
return mockJndiContext;
}
});
template.setDestinationResolver(destMan);
template.setSessionTransacted(useTransactedTemplate());
return template;
}
protected boolean useTransactedSession() {
return false;
}
protected boolean useTransactedTemplate() {
return false;
}
public void testExceptionStackTrace() {
JMSException jmsEx = new JMSException("could not connect");
Exception innerEx = new Exception("host not found");
jmsEx.setLinkedException(innerEx);
JmsException springJmsEx = JmsUtils.convertJmsAccessException(jmsEx);
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
springJmsEx.printStackTrace(out);
String trace = sw.toString();
assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0);
}
public void testProducerCallback() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
mockSession.createProducer(null);
sessionControl.setReturnValue(mockMessageProducer);
mockMessageProducer.getPriority();
messageProducerControl.setReturnValue(4);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.execute(new ProducerCallback() {
public Object doInJms(Session session, MessageProducer producer) throws JMSException {
boolean b = session.getTransacted();
int i = producer.getPriority();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
public void testProducerCallbackWithIdAndTimestampDisabled() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageIdEnabled(false);
template.setMessageTimestampEnabled(false);
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
mockSession.createProducer(null);
sessionControl.setReturnValue(mockMessageProducer);
mockMessageProducer.setDisableMessageID(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.setDisableMessageTimestamp(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.getPriority();
messageProducerControl.setReturnValue(4);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.execute(new ProducerCallback() {
public Object doInJms(Session session, MessageProducer producer) throws JMSException {
boolean b = session.getTransacted();
int i = producer.getPriority();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
/**
* Test the method execute(SessionCallback action).
*/
public void testSessionCallback() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
sessionControl.replay();
connectionControl.replay();
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
public void testSessionCallbackWithinSynchronizedTransaction() throws Exception {
SingleConnectionFactory scf = new SingleConnectionFactory(mockConnectionFactory);
JmsTemplate template = createTemplate();
template.setConnectionFactory(scf);
mockConnection.start();
connectionControl.setVoidCallable(3);
// We're gonna call getTransacted 3 times, i.e. 2 more times.
mockSession.getTransacted();
sessionControl.setReturnValue(useTransactedSession(), 2);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.stop();
connectionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
sessionControl.replay();
connectionControl.replay();
TransactionSynchronizationManager.initSynchronization();
try {
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
template.execute(new SessionCallback() {
public Object doInJms(Session session) throws JMSException {
boolean b = session.getTransacted();
return null;
}
});
assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, null, false));
assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false));
TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf);
Connection tac = tacf.createConnection();
Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE);
boolean b = tas.getTransacted();
tas.close();
tac.close();
List synchs = TransactionSynchronizationManager.getSynchronizations();
assertEquals(1, synchs.size());
TransactionSynchronization synch = (TransactionSynchronization) synchs.get(0);
synch.beforeCommit(false);
synch.beforeCompletion();
synch.afterCommit();
synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
finally {
TransactionSynchronizationManager.clearSynchronization();
scf.destroy();
}
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
/**
* Test sending to a destination using the method
* send(Destination d, MessageCreator messageCreator)
*/
public void testSendDestination() throws Exception {
doTestSendDestination(true, false, true, false);
}
/**
* Test seding to a destination using the method
* send(String d, MessageCreator messageCreator)
*/
public void testSendDestinationName() throws Exception {
doTestSendDestination(false, false, true, false);
}
/**
* Test sending to a destination using the method
* send(Destination d, MessageCreator messageCreator) using QOS parameters.
*/
public void testSendDestinationWithQOS() throws Exception {
doTestSendDestination(true, false, false, true);
}
/**
* Test sending to a destination using the method
* send(String d, MessageCreator messageCreator) using QOS parameters.
*/
public void testSendDestinationNameWithQOS() throws Exception {
doTestSendDestination(false, false, false, true);
}
/**
* Test sending to the default destination.
*/
public void testSendDefaultDestination() throws Exception {
doTestSendDestination(true, true, true, true);
}
/**
* Test sending to the default destination name.
*/
public void testSendDefaultDestinationName() throws Exception {
doTestSendDestination(false, true, true, true);
}
/**
* Test sending to the default destination using explicit QOS parameters.
*/
public void testSendDefaultDestinationWithQOS() throws Exception {
doTestSendDestination(true, true, false, false);
}
/**
* Test sending to the default destination name using explicit QOS parameters.
*/
public void testSendDefaultDestinationNameWithQOS() throws Exception {
doTestSendDestination(false, true, false, false);
}
/**
* Common method for testing a send method that uses the MessageCreator
* callback but with different QOS options.
* @param ignoreQOS test using default QOS options.
*/
private void doTestSendDestination(
boolean explicitDestination, boolean useDefaultDestination,
boolean ignoreQOS, boolean disableIdAndTimestamp) throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
String destinationName = "testDestination";
if (useDefaultDestination) {
if (explicitDestination) {
template.setDefaultDestination(mockQueue);
}
else {
template.setDefaultDestinationName(destinationName);
}
}
if (disableIdAndTimestamp) {
template.setMessageIdEnabled(false);
template.setMessageTimestampEnabled(false);
}
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("just testing");
sessionControl.setReturnValue(mockMessage);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
if (disableIdAndTimestamp) {
mockMessageProducer.setDisableMessageID(true);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.setDisableMessageTimestamp(true);
messageProducerControl.setVoidCallable(1);
}
if (ignoreQOS) {
mockMessageProducer.send(mockMessage);
}
else {
template.setExplicitQosEnabled(true);
template.setDeliveryMode(deliveryMode);
template.setPriority(priority);
template.setTimeToLive(timeToLive);
mockMessageProducer.send(mockMessage, deliveryMode, priority, timeToLive);
}
messageProducerControl.setVoidCallable(1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
if (useDefaultDestination) {
template.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
else {
if (explicitDestination) {
template.send(mockQueue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
else {
template.send(destinationName, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
}
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
messageProducerControl.verify();
}
public void testConverter() throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageConverter(new SimpleMessageConverter());
String s = "Hello world";
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("Hello world");
sessionControl.setReturnValue(mockMessage);
mockMessageProducer.send(mockMessage);
messageProducerControl.setVoidCallable(1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
template.convertAndSend(mockQueue, s);
messageProducerControl.verify();
sessionControl.verify();
connectionControl.verify();
connectionFactoryControl.verify();
}
public void testReceiveDefaultDestination() throws Exception {
doTestReceive(true, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDefaultDestinationName() throws Exception {
doTestReceive(false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestination() throws Exception {
doTestReceive(true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestinationWithClientAcknowledge() throws Exception {
doTestReceive(true, false, false, true, false, false, 1000);
}
public void testReceiveDestinationName() throws Exception {
doTestReceive(false, false, false, false, false, true, 1000);
}
public void testReceiveDefaultDestinationWithSelector() throws Exception {
doTestReceive(true, true, false, false, true, true, 1000);
}
public void testReceiveDefaultDestinationNameWithSelector() throws Exception {
doTestReceive(false, true, false, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveDestinationWithSelector() throws Exception {
doTestReceive(true, false, false, false, true, false, 1000);
}
public void testReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception {
doTestReceive(true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveDestinationNameWithSelector() throws Exception {
doTestReceive(false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveAndConvertDefaultDestination() throws Exception {
doTestReceive(true, true, true, false, false, false, 1000);
}
public void testReceiveAndConvertDefaultDestinationName() throws Exception {
doTestReceive(false, true, true, false, false, false, 1000);
}
public void testReceiveAndConvertDestinationName() throws Exception {
doTestReceive(false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveAndConvertDestination() throws Exception {
doTestReceive(true, false, true, false, false, true, 1000);
}
public void testReceiveAndConvertDefaultDestinationWithSelector() throws Exception {
doTestReceive(true, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
}
public void testReceiveAndConvertDestinationNameWithSelector() throws Exception {
doTestReceive(false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT);
}
public void testReceiveAndConvertDestinationWithSelector() throws Exception {
doTestReceive(true, false, true, false, true, false, 1000);
}
private void doTestReceive(
boolean explicitDestination, boolean useDefaultDestination, boolean testConverter,
boolean clientAcknowledge, boolean messageSelector, boolean noLocal, long timeout)
throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
String destinationName = "testDestination";
if (useDefaultDestination) {
if (explicitDestination) {
template.setDefaultDestination(mockQueue);
}
else {
template.setDefaultDestinationName(destinationName);
}
}
if (noLocal) {
template.setPubSubNoLocal(true);
}
template.setReceiveTimeout(timeout);
mockConnection.start();
connectionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class);
MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock();
String selectorString = "selector";
mockSession.createConsumer(mockQueue, messageSelector ? selectorString : null);
sessionControl.setReturnValue(mockMessageConsumer);
if (useTransactedTemplate()) {
mockSession.commit();
sessionControl.setVoidCallable(1);
}
else if (!useTransactedSession()) {
mockSession.getAcknowledgeMode();
if (clientAcknowledge) {
sessionControl.setReturnValue(Session.CLIENT_ACKNOWLEDGE, 1);
}
else {
sessionControl.setReturnValue(Session.AUTO_ACKNOWLEDGE, 1);
}
}
mockSession.close();
sessionControl.setVoidCallable(1);
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
if (testConverter) {
mockMessage.getText();
messageControl.setReturnValue("Hello World!");
}
if (!useTransactedSession() && clientAcknowledge) {
mockMessage.acknowledge();
messageControl.setVoidCallable(1);
}
sessionControl.replay();
connectionControl.replay();
messageControl.replay();
if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) {
mockMessageConsumer.receiveNoWait();
}
else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) {
mockMessageConsumer.receive();
}
else {
mockMessageConsumer.receive(timeout);
}
messageConsumerControl.setReturnValue(mockMessage);
mockMessageConsumer.close();
messageConsumerControl.setVoidCallable(1);
messageConsumerControl.replay();
Message message = null;
String textFromMessage = null;
if (useDefaultDestination) {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(selectorString) :
template.receiveAndConvert());
}
else {
message = (messageSelector ? template.receiveSelected(selectorString) : template.receive());
}
}
else if (explicitDestination) {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(mockQueue, selectorString) :
template.receiveAndConvert(mockQueue));
}
else {
message = (messageSelector ? template.receiveSelected(mockQueue, selectorString) :
template.receive(mockQueue));
}
}
else {
if (testConverter) {
textFromMessage = (String)
(messageSelector ? template.receiveSelectedAndConvert(destinationName, selectorString) :
template.receiveAndConvert(destinationName));
}
else {
message = (messageSelector ? template.receiveSelected(destinationName, selectorString) :
template.receive(destinationName));
}
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
messageConsumerControl.verify();
messageControl.verify();
if (testConverter) {
assertEquals("Message text should be equal", "Hello World!", textFromMessage);
}
else {
assertEquals("Messages should refer to the same object", message, mockMessage);
}
}
public void testIllegalStateException() throws Exception {
doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class);
}
public void testInvalidClientIDException() throws Exception {
doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class);
}
public void testInvalidDestinationException() throws Exception {
doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class);
}
public void testInvalidSelectorException() throws Exception {
doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class);
}
public void testJmsSecurityException() throws Exception {
doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class);
}
public void testMessageEOFException() throws Exception {
doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class);
}
public void testMessageFormatException() throws Exception {
doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class);
}
public void testMessageNotReadableException() throws Exception {
doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class);
}
public void testMessageNotWriteableException() throws Exception {
doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class);
}
public void testResourceAllocationException() throws Exception {
doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class);
}
public void testTransactionInProgressException() throws Exception {
doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class);
}
public void testTransactionRolledBackException() throws Exception {
doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class);
}
public void testUncategorizedJmsException() throws Exception {
doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class);
}
protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(mockConnectionFactory);
template.setMessageConverter(new SimpleMessageConverter());
String s = "Hello world";
MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage mockMessage = (TextMessage) messageControl.getMock();
sessionControl.reset();
mockSession.createProducer(mockQueue);
sessionControl.setReturnValue(mockMessageProducer);
mockSession.createTextMessage("Hello world");
sessionControl.setReturnValue(mockMessage);
mockMessageProducer.send(mockMessage);
messageProducerControl.setThrowable(original, 1);
mockMessageProducer.close();
messageProducerControl.setVoidCallable(1);
mockSession.close();
sessionControl.setVoidCallable(1);
mockConnection.close();
connectionControl.setVoidCallable(1);
messageProducerControl.replay();
sessionControl.replay();
connectionControl.replay();
try {
template.convertAndSend(mockQueue, s);
fail("Should have thrown JmsException");
}
catch (JmsException wrappedEx) {
// expected
assertEquals(thrownExceptionClass, wrappedEx.getClass());
assertEquals(original, wrappedEx.getCause());
}
messageProducerControl.verify();
sessionControl.verify();
connectionControl.verify();
connectionFactoryControl.verify();
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2002-2005 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.jms.core;
/**
* @author Juergen Hoeller
* @since 06.01.2005
*/
public class JmsTemplateTransactedTests extends JmsTemplateTests {
protected boolean useTransactedSession() {
return true;
}
protected boolean useTransactedTemplate() {
return true;
}
}

View File

@@ -1,66 +0,0 @@
/*
* Copyright 2002-2005 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.jms.core.support;
import java.util.ArrayList;
import java.util.List;
import javax.jms.ConnectionFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.core.JmsTemplate;
/**
* @author Mark Pollack
* @since 24.9.2004
*/
public class JmsGatewaySupportTests extends TestCase {
public void testJmsGatewaySupportWithConnectionFactory() throws Exception {
MockControl connectionFactoryControl = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock();
connectionFactoryControl.replay();
final List test = new ArrayList();
JmsGatewaySupport gateway = new JmsGatewaySupport() {
protected void initGateway() {
test.add("test");
}
};
gateway.setConnectionFactory(mockConnectionFactory);
gateway.afterPropertiesSet();
assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory());
assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory());
assertEquals("initGatway called", test.size(), 1);
connectionFactoryControl.verify();
}
public void testJmsGatewaySupportWithJmsTemplate() throws Exception {
JmsTemplate template = new JmsTemplate();
final List test = new ArrayList();
JmsGatewaySupport gateway = new JmsGatewaySupport() {
protected void initGateway() {
test.add("test");
}
};
gateway.setJmsTemplate(template);
gateway.afterPropertiesSet();
assertEquals("Correct JmsTemplate", template, gateway.getJmsTemplate());
assertEquals("initGateway called", test.size(), 1);
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2002-2006 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.jms.listener;
import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
/**
* Unit tests for the {@link AbstractMessageListenerContainer} class.
*
* @author Rick Evans
*/
public abstract class AbstractMessageListenerContainerTests extends TestCase {
protected abstract AbstractMessageListenerContainer getContainer();
public void testSettingMessageListenerToANullType() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
getContainer().setMessageListener(null);
}
}.runTest();
}
public void testSettingMessageListenerToAnUnsupportedType() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
getContainer().setMessageListener("Bingo");
}
}.runTest();
}
}

View File

@@ -1,607 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener;
import java.util.HashSet;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.easymock.MockControl;
import org.easymock.internal.AlwaysMatcher;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jms.StubQueue;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class SimpleMessageListenerContainerTests extends AbstractMessageListenerContainerTests {
private static final String DESTINATION_NAME = "foo";
private static final String EXCEPTION_MESSAGE = "This.Is.It";
private static final StubQueue QUEUE_DESTINATION = new StubQueue();
private SimpleMessageListenerContainer container;
protected void setUp() throws Exception {
this.container = (SimpleMessageListenerContainer) getContainer();
}
protected AbstractMessageListenerContainer getContainer() {
return new SimpleMessageListenerContainer();
}
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
assertFalse("The [pubSubLocal] property of SimpleMessageListenerContainer " +
"must default to false. Change this test (and the " +
"attendant Javadoc) if you have changed the default.",
container.isPubSubNoLocal());
}
public void testSettingConcurrentConsumersToZeroIsNotAllowed() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
container.setConcurrentConsumers(0);
container.afterPropertiesSet();
}
}.runTest();
}
public void testSettingConcurrentConsumersToANegativeValueIsNotAllowed() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
container.setConcurrentConsumers(-198);
container.afterPropertiesSet();
}
}.runTest();
}
public void testInitDoesNotStartTheConnectionIfAutoStartIsSetToFalse() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.setAutoStartup(false);
this.container.afterPropertiesSet();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testInitStartsTheConnectionByDefault() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.afterPropertiesSet();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
session.getAcknowledgeMode();
mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final HashSet failure = new HashSet();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener() {
public void onMessage(Message message, Session sess) {
try {
// Check correct Session passed into SessionAwareMessageListener.
assertSame(sess, session);
}
catch (Throwable ex) {
failure.add("MessageListener execution failed: " + ex);
}
}
});
this.container.afterPropertiesSet();
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
messageConsumer.sendMessage(message);
if (!failure.isEmpty()) {
fail(failure.iterator().next().toString());
}
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testTaskExecutorCorrectlyInvokedWhenSpecified() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
session.getTransacted();
mockSession.setReturnValue(false);
session.getAcknowledgeMode();
mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final TestMessageListener listener = new TestMessageListener();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(listener);
this.container.setTaskExecutor(new TaskExecutor() {
public void execute(Runnable task) {
listener.executorInvoked = true;
assertFalse(listener.listenerInvoked);
task.run();
assertTrue(listener.listenerInvoked);
}
});
this.container.afterPropertiesSet();
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
messageConsumer.sendMessage(message);
assertTrue(listener.executorInvoked);
assertTrue(listener.listenerInvoked);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testRegisteredExceptionListenerIsInvokedOnException() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
final JMSException theException = new JMSException(EXCEPTION_MESSAGE);
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener() {
public void onMessage(Message message, Session session) throws JMSException {
throw theException;
}
});
MockControl mockExceptionListener = MockControl.createControl(ExceptionListener.class);
ExceptionListener exceptionListener = (ExceptionListener) mockExceptionListener.getMock();
exceptionListener.onException(theException);
mockExceptionListener.setVoidCallable();
mockExceptionListener.replay();
this.container.setExceptionListener(exceptionListener);
this.container.afterPropertiesSet();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockExceptionListener.verify();
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(false);
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillDo_NOT_Propagate() throws Exception {
this.container.setSessionTransacted(true);
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
session.getTransacted();
mockSession.setReturnValue(true);
// Session is rolled back 'cos it is transacted...
session.rollback();
mockSession.setVoidCallable();
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
// manually trigger an Exception with the above bad MessageListener...
MockControl mockMessage = MockControl.createControl(Message.class);
final Message message = (Message) mockMessage.getMock();
mockMessage.replay();
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
mockMessage.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws Exception {
MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class);
MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock();
messageConsumer.setMessageListener(null);
// anon. inner class passed in, so just expect a call...
mockMessageConsumer.setMatcher(new AlwaysMatcher());
mockMessageConsumer.setVoidCallable();
// closing down...
messageConsumer.close();
mockMessageConsumer.setVoidCallable();
mockMessageConsumer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
// Queue gets created in order to create MessageConsumer for that Destination...
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector...
mockSession.setReturnValue(messageConsumer);
// closing down...
session.close();
mockSession.setVoidCallable();
mockSession.replay();
MockControl mockConnection = MockControl.createControl(Connection.class);
Connection connection = (Connection) mockConnection.getMock();
connection.setExceptionListener(this.container);
mockConnection.setVoidCallable();
// session gets created in order to register MessageListener...
connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode());
mockConnection.setReturnValue(session);
// and the connection is start()ed after the listener is registered...
connection.start();
mockConnection.setVoidCallable();
// closing down...
connection.close();
mockConnection.setVoidCallable();
mockConnection.replay();
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
connectionFactory.createConnection();
mockConnectionFactory.setReturnValue(connection);
mockConnectionFactory.replay();
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.afterPropertiesSet();
this.container.destroy();
mockMessageConsumer.verify();
mockSession.verify();
mockConnection.verify();
mockConnectionFactory.verify();
}
private static class TestMessageListener implements MessageListener {
public boolean executorInvoked = false;
public boolean listenerInvoked = false;
public void onMessage(Message message) {
this.listenerInvoked = true;
}
}
private static class SimpleMessageConsumer implements MessageConsumer {
private MessageListener messageListener;
public void sendMessage(Message message) throws JMSException {
this.messageListener.onMessage(message);
}
public String getMessageSelector() throws JMSException {
throw new UnsupportedOperationException();
}
public MessageListener getMessageListener() throws JMSException {
return this.messageListener;
}
public void setMessageListener(MessageListener messageListener) throws JMSException {
this.messageListener = messageListener;
}
public Message receive() throws JMSException {
throw new UnsupportedOperationException();
}
public Message receive(long l) throws JMSException {
throw new UnsupportedOperationException();
}
public Message receiveNoWait() throws JMSException {
throw new UnsupportedOperationException();
}
public void close() throws JMSException {
throw new UnsupportedOperationException();
}
}
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener.adapter;
import java.util.Map;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
* @author Juergen Hoeller
*/
public interface MessageContentsDelegate {
void handleMessage(CharSequence message);
void handleMessage(Map message);
void handleMessage(byte[] message);
void handleMessage(Number message);
void handleMessage(Object message);
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener.adapter;
import javax.jms.BytesMessage;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface MessageDelegate {
void handleMessage(TextMessage message);
void handleMessage(MapMessage message);
void handleMessage(BytesMessage message);
void handleMessage(ObjectMessage message);
}

View File

@@ -1,432 +0,0 @@
/*
* Copyright 2002-2006 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.jms.listener.adapter;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.support.converter.SimpleMessageConverter102;
import org.springframework.test.AssertThrows;
import javax.jms.*;
/**
* Unit tests for the {@link MessageListenerAdapter102} class.
*
* @author Rick Evans
*/
public final class MessageListenerAdapter102Tests extends TestCase {
private static final String TEXT = "The Runaways";
private static final String CORRELATION_ID = "100";
private static final String RESPONSE_TEXT = "Old Lace";
public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock();
// BytesMessage contents must be unwrapped...
bytesMessage.readBytes(null);
mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER);
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
mockBytesMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT.getBytes());
mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
adapter.onMessage(bytesMessage);
mockDelegate.verify();
mockBytesMessage.verify();
}
public void testWithMessageDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter102() throws Exception {
MessageListenerAdapter102 adapter = new MessageListenerAdapter102();
assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter());
assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter102]; if you've just changed it, then change this test to reflect your change.", adapter.getMessageConverter() instanceof SimpleMessageConverter102);
}
public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setReturnValue(TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForQueue() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForTopic() throws Exception {
MockControl mockDestination = MockControl.createControl(Topic.class);
Topic destination = (Topic) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockTopicPublisher = MockControl.createControl(TopicPublisher.class);
TopicPublisher topicPublisher = (TopicPublisher) mockTopicPublisher.getMock();
topicPublisher.publish(responseTextMessage);
mockTopicPublisher.setVoidCallable();
topicPublisher.close();
mockTopicPublisher.setVoidCallable();
mockTopicPublisher.replay();
MockControl mockSession = MockControl.createControl(TopicSession.class);
TopicSession session = (TopicSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createPublisher(destination);
mockSession.setReturnValue(topicPublisher);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockTopicPublisher.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(InvalidDestinationException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setThrowable(new JMSException("Dow!"));
// ensure that regardless of a JMSException the producer is closed...
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createSender(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(JMSException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
mockSentTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setThrowable(new IllegalArgumentException("Dow!"));
mockDelegate.replay();
final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(ListenerExecutionFailedException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
}
}

View File

@@ -1,657 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener.adapter;
import java.io.Serializable;
import javax.jms.BytesMessage;
import javax.jms.IllegalStateException;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class MessageListenerAdapterTests extends TestCase {
private static final String TEXT = "I fancy a good cuppa right now";
private static final Integer NUMBER = new Integer(1);
private static final SerializableObject OBJECT = new SerializableObject();
private static final String CORRELATION_ID = "100";
private static final String RESPONSE_TEXT = "... wi' some full fat creamy milk. Top banana.";
public void testWithMessageContentsDelegateForTextMessage() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class);
BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock();
// BytesMessage contents must be unwrapped...
bytesMessage.getBodyLength();
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
bytesMessage.readBytes(null);
mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER);
mockBytesMessage.setReturnValue(TEXT.getBytes().length);
mockBytesMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(TEXT.getBytes());
mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(bytesMessage);
mockDelegate.verify();
mockBytesMessage.verify();
}
public void testWithMessageContentsDelegateForObjectMessage() throws Exception {
MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class);
ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock();
objectMessage.getObject();
mockObjectMessage.setReturnValue(NUMBER);
mockObjectMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(NUMBER);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(objectMessage);
mockDelegate.verify();
mockObjectMessage.verify();
}
public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class);
ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock();
objectMessage.getObject();
mockObjectMessage.setReturnValue(OBJECT);
mockObjectMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class);
MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock();
delegate.handleMessage(OBJECT);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
adapter.onMessage(objectMessage);
mockDelegate.verify();
mockObjectMessage.verify();
}
public void testWithMessageDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setVoidCallable();
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testWhenTheAdapterItselfIsTheDelegate() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
adapter.onMessage(textMessage);
assertTrue(adapter.wasCalled());
mockTextMessage.verify();
}
public void testRainyDayWithNoApplicableHandlingMethods() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
// TextMessage contents must be unwrapped...
textMessage.getText();
mockTextMessage.setReturnValue(TEXT);
mockTextMessage.replay();
StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
adapter.setDefaultListenerMethod("walnutsRock");
adapter.onMessage(textMessage);
assertFalse(adapter.wasCalled());
mockTextMessage.verify();
}
public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception {
final IllegalArgumentException exception = new IllegalArgumentException();
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(MessageDelegate.class);
MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setThrowable(exception);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected void handleListenerException(Throwable ex) {
assertNotNull("The Throwable passed to the handleListenerException(..) method must never be null.", ex);
assertTrue("The Throwable passed to the handleListenerException(..) method must be of type [ListenerExecutionFailedException].",
ex instanceof ListenerExecutionFailedException);
ListenerExecutionFailedException lefx = (ListenerExecutionFailedException) ex;
Throwable cause = lefx.getCause();
assertNotNull("The cause of a ListenerExecutionFailedException must be preserved.", cause);
assertSame(exception, cause);
}
};
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter());
assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter]",
adapter.getMessageConverter() instanceof SimpleMessageConverter);
}
public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertSame(adapter, adapter.getDelegate());
}
public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertEquals(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD, adapter.getDefaultListenerMethod());
}
public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
MockControl mockTextMessage = MockControl.createControl(TextMessage.class);
TextMessage textMessage = (TextMessage) mockTextMessage.getMock();
mockTextMessage.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(textMessage);
mockDelegate.setReturnValue(TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
// we DON'T want the default SimpleMessageConversion happening...
adapter.setMessageConverter(null);
adapter.onMessage(textMessage);
mockDelegate.verify();
mockTextMessage.verify();
}
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null); // we want to fall back to the default...
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseTextMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setDefaultResponseDestination(destination);
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockQueueSender.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(null);
sentTextMessage.getJMSMessageID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class);
MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock();
messageProducer.send(responseTextMessage);
mockMessageProducer.setVoidCallable();
messageProducer.close();
mockMessageProducer.setVoidCallable();
mockMessageProducer.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(messageProducer);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.onMessage(sentTextMessage, session);
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockMessageProducer.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(null);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(InvalidDestinationException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
}
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class);
TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock();
responseTextMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseTextMessage.setVoidCallable();
mockResponseTextMessage.replay();
MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class);
MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock();
messageProducer.send(responseTextMessage);
mockMessageProducer.setThrowable(new JMSException("Dow!"));
// ensure that regardless of a JMSException the producer is closed...
messageProducer.close();
mockMessageProducer.setVoidCallable();
mockMessageProducer.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
session.createTextMessage(RESPONSE_TEXT);
mockSession.setReturnValue(responseTextMessage);
session.createProducer(destination);
mockSession.setReturnValue(messageProducer);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(JMSException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockResponseTextMessage.verify();
mockSession.verify();
mockDestination.verify();
mockMessageProducer.verify();
}
public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
mockMessage.replay();
MockControl mockSession = MockControl.createControl(QueueSession.class);
final QueueSession session = (QueueSession) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(message);
mockDelegate.setThrowable(new IllegalArgumentException("Dow!"));
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
new AssertThrows(ListenerExecutionFailedException.class) {
public void test() throws Exception {
adapter.onMessage(message, session);
}
}.runTest();
mockDelegate.verify();
mockMessage.verify();
mockSession.verify();
}
public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
message.getText();
mockMessage.setReturnValue(TEXT);
mockMessage.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter() {
protected void handleListenerException(Throwable ex) {
assertTrue(ex instanceof IllegalStateException);
}
};
adapter.setDefaultListenerMethod(null);
adapter.onMessage(message);
mockMessage.verify();
}
public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception {
MockControl mockMessage = MockControl.createControl(TextMessage.class);
final TextMessage message = (TextMessage) mockMessage.getMock();
message.getText();
mockMessage.setReturnValue(TEXT);
mockMessage.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter() {
protected void handleListenerException(Throwable ex) {
assertTrue(ex instanceof javax.jms.IllegalStateException);
}
protected String getListenerMethodName(Message originalMessage, Object extractedMessage) {
return null;
}
};
adapter.setDefaultListenerMethod(null);
adapter.onMessage(message);
mockMessage.verify();
}
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
mockSentTextMessage.replay();
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class);
ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(RESPONSE_TEXT);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setMessageConverter(null);
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
adapter.onMessage(sentTextMessage, session);
}
}.runTest();
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
}
public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
MockControl mockDestination = MockControl.createControl(Queue.class);
Queue destination = (Queue) mockDestination.getMock();
mockDestination.replay();
MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class);
final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock();
// correlation ID is queried when response is being created...
sentTextMessage.getJMSCorrelationID();
mockSentTextMessage.setReturnValue(CORRELATION_ID);
// Reply-To is queried when response is being created...
sentTextMessage.getJMSReplyTo();
mockSentTextMessage.setReturnValue(destination);
mockSentTextMessage.replay();
MockControl mockResponseMessage = MockControl.createControl(TextMessage.class);
TextMessage responseMessage = (TextMessage) mockResponseMessage.getMock();
responseMessage.setJMSCorrelationID(CORRELATION_ID);
mockResponseMessage.setVoidCallable();
mockResponseMessage.replay();
MockControl mockQueueSender = MockControl.createControl(QueueSender.class);
QueueSender queueSender = (QueueSender) mockQueueSender.getMock();
queueSender.send(responseMessage);
mockQueueSender.setVoidCallable();
queueSender.close();
mockQueueSender.setVoidCallable();
mockQueueSender.replay();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createProducer(destination);
mockSession.setReturnValue(queueSender);
mockSession.replay();
MockControl mockDelegate = MockControl.createControl(ResponsiveJmsTextMessageReturningMessageDelegate.class);
ResponsiveJmsTextMessageReturningMessageDelegate delegate = (ResponsiveJmsTextMessageReturningMessageDelegate) mockDelegate.getMock();
delegate.handleMessage(sentTextMessage);
mockDelegate.setReturnValue(responseMessage);
mockDelegate.replay();
final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
protected Object extractMessage(Message message) {
return message;
}
};
adapter.setMessageConverter(null);
adapter.onMessage(sentTextMessage, session);
mockDestination.verify();
mockDelegate.verify();
mockSentTextMessage.verify();
mockSession.verify();
mockQueueSender.verify();
mockResponseMessage.verify();
}
private static class SerializableObject implements Serializable {
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener.adapter;
import javax.jms.TextMessage;
import javax.jms.MapMessage;
import javax.jms.BytesMessage;
import javax.jms.ObjectMessage;
import java.util.Map;
import java.io.Serializable;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface ResponsiveJmsTextMessageReturningMessageDelegate {
TextMessage handleMessage(TextMessage message);
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2008 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.jms.listener.adapter;
import java.io.Serializable;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
/**
* See the MessageListenerAdapterTests class for usage.
*
* @author Rick Evans
*/
public interface ResponsiveMessageDelegate {
String handleMessage(TextMessage message);
Map handleMessage(MapMessage message);
byte[] handleMessage(BytesMessage message);
Serializable handleMessage(ObjectMessage message);
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2007 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.jms.listener.adapter;
/**
* Stub extension of the {@link MessageListenerAdapter} class for use in testing.
*
* @author Rick Evans
*/
public class StubMessageListenerAdapter extends MessageListenerAdapter {
private boolean wasCalled;
public boolean wasCalled() {
return this.wasCalled;
}
public void handleMessage(String message) {
this.wasCalled = true;
}
protected void handleListenerException(Throwable ex) {
System.out.println(ex);
}
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2007 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.jms.listener.adapter;
/**
* Stub extension of the {@link MessageListenerAdapter102} class for use in testing.
*
* @author Rick Evans
*/
public class StubMessageListenerAdapter102 extends MessageListenerAdapter102 {
private boolean wasCalled;
public boolean wasCalled() {
return this.wasCalled;
}
public void handleMessage(String message) {
this.wasCalled = true;
}
protected void handleListenerException(Throwable ex) {
System.out.println(ex);
}
}

View File

@@ -1,168 +0,0 @@
/*
* Copyright 2002-2007 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.jms.listener.endpoint;
import javax.jms.Destination;
import javax.jms.Session;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jca.StubResourceAdapter;
import org.springframework.jms.StubQueue;
import org.springframework.jms.support.destination.DestinationResolver;
/**
* @author Agim Emruli
* @author Juergen Hoeller
*/
public class DefaultJmsActivationSpecFactoryTests extends TestCase {
private JmsActivationSpecConfig activationSpecConfig;
protected void setUp() throws Exception {
activationSpecConfig = new JmsActivationSpecConfig();
activationSpecConfig.setMaxConcurrency(5);
activationSpecConfig.setPrefetchSize(3);
activationSpecConfig.setAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
activationSpecConfig.setClientId("clientid");
activationSpecConfig.setDestinationName("destinationname");
activationSpecConfig.setDurableSubscriptionName("durableSubscriptionName");
activationSpecConfig.setMessageSelector("selector");
}
public void testActiveMQResourceAdapterSetup() {
activationSpecConfig.setAcknowledgeMode(Session.SESSION_TRANSACTED);
JmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory();
StubActiveMQActivationSpec spec = (StubActiveMQActivationSpec) activationSpecFactory.createActivationSpec(
new StubActiveMQResourceAdapter(), activationSpecConfig);
assertEquals(5, spec.getMaxSessions());
assertEquals(3, spec.getMaxMessagesPerSessions());
assertTrue(spec.isUseRAManagedTransaction());
}
public void testWebSphereResourceAdapterSetup() throws Exception {
Destination destination = new StubQueue();
MockControl control = MockControl.createControl(DestinationResolver.class);
DestinationResolver destinationResolver = (DestinationResolver) control.getMock();
destinationResolver.resolveDestinationName(null, "destinationname", false);
control.setReturnValue(destination);
control.replay();
DefaultJmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory();
activationSpecFactory.setDestinationResolver(destinationResolver);
StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory
.createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig);
control.verify();
assertEquals(destination, spec.getDestination());
assertEquals(5, spec.getMaxConcurrency());
assertEquals(3, spec.getMaxBatchSize());
}
private static class StubActiveMQResourceAdapter extends StubResourceAdapter {
}
private static class StubWebSphereResourceAdapterImpl extends StubResourceAdapter {
}
private static class StubActiveMQActivationSpec extends StubJmsActivationSpec {
private int maxSessions;
private int maxMessagesPerSessions;
private String destination;
private boolean useRAManagedTransaction;
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public void setMaxMessagesPerSessions(int maxMessagesPerSessions) {
this.maxMessagesPerSessions = maxMessagesPerSessions;
}
public int getMaxSessions() {
return maxSessions;
}
public int getMaxMessagesPerSessions() {
return maxMessagesPerSessions;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public boolean isUseRAManagedTransaction() {
return useRAManagedTransaction;
}
public void setUseRAManagedTransaction(boolean useRAManagedTransaction) {
this.useRAManagedTransaction = useRAManagedTransaction;
}
}
private static class StubWebSphereActivationSpecImpl extends StubJmsActivationSpec {
private Destination destination;
private int maxConcurrency;
private int maxBatchSize;
public void setDestination(Destination destination) {
this.destination = destination;
}
public Destination getDestination() {
return destination;
}
public int getMaxConcurrency() {
return maxConcurrency;
}
public void setMaxConcurrency(int maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
public int getMaxBatchSize() {
return maxBatchSize;
}
public void setMaxBatchSize(int maxBatchSize) {
this.maxBatchSize = maxBatchSize;
}
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2002-2007 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.jms.listener.endpoint;
import javax.jms.Destination;
import org.springframework.jca.StubActivationSpec;
/**
* StubActivationSpec which implements all required and optional properties (see
* specification Appendix B.2) except the destination attribute. Because this
* can be a string but also an {@link Destination} object, which is configured
* as an administrated object.
*
* @author Agim Emruli
*/
public class StubJmsActivationSpec extends StubActivationSpec {
private String destinationType;
private String subscriptionDurability;
private String subscriptionName;
private String clientId;
private String messageSelector;
private String acknowledgeMode;
public String getDestinationType() {
return destinationType;
}
public void setDestinationType(String destinationType) {
this.destinationType = destinationType;
}
public String getSubscriptionDurability() {
return subscriptionDurability;
}
public void setSubscriptionDurability(String subscriptionDurability) {
this.subscriptionDurability = subscriptionDurability;
}
public String getSubscriptionName() {
return subscriptionName;
}
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getMessageSelector() {
return messageSelector;
}
public void setMessageSelector(String messageSelector) {
this.messageSelector = messageSelector;
}
public String getAcknowledgeMode() {
return acknowledgeMode;
}
public void setAcknowledgeMode(String acknowledgeMode) {
this.acknowledgeMode = acknowledgeMode;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2002-2007 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.jms.listener.endpoint;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.ResourceAdapter;
import org.springframework.jca.StubActivationSpec;
/**
* @author Juergen Hoeller
*/
public class StubJmsActivationSpecFactory implements JmsActivationSpecFactory {
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
return new StubActivationSpec();
}
}

View File

@@ -1,414 +0,0 @@
/*
* Copyright 2002-2007 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.jms.remoting;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Enumeration;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
/**
* @author Juergen Hoeller
*/
public class JmsInvokerTests extends TestCase {
private MockControl connectionFactoryControl;
private QueueConnectionFactory mockConnectionFactory;
private MockControl connectionControl;
private QueueConnection mockConnection;
private MockControl sessionControl;
private QueueSession mockSession;
private MockControl queueControl;
private Queue mockQueue;
protected void setUp() throws Exception {
connectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class);
mockConnectionFactory = (QueueConnectionFactory) connectionFactoryControl.getMock();
connectionControl = MockControl.createControl(QueueConnection.class);
mockConnection = (QueueConnection) connectionControl.getMock();
sessionControl = MockControl.createControl(QueueSession.class);
mockSession = (QueueSession) sessionControl.getMock();
queueControl = MockControl.createControl(Queue.class);
mockQueue = (Queue) queueControl.getMock();
mockConnectionFactory.createQueueConnection();
connectionFactoryControl.setReturnValue(mockConnection, 8);
mockConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
connectionControl.setReturnValue(mockSession, 8);
mockConnection.start();
connectionControl.setVoidCallable(8);
connectionFactoryControl.replay();
connectionControl.replay();
}
public void testJmsInvokerProxyFactoryBeanAndServiceExporter() throws Throwable {
sessionControl.replay();
doTestJmsInvokerProxyFactoryBeanAndServiceExporter(false);
}
public void testJmsInvokerProxyFactoryBeanAndServiceExporterWithDynamicQueue() throws Throwable {
mockSession.createQueue("myQueue");
sessionControl.setReturnValue(mockQueue, 8);
sessionControl.replay();
doTestJmsInvokerProxyFactoryBeanAndServiceExporter(true);
}
private void doTestJmsInvokerProxyFactoryBeanAndServiceExporter(boolean dynamicQueue) throws Throwable {
TestBean target = new TestBean("myname", 99);
final JmsInvokerServiceExporter exporter = new JmsInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setMessageConverter(new MockSimpleMessageConverter());
exporter.afterPropertiesSet();
JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() {
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
MockControl exporterSessionControl = MockControl.createControl(Session.class);
Session mockExporterSession = (Session) exporterSessionControl.getMock();
ResponseStoringProducer mockProducer = new ResponseStoringProducer();
mockExporterSession.createProducer(requestMessage.getJMSReplyTo());
exporterSessionControl.setReturnValue(mockProducer);
exporterSessionControl.replay();
exporter.onMessage(requestMessage, mockExporterSession);
exporterSessionControl.verify();
assertTrue(mockProducer.closed);
return mockProducer.response;
}
};
pfb.setServiceInterface(ITestBean.class);
pfb.setConnectionFactory(this.mockConnectionFactory);
if (dynamicQueue) {
pfb.setQueueName("myQueue");
}
else {
pfb.setQueue(this.mockQueue);
}
pfb.setMessageConverter(new MockSimpleMessageConverter());
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
proxy.setStringArray(new String[] {"str1", "str2"});
assertTrue(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray()));
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
connectionFactoryControl.verify();
connectionControl.verify();
sessionControl.verify();
}
private static class ResponseStoringProducer implements MessageProducer {
public Message response;
public boolean closed = false;
public void setDisableMessageID(boolean b) throws JMSException {
}
public boolean getDisableMessageID() throws JMSException {
return false;
}
public void setDisableMessageTimestamp(boolean b) throws JMSException {
}
public boolean getDisableMessageTimestamp() throws JMSException {
return false;
}
public void setDeliveryMode(int i) throws JMSException {
}
public int getDeliveryMode() throws JMSException {
return 0;
}
public void setPriority(int i) throws JMSException {
}
public int getPriority() throws JMSException {
return 0;
}
public void setTimeToLive(long l) throws JMSException {
}
public long getTimeToLive() throws JMSException {
return 0;
}
public Destination getDestination() throws JMSException {
return null;
}
public void close() throws JMSException {
this.closed = true;
}
public void send(Message message) throws JMSException {
this.response = message;
}
public void send(Message message, int i, int i1, long l) throws JMSException {
}
public void send(Destination destination, Message message) throws JMSException {
}
public void send(Destination destination, Message message, int i, int i1, long l) throws JMSException {
}
}
private static class MockObjectMessage implements ObjectMessage {
private Serializable serializable;
private Destination replyTo;
public MockObjectMessage(Serializable serializable) {
this.serializable = serializable;
}
public void setObject(Serializable serializable) throws JMSException {
this.serializable = serializable;
}
public Serializable getObject() throws JMSException {
return serializable;
}
public String getJMSMessageID() throws JMSException {
return null;
}
public void setJMSMessageID(String string) throws JMSException {
}
public long getJMSTimestamp() throws JMSException {
return 0;
}
public void setJMSTimestamp(long l) throws JMSException {
}
public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
return new byte[0];
}
public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException {
}
public void setJMSCorrelationID(String string) throws JMSException {
}
public String getJMSCorrelationID() throws JMSException {
return null;
}
public Destination getJMSReplyTo() throws JMSException {
return replyTo;
}
public void setJMSReplyTo(Destination destination) throws JMSException {
this.replyTo = destination;
}
public Destination getJMSDestination() throws JMSException {
return null;
}
public void setJMSDestination(Destination destination) throws JMSException {
}
public int getJMSDeliveryMode() throws JMSException {
return 0;
}
public void setJMSDeliveryMode(int i) throws JMSException {
}
public boolean getJMSRedelivered() throws JMSException {
return false;
}
public void setJMSRedelivered(boolean b) throws JMSException {
}
public String getJMSType() throws JMSException {
return null;
}
public void setJMSType(String string) throws JMSException {
}
public long getJMSExpiration() throws JMSException {
return 0;
}
public void setJMSExpiration(long l) throws JMSException {
}
public int getJMSPriority() throws JMSException {
return 0;
}
public void setJMSPriority(int i) throws JMSException {
}
public void clearProperties() throws JMSException {
}
public boolean propertyExists(String string) throws JMSException {
return false;
}
public boolean getBooleanProperty(String string) throws JMSException {
return false;
}
public byte getByteProperty(String string) throws JMSException {
return 0;
}
public short getShortProperty(String string) throws JMSException {
return 0;
}
public int getIntProperty(String string) throws JMSException {
return 0;
}
public long getLongProperty(String string) throws JMSException {
return 0;
}
public float getFloatProperty(String string) throws JMSException {
return 0;
}
public double getDoubleProperty(String string) throws JMSException {
return 0;
}
public String getStringProperty(String string) throws JMSException {
return null;
}
public Object getObjectProperty(String string) throws JMSException {
return null;
}
public Enumeration getPropertyNames() throws JMSException {
return null;
}
public void setBooleanProperty(String string, boolean b) throws JMSException {
}
public void setByteProperty(String string, byte b) throws JMSException {
}
public void setShortProperty(String string, short i) throws JMSException {
}
public void setIntProperty(String string, int i) throws JMSException {
}
public void setLongProperty(String string, long l) throws JMSException {
}
public void setFloatProperty(String string, float v) throws JMSException {
}
public void setDoubleProperty(String string, double v) throws JMSException {
}
public void setStringProperty(String string, String string1) throws JMSException {
}
public void setObjectProperty(String string, Object object) throws JMSException {
}
public void acknowledge() throws JMSException {
}
public void clearBody() throws JMSException {
}
}
private static class MockSimpleMessageConverter extends SimpleMessageConverter {
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
return new MockObjectMessage((Serializable) object);
}
};
}

View File

@@ -1,72 +0,0 @@
/*
* Copyright 2002-2006 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.jms.support;
import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
import javax.jms.Session;
/**
* Unit tests for the {@link JmsAccessor} class.
*
* @author Rick Evans
*/
public final class JmsAccessorTests extends TestCase {
public void testChokesIfConnectionFactoryIsNotSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
accessor.afterPropertiesSet();
}
}.runTest();
}
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertFalse("The [sessionTransacted] property of JmsAccessor must default to " +
"false. Change this test (and the attendant Javadoc) if you have " +
"changed the default.",
accessor.isSessionTransacted());
}
public void testAcknowledgeModeReallyDoesDefaultToAutoAcknowledge() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertEquals("The [sessionAcknowledgeMode] property of JmsAccessor must default to " +
"[Session.AUTO_ACKNOWLEDGE]. Change this test (and the attendant " +
"Javadoc) if you have changed the default.",
Session.AUTO_ACKNOWLEDGE,
accessor.getSessionAcknowledgeMode());
}
public void testSetAcknowledgeModeNameChokesIfBadAckModeIsSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!");
}
}.runTest();
}
/**
* Crummy, stub, do-nothing subclass of the JmsAccessor class for use in testing.
*/
private static final class StubJmsAccessor extends JmsAccessor {
}
}

View File

@@ -1,76 +0,0 @@
/*
* Copyright 2002-2006 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.jms.support;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.springframework.jms.support.converter.SimpleMessageConverter102;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Arrays;
/**
* Unit tests for the {@link SimpleMessageConverter102} class.
*
* @author Juergen Hoeller
* @author Rick Evans
*/
public final class SimpleMessageConverter102Tests extends TestCase {
public void testByteArrayConversion102() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = new byte[5000];
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter102 converter = new SimpleMessageConverter102();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
}

View File

@@ -1,259 +0,0 @@
/*
* Copyright 2002-2006 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.jms.support;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.test.AssertThrows;
import javax.jms.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Unit tests for the {@link SimpleMessageConverter} class.
*
* @author Juergen Hoeller
* @author Rick Evans
* @since 18.09.2004
*/
public final class SimpleMessageConverterTests extends TestCase {
public void testStringConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage message = (TextMessage) messageControl.getMock();
String content = "test";
session.createTextMessage(content);
sessionControl.setReturnValue(message, 1);
message.getText();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testByteArrayConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = "test".getBytes();
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.getBodyLength();
messageControl.setReturnValue(content.length, 1);
message.readBytes(new byte[content.length]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(content.length, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
public void testMapConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
Map content = new HashMap();
content.put("key1", "value1");
content.put("key2", "value2");
session.createMapMessage();
sessionControl.setReturnValue(message, 1);
message.setObject("key1", "value1");
messageControl.setVoidCallable(1);
message.setObject("key2", "value2");
messageControl.setVoidCallable(1);
message.getMapNames();
messageControl.setReturnValue(Collections.enumeration(content.keySet()));
message.getObject("key1");
messageControl.setReturnValue("value1", 1);
message.getObject("key2");
messageControl.setReturnValue("value2", 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testSerializableConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
Integer content = new Integer(5);
session.createObjectMessage(content);
sessionControl.setReturnValue(message, 1);
message.getObject();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(null, null);
}
}.runTest();
}
public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(new Object(), null);
}
}.runTest();
}
public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(message, session);
assertSame(message, msg);
sessionControl.verify();
messageControl.verify();
}
public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl messageControl = MockControl.createControl(Message.class);
Message message = (Message) messageControl.getMock();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Object msg = converter.fromMessage(message);
assertSame(message, msg);
messageControl.verify();
}
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(new Integer(1), "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
sessionControl.verify();
}
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(null, "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
sessionControl.verify();
}
}

View File

@@ -1,108 +0,0 @@
/*
* Copyright 2002-2008 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.jms.support.destination;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicSession;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jms.StubQueue;
import org.springframework.jms.StubTopic;
/**
* @author Rick Evans
*/
public class DynamicDestinationResolverTests extends TestCase {
private static final String DESTINATION_NAME = "foo";
public void testResolveWithPubSubTopicSession() throws Exception {
Topic expectedDestination = new StubTopic();
MockControl mockSession = MockControl.createControl(TopicSession.class);
TopicSession session = (TopicSession) mockSession.getMock();
session.createTopic(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, true);
mockSession.verify();
}
public void testResolveWithPubSubVanillaSession() throws Exception {
Topic expectedDestination = new StubTopic();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createTopic(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, true);
mockSession.verify();
}
public void testResolveWithPointToPointQueueSession() throws Exception {
Queue expectedDestination = new StubQueue();
MockControl mockSession = MockControl.createControl(QueueSession.class);
Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, false);
mockSession.verify();
}
public void testResolveWithPointToPointVanillaSession() throws Exception {
Queue expectedDestination = new StubQueue();
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
session.createQueue(DESTINATION_NAME);
mockSession.setReturnValue(expectedDestination);
mockSession.replay();
testResolveDestination(session, expectedDestination, false);
mockSession.verify();
}
private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException {
DynamicDestinationResolver resolver = new DynamicDestinationResolver();
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, isPubSub);
assertNotNull(destination);
assertSame(expectedDestination, destination);
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2002-2008 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.jms.support.destination;
import javax.jms.ConnectionFactory;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.test.AssertThrows;
/**
* @author Rick Evans
*/
public class JmsDestinationAccessorTests extends TestCase {
public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exception {
MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class);
final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock();
mockConnectionFactory.replay();
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
JmsDestinationAccessor accessor = new StubJmsDestinationAccessor();
accessor.setConnectionFactory(connectionFactory);
accessor.setDestinationResolver(null);
accessor.afterPropertiesSet();
}
}.runTest();
mockConnectionFactory.verify();
}
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsDestinationAccessor accessor = new StubJmsDestinationAccessor();
assertFalse("The [pubSubDomain] property of JmsDestinationAccessor must default to " +
"false (i.e. Queues are used by default). Change this test (and the " +
"attendant Javadoc) if you have changed the default.",
accessor.isPubSubDomain());
}
private static class StubJmsDestinationAccessor extends JmsDestinationAccessor {
}
}

View File

@@ -1,156 +0,0 @@
/*
* Copyright 2002-2008 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.jms.support.destination;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.test.AssertThrows;
import org.springframework.jms.StubTopic;
import javax.jms.Destination;
import javax.jms.Session;
import javax.naming.NamingException;
/**
* @author Rick Evans
*/
public class JndiDestinationResolverTests extends TestCase {
private static final String DESTINATION_NAME = "foo";
private static final Destination DESTINATION = new StubTopic();
public void testHitsCacheSecondTimeThrough() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver();
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
mockSession.verify();
}
public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
CountingCannedJndiDestinationResolver resolver
= new CountingCannedJndiDestinationResolver();
resolver.setCache(false);
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
assertEquals(1, resolver.getCallCount());
destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
assertEquals(2, resolver.getCallCount());
mockSession.verify();
}
public void testDelegatesToFallbackIfNotResolvedInJndi() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class);
DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock();
dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, true);
mockDestinationResolver.setReturnValue(DESTINATION);
mockDestinationResolver.replay();
JndiDestinationResolver resolver = new JndiDestinationResolver() {
protected Object lookup(String jndiName, Class requiredClass) throws NamingException {
throw new NamingException();
}
};
resolver.setFallbackToDynamicDestination(true);
resolver.setDynamicDestinationResolver(dynamicResolver);
Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true);
assertNotNull(destination);
assertSame(DESTINATION, destination);
mockSession.verify();
mockDestinationResolver.verify();
}
public void testDoesNotDelegateToFallbackIfNotResolvedInJndi() throws Exception {
MockControl mockSession = MockControl.createControl(Session.class);
final Session session = (Session) mockSession.getMock();
mockSession.replay();
MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class);
DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock();
mockDestinationResolver.replay();
final JndiDestinationResolver resolver = new JndiDestinationResolver() {
protected Object lookup(String jndiName, Class requiredClass) throws NamingException {
throw new NamingException();
}
};
resolver.setDynamicDestinationResolver(dynamicResolver);
new AssertThrows(DestinationResolutionException.class) {
public void test() throws Exception {
resolver.resolveDestinationName(session, DESTINATION_NAME, true);
}
}.runTest();
mockSession.verify();
mockDestinationResolver.verify();
}
private static class OneTimeLookupJndiDestinationResolver extends JndiDestinationResolver {
private boolean called;
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
if (called) {
fail("Must not be delegating to lookup(..), must be resolving from cache.");
}
assertEquals(DESTINATION_NAME, jndiName);
called = true;
return DESTINATION;
}
}
private static class CountingCannedJndiDestinationResolver extends JndiDestinationResolver {
private int callCount;
public int getCallCount() {
return this.callCount;
}
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
++this.callCount;
return DESTINATION;
}
}
}